user2178640
user2178640

Reputation: 95

file_put_contents not working of used from command line?

Here is the contents of a PHP file:

<? 
file_put_contents('test.txt', 'stuff');
echo 'complete';
?>

I call this test.php, it is located in /mnt. It has 777 permissions. Now I go into SSH, and execute: sudo /usr/bin/php /mnt/test.php. I receive the complete message at the bottom of my script. Now, I cd into /mnt. Text.txt is not there. What gives?

Upvotes: 0

Views: 2106

Answers (3)

anon
anon

Reputation:

Change your code to include the absolute path, like so:

file_put_contents('/mnt/test.txt', 'stuff');

Otherise, PHP will just write the file in the working directory (which is usually /home/user)

Upvotes: 0

JimiDini
JimiDini

Reputation: 2069

proper code is this:

file_put_contents(__DIR__.'/test.txt', 'stuff');
echo 'complete';

otherwise, php writes file in "current working directory", not where it is put

Upvotes: 6

Quentin
Quentin

Reputation: 943537

You haven't specified a path, so you are putting stuff into text.txt in the current working directory. That will be the directory you cd to (or your default directory for a new shell) before running sudo, not the directory the PHP script is in.

Upvotes: 1

Related Questions