nth-chile
nth-chile

Reputation: 735

PHP script only executing from command line when command is run from script's directory

I am trying to run this script from the command line:

#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile); 
?>

And it works, but only when I cd into the directory of the script and run:

/usr/local/bin/php test_script.php

This also works:

/usr/local/bin/php /home/<username>/public_html/test_script.php

but not when I leave the directory.

Upvotes: 1

Views: 2153

Answers (2)

nth-chile
nth-chile

Reputation: 735

Solved by changing line 3 of test_script.php from:

$myfile = fopen("cc.log", "a") or die("Unable to open file!");

to an absolute path:

$myfile = fopen("/home/<username>/public_html/cc.log", "a") or die("Unable to open file!");

The original script created a cc.log file in the directory from where the command was called and appended about 50 "Success" messages xD

Upvotes: 1

cosinepenguin
cosinepenguin

Reputation: 1575

A more formal answer to the original question:

Your file (test_script.php) needs to be made executable to be able to be run from anywhere. This can be done with chmod:

chmod 755 test_script.php

and results in the file being able to be run by invoking.

./test_script.php

And now, drumroll please, you should be able to run the file by invoking it like this:

./path/to/test_script.php

That dot at the front of the path should allow you to run the script as an executable without doing anything else.

Hope it helps/works!

(If it doesn't work comment and I'll boot up my Linux machine and try to replicate it!)

EDIT

Ok, that's weird that it doesn't work! Shoot! Is the PHP CLI (command line interface) installed on your Linux server? If so I would encourage you to try:

php /path/to/your/test_script.php

Hope that second suggestion helps!

EDIT 2

Aha moment number 2!!

I believe your php should be installed here: /usr/bin/php, having it in the local folder will not allow you to properly invoke it from another directory!

To download yourself a new installation of php, run

sudo apt-get install php5 libapache2-mod-php5

You will also have to change your script header to #!/usr/bin/php.

This was a good source for this third edit! I really hope it helps!

Upvotes: 0

Related Questions