require_once doesn't work in command line - php

php /home/test9/public_html/degerlendir/test-4567.php "var1=18&var2=22"
I need to run one page at background with cron job. I tested my code with command at above. But I get this error:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/extensions/no-debug-non-zts-20100525/imagick.so' - /usr/lib64/extensions/no-debug-non-zts-20100525/imagick.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning: require_once(../config.php): failed to open stream: No such file or directory in /home/test9/public_html/degerlendir/test-4567.php on line 2
PHP Fatal error: require_once(): Failed opening required '../config.php' (include_path='.:/usr/lib64/php') in /home/test9/public_html/degerlendir/test-4567.php on line 2
The problem is page doesn't include config.php in the parent directory. The page working in browser normally. I tried to use different require_once variations like require_once ($_SERVER['DOCUMENT_ROOT']."/config.php"). I could not get it to work.

from the command line there is no $_SERVER['DOCUMENT_ROOT']. That one is only available from the http-server (Apache).
The working directory will not be automatically set. If you prompt is currently at /some/path/ the script will try to find config.php in /some/config.php.
Try cd to the current path by using __DIR__ in the start of your script
<?php chdir(__DIR__); ?>

Cron jobs always take full path of the included file from your root.
/home/test/.../your-file

In your cron job, you need to cd to the correct working directory to allow your PHP file to find it's includes. I do this by creating small shell scripts, and run the shell scripts from cron:
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd ${DIR}
php test-4567.php
exit 0
This also gives you the ability to do some useful things like checking to see if the script is already running to make sure you don't spin up multiple threads if that's something you want to avoid.
#!/bin/bash
FIND_PROC=`ps -ef |grep "php test-4567.php" | awk '{if ($8 !~ /grep/) print $2}'`
# if FIND_PROC is empty, the process has died; restart it
if [ -z "${FIND_PROC}" ]; then
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd ${DIR}
php test-4567.php
fi
exit 0

Related

Include in remote script fails when running it via SSH

I run a script locally, which when finished makes an exec call to a script on a remote server.
exec("ssh user#server.com \"php /full/path/to/script.php\"", $output, $return);
It presents me with this error:
PHP Warning: require(../resources/vendor/autoload.php): failed to open stream: No such file or directory in /full/path/to/script.php on line 3
I have tried charging the required script to it's full path with no success. Any ideas?
Because PHP sets CWD (current working directory) to where you are after SSH login (presumably the user home folder) and references to includes in the PHP file are interpreted as being relative to CWD. You should change directory to the root of your project:
exec("ssh user#server.com \"cd /full/path/to/; php script.php\"", $output, $return);

PHP Script unlinks files interactively in browser, but not as cPanel cron job

The following execution syntax actually runs in cron job:
/usr/local/bin/php -q /home/pbjwbh0mgv9o/public_html/buildlistings.php
Yet I get the following in my error_log:
[05-May-2018 21:53:00 UTC] PHP Warning: unlink(property_a.xml): No such file or directory in /home/pbjwbh0mgv9o/public_html/buildlistings.php on line 63
[05-May-2018 21:53:05 UTC] PHP Warning: unlink(property_map.xml): No such file or directory in /home/pbjwbh0mgv9o/public_html/buildlistings.php on line 215
Once again the following part of script executes perfectly in browser, and attached below is screenshot of directory:
unlink('property_a.csv');
unlink('property_a.xml');
unlink('property_map.xml');
Am I formatting the cron job command incorrectly, or missing something within my script related to Linux?
When you execute the script via the web server, the CWD (current working directory) is what you expect.
When cron executes that job, it's not happening from the same location. You need to make sure it calls cd to change to wherever you expect the files to be.
Edit:
Here's an example for your cron job:
cd /home/pbjwbh0mgv9o/public_html && /usr/local/bin/php -q buildlistings.php

Does PHP support process substitution?

I've trying the following examples such as:
$ php -r 'require_once($argv[1]);' <(echo "hello")
or:
$ php -r 'file_get_contents($argv[1]);' <(echo "hello")
both fails like:
PHP Warning: require_once(/dev/fd/63): failed to open stream: No such file or directory in Command line code on line 1
PHP Warning: file_get_contents(/dev/fd/63): failed to open stream: No such file or directory in Command line code on line 1
or:
$ php -r 'file_get_contents($argv[0]);' < <(echo "hello")
which fails with:
PHP Fatal error: require_once(): Failed opening required '-' (include_path='.:/usr/share/pear:/usr/share/php') in Command line code on line 1
The above attempts were inspired by drush command, for example:
$ drush --early=<(echo print 123';') ""
[warning] require_once(/dev/fd/63): failed to open stream: No such file or directory preflight.inc:58
where I could inject the dynamic PHP code from the file descriptor (without creating a separate file each time) in order to execute the code before bootstrapping the main code.
Other similar command tools works correctly:
$ cat <(echo "hello")
hello
or:
$ python -c "import sys; print sys.stdin.readlines()" < <(echo "hello")
['hello\n']
I've found this PHP bug and this one, but these has been fixed long time ago and I'm using 5.6.22.
Is there any way that I can trick PHP into reading data from the process substitution (to read from file descriptor , e.g. /dev/fd) when called from CLI, by using some simple one-liner?
The error message gives a good hint: PHP cannot find the given file.
But wait, what file? Well, let's remember what process substitution is:
Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.
And so you see when you print the argument you are providing this way:
$ php -r 'print $argv[1];' <(echo "a")
To me it returns the following temporary file:
/dev/fd/63
So yes, you can use process substitution with PHP, but not for this.
If what you want is to use the output of the command as an argument, just use $() to expand it:
$ php -r 'print $argv[1];' "$(echo "hello man")"
hello man

