如何从命令行PHP写入文件?

I'm trying to write some command line PHP - is there a trick to writing to a file from the command line using PHP? The file is called testcl.php and I execute it with:

/usr/bin/php -f /var/www/html/media/testcli.php

$myFile = "test.txt";
$fh = fopen($myFile, 'a');
fwrite($fh, "batman2");
fclose($fh);
echo "batman";

The batman echo statement works, so I know the file is running - but it's not writing to test.txt for some reason. If I access testcli.php it writes text.txt successfully - so I think I'm missing some trick.

I suspect you have a CWD issue: test.txt is a relative path, so it will be calculated for wherever you stand while calling the script - this might be differet between you on the shell an the webserver. Try

$myFile=dirname(__FILE__).'/test.txt';

It might also be a permission problem: Make sure, you have write privileges for the websrver directory.

I would cd to /var/www/html/media/ before running the php code. Also make sure the current user can write to that directory/

It is probably a permission issue. Try using:

sudo /usr/bin/php -f /var/www/html/media/testcli.php

Two possibilities:

  • When you run PHP from the web server, it always runs with the current directory set to the directory containing the script. When you run PHP from the command line, the working directory is left alone. Check your cwd for the output file.

  • If that file doesn't exist, it's possible that the user you're running php-cli doesn't have permissions to write to its current directory.

Relative to OP question. For example if we have two files one is log.php that writes to log.txt file and both are located in C:/MAMP/htdocs.Log.php contains:

<?php
 $txt = "user id date";
 $myfile = file_put_contents(dirname(__FILE__).'/logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
echo dirname(__FILE__);
?>

This will find log.txt file in the directory where log.php is being executed:

php -f C:/MAMP/htdocs/log.php

** Here php is set as environment variable else one can use C:\MAMP\bin\php\php7.1.7\php.exe

** set php7.1.1 to your php version

** This example is for MAMP and can be used on other local servers