Boston Linux & UNIX was originally founded in 1994 as part of The Boston Computer Society. We meet on the third Wednesday of each month at the Massachusetts Institute of Technology, in Building E51.

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Discuss] php question. change directory to executing script.



Eric Chadbourne <sillystring at protonmail.com> writes:

> Hi All,
>
> I have a little function that needs to delete some files.  I don't
> want it to delete them from the directory of my user, but in the
> directory of the script.
>
> For example from terminal:
>
> cd $HOME
> php /path/to/script/foo.php  // will execute foo in home
>
> But I want it to execute foo in /script.
>
> So in the function I told it to change working directory to script path.
>
> chdir(dirname(__FILE__));
>
> Am I missing something or is this OK?  Is it evil to do such a thing?

Could your script ever be a symlink? Seems to me I've seen this go wrong
or at least get confusing (yes, it seems not uncommon to want to run
things in the script's directory - each place I've worked at the last 20
years has done it, both under Linux and under Windows) when symlinks are
involved.

What about passing an argument with the directory to execute in. Then at
least you have outside control. It's kind of the moral equivalent of a
local (or really a function argument) vs. global variable, in the sense
that your script's directory is like a global in that it comes from the
surrounding environment and isn't stated explicitly vs. a command
argument which would be more like (and end up in) a local variable.

It it's clumsy to run that way you can always use an alias.

On the other hand if its your own thing make it as simple as works for
you. Maybe you don't care about symlinks, and it's small enough that
"global variables" are appropriate. I just recall at the Windows job
when the program got big new programmers were a bit puzzled about which
directory it ran in and where it found its configuration files. It was
yet another bit of annoying incidental knowledge to be passed on that
the "working directory" wasn't the normal working directory but the
program's directory, or subdirectories relative to that.

-- 
Mike Small
smallm at sdf.org



BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org