Execute php script without permission from web

I'm trying to execute a php script but i'm having this kind of errors:
Warning: file_put_contents(/sys/class/gpio/export): failed to open stream: Permission denied in /home/pi/php-gpio/src/PhpGpio/Gpio.php on line 99
Warning: file_put_contents(/sys/class/gpio/gpio17/direction): failed to open stream: Permission denied in /home/pi/php-gpio/src/PhpGpio/Gpio.php on line 103
I've tried to set up the permission in the $ sudo visudo like this:
www-data ALL=NOPASSWD: path/to/my/script
or
www-data ALL=NOPASSWD: ALL
but is not working, i'm able to execute this script only with sudo form the command line!
Thanks in advance!
If you using in your computer, you must change the default directory permission:
$ sudo chmod -R +w /sys/class/gpio/export
else if you run code in a server, in server panel and in section files (e.g. CPanel) change permission and add write right.
Another way is running exec() command:
<?php
exec('chmod -R +w /sys/class/gpio/export');
?>
However, php should have exec right and running with root!
I recently published a project that allows PHP to obtain and interact with a real Bash shell (as root if requested), it solves the limitations of exec() and shell_exec(). Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd('/sys/class/gpio/export');
$return2 = $shell->exeCmd('/sys/class/gpio/gpio17/direction');
//the return will be a string containing the return of the command
echo $return1;
echo $return2;
In terms of security it is far better than running apache as root, or the wide open sudo permissions in your question. But letting PHP anywhere near root is always tricky.
The project i built achieves a root bash shell in one of 2 ways:
1) You allow apache the right to sudo python.
OR
2) You pass root credentials to the object every time you need a shell with root setup.
Pick your poison. :) Read the documentation.

Not able to run wkhtmltopdf commad through shell_exec() function in php but same command works on command line

I'm in trouble and that much confused about a php shell_exec command.
When the command is execute by PHP I have no error but the execution fails. If I use exactly the same command from a terminal it works.
Here's the command :
/usr/bin/wkhtmltopdf --lowquality --dpi 300 --encoding utf-8 "/tmp/knplabs_snappyxa9otq.html" "/tmp/knplabs_snappyv3pD7h.pdf"
When I lauch this from a terminal :
$ /usr/bin/wkhtmltopdf --lowquality --dpi 300 --encoding utf-8 "/tmp/knplabs_snappyWG9XTd.html" "/tmp/knplabs_snappyv3pD7h.pdf"
Loading page (1/2)
Printing pages (2/2)
Done
But from my php script :
// Construct the previous command
$command = $this->buildCommand($url, $path);
../..
shell_exec($command);
../..
$content = file_get_contents($path);
../..
I've test the output of shell_exec, it's empty.
The log :
Warning: file_get_contents(/tmp/knplabs_snappyv3pD7h.pdf): failed to open stream: No such file or directory in /*****/lib/snappy/SnappyMedia.class.php on line 64
No permission pb in the /tmp directory :
$ ls -la /tmp
total 448
drwxrwxrwt 16 root root 4096 mars 12 21:51 .
../..
I've tried avec the PHP exec() function to get error informations, I just get an "1" error code in return_var and nothing in output.
For information this issue appear on my test server, my desktop computer but not on my notebook. All the 3 are with sames PHP, Apache, Mysql versions.
I don't understand anything ...
Thanks for any help, I'm loosing my mind.
David.
I've found the solution here : Executing wkhtmltopdf from PHP fails
Thanks to Krzychu.
First to get information from the shell_exec command add " 2>&1" at the end of the command. In that way you will get information in return of the command :
$no_output = shell_exec($command);
echo $no_output; // nothing
$output = shell_exec($command . ' 2>&1');
echo $output; // in my case : "cannot connect to X server"
The solution :
Not use the wkhtmltopdf ubuntu package (0.9.9-4)
Use the official package from the Wkhtmltopdf download page
So no need to install xvfb ! (I've seen this advice many times)
Looks like a user's permissions issue.
When you run the command from the terminal, it is the user account, currently used, which does have the right permissions, to run a command in /usr/bin, and execute the specific file.
When you run it from the php script, it is the http server account on your system, which needs the permission to execute the file in /usr/bin. Usually this is the apache user.
How you should setup permissions depends on your system. Just remember that what is allowed for apache, is allowed for anyone accessing your http server.
I have had this problem for ages and adding . ' 2>&1' after the $command has somehow solved the problem.
this:
$output = shell_exec($command . ' 2>&1');
instead of:
$output = shell_exec($command);
No idea why but it works and I'm grateful.
Is it a shared hosting? It seems like shell_exec is a restricted function. Try running error_reporting(E_ALL); ini_set('display_errors', 1); before calling shell_exec.
I stumbled upon the same Problem, in my case an absolut Path in the exec Command like /var/www did not work, I had to use relative Paths from the point where I executed the php File.
I also wanted to notice, that it did not work using shell_exec, however it worked using normal exec command, not sure wheres the difference here.

Categories