Vivek Vaghela
Vivek Vaghela

Reputation: 1075

file write not working from terminal but works from browser

I have a php script, that contains some text file writing operation. Now if I execute the script from browser, by accessing it using it's url, it works fine and file is written perfectly. But when I run the same script from terminal, using command, the script runs but no file operation is performed. I am not sure, why this happens. I know it may be a silly thing or I am missing some key or anything but can't able to figure it out as of now.

Here is the command I am using

/path/to/php -f /path/to/file

Here is the code which writes to text file:

$myFile = "filename.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
$str = "file content here";
fwrite($fh, $str);
fclose($fh);

Thanks for the help.

Upvotes: 2

Views: 1132

Answers (4)

John Lawrence
John Lawrence

Reputation: 2923

This may be using different paths. For example, when run from the terminal it will be looking for "filename.txt" in the directory you are in when you run the command, whereas when running from the browser it will look in the same directory as your PHP file.

To fix this use the full path rather than just the filename for the file you are accessing.

Upvotes: 3

Aurel
Aurel

Reputation: 385

ilanco is right, this probably comes from permission issues. On Unix, one way of solving this is:

1 . First, give owneship of this file to the command-line user, and set the group to the webserver. For example, if the server is apache, execute the following command:

chown your_username:www-data filename

www-data is the default group for apache web server. This command should be run as root.

2 . Then, give the group permission to write this file:

chmod g+w filename

Upvotes: 0

vinay rajan
vinay rajan

Reputation: 361

Check for the paths, use a path from /var/www/example.com/filename.ext instead of http://www.example.com/filename.ext

Upvotes: 1

ilanco
ilanco

Reputation: 9967

This is probably a permission issue. When you run the script from the browser, the script is executed with the credentials of the webserver.

Set the correct permissions to the file/directory or run the script as the webserver's user.

Upvotes: 1

Related Questions