PHP script fails when called from a browser but not from CLI - php

This is driving me nuts.
I've reduced my problem to this: I have a simple file 'test.php' that invokes a php file (this is from a bigger application, so in fact we need to execute many php scripts from a main script):
<?php
exec("php /var/www/setActive.php 273 1 2>&1",$arO,$nO);
echo $nO.'|'.implode(',',$arO);
The original path for setActive.php is way longer, I shortened it for this example.
Now, if I try:
[root#stg]# sudo -u apache php test.php
I get:
0|
Great, this means the setActive.php script ran smoothly.
Now, if I try it from a browser or from curl:
[root#stg]#curl http://my.url/path/test.php
This is what I get:
1|Could not open input file: /var/www/setActive.php
I already reviewed all the permissions. Apache user has access to all directories and files.
This was working ok in another server. I reviewed the php.ini files and there is no difference between them.
Maybe is a option that I'm not seeing, or an apache config option. I'm ran out of ideas.
Please help me!
Thanks in advance.
I have Linux, Cent OS. PHP 5.3.23

If permissions etc.. are all ok, possibly the apache config. in your setup has the 'ChrootDir' set:
http://httpd.apache.org/docs/2.2/mod/mpm_common.html#chrootdir
This uses the syscall chroot() and the view for '/' dir for that process starts from this setup dir, and hence everything should be relative to it.

Related

Why is PHP not recognizing a program in the Windows System PATH when I use it with Apache?

In my local development environment, I have Apache and PHP installed on Windows 7. I'm calling 7-Zip from my PHP program with exec. I tried at first with
exec('7z a example.zip example.pdf');
but it didn't create the zip file. After checking the Apache error log, I found
'7z' is not recognized as an internal or external command, operable program or batch file.
After changing the exec to include the full path to 7-Zip.exe, it worked.
exec('"C:\\Program Files\\7-Zip\\7z" a example.zip example.pdf');
But C:\Program Files\7-Zip is included in my Windows system PATH. The same PHP code works from the command line without using the full path.
php -r "exec('7z a example.zip example.pdf');"
Why is it requiring the full path when I use it with Apache?
An important point which I neglected to include when I originally posted this question is that I am already able to use exec() to call other programs included in the Windows System PATH without referring to them by their full paths.
Another point which I did not mention originally because I did not realize its relevance was that 7-Zip had been added to the PATH only recently, and I had restarted the Apache service after adding it.
I've WAMP installed on windows 8 and after reading your question I decided to test a couple of things.
Running echo exec('whoami'); echoed:
nt authority\system
This confirms what #Barmar said, Apache isn't running under the same user as you, so, the PATH is different.
I decided to stop Apache and start it manually under the Administrator account.
Then I tried:
echo exec('whoami');
Which outputted:
computername\administrator
I assumed that now the exec would work with PATH and tried:
echo exec('adb'); //android adb tool is on my PATH
Surprisingly, despite the fact Apache was running with the same user as me, the PATH still didn't work. I've no idea why this is happening and if someone has a clue please comment below.
I managed to use the PATH (using the Administrator account) with the following code:
https://stackoverflow.com/users/171318/hek2mgl
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C 7z a example.zip example.pdf", 0); // 0 invisible / 1 visible
I didn't test the code below, but you can try setting the PATH under the Apache Service account (nt authority\system), and then use the command, i.e.:
echo exec('set PATH=%PATH%;C:/path/to/7z');
echo exec('7z a example.zip example.pdf');
I believe the path will still be valid between restarts.
Update:
this answer, may help you setting the PATH for the account nt authority\system.
The Local System user's personal environment variables are specified
at "HKEY_USERS.DEFAULT\Environment". The machine-wide environment
variables are specified at
"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment". The former isn't really easily accessible from
anywhere except the registry, but the latter is accessible from the
"Environment Variables" dialog on the "Advanced" tab of the "System
Properties".
For future users, the correct way to set the Apache PATH is:
You can use setEnv in .htaccess or putenv in PHP code to set
$PATH
Credit goes to hek2mgl
I just figured out what was causing this problem. It was actually unrelated to my original assumption.
I remembered seeing PATH information in phpinfo(), so I looked at that. In the "Apache Environment" section it did show all of the PATH except the path to 7-Zip, which I had just added to the system PATH recently. So apparently it DOES seem to have access to that path, but it wasn't using the current version of it. Why not?
Normally I would think I had just forgotten to restart Apache after updating the path, but I'd restarted it repeatedly while trying to figure this out. But apparently restarting Apache does not refresh this value. I had to stop it and then start it. Then the 7-Zip path showed up in PATH in phpinfo, and I was able to change my program back to using plain 7z.

PHP date and paths when running a batch file in windows

I am facing a puzzle, im testing some scripts on my wamp installation. When i do a echo date('d) and i run the script from the browser i see the correct week day, by example, lets say it echo 'Mon', but.. when i execute it from a batch file, the echo shows the next day, by example 'Tue', why this can be happening? I have the correct timezone in my php.ini the windows clock as well, i dont have a clue why this is happening. In the same puzzle, i have a path to a dbconnect file, again, from browser it run ok, but from the batch file it dont find the included path, i solved it writing the full windows path C:/path/to/file.php but i dont understand why, the include is done by the php file executed by the batch file, so the path should be ok right?
If someone can share some lights i would appreciate it.
In WAMP the CLI uses a separate php.ini file in the PHP installation directory (e.g. C:\wamp\bin\php\php5.3.13) rather than the one under the Apache installation so check the settings in that file for running PHP on the command line.
Using php through the browser is using the CGI/FPM version and with your command line it is the CLI version. CLI and server (cgi/fpm) use different php.ini-files. On cli type
php --ini
To find where your ini file is and correct it.

PHP external program call

My setup is as follows: Windows 7, XAMPP with Apache and PHP enabled I have a PHP script in which I call an external program to do run a conversion. This external program is an EXE file, which requires 3 attributes:
The source file
The destination file
Additional flags (conversion type etc)
When I use the command line tool built into XAMPP to execute my script, everything works fine. But when I use the exec() function in my PHP script, no output file is created. I'm pretty sure the conversion is actually happening (it takes about 5 seconds, about the same time it takes to run the PHP script).
I think it's a permissions thing, so I already moved the EXE file to the same folder as my PHP file and adjusted the permissions of the entire folder (I granted all permissions to all users). I also disabled the Windows UAC and tried to put the command in a BAT file. The file just is not created.
Any help or tips would be greatly appreciated!
My PHP code is as follows:
exec('c:\converter.exe c:\src.txt c:\dst.txt -f', $output);
print_r($output);
When I print out $output, the array turns out to be empty. When I put the exact same command in Command Prompt, the code works like a charm (no syntax errors). I use absolute paths as well.
Try to copy your executable file in same folder as your application.
try
exec("script.exe src.txt dst.txt", &$output);
echo $output;
also, do not forget to use escapeshellcmd() to add some security to your application.
Thank you very much for your input! As it turns out, it was Windows issue caused by the 'Interactive Services Detection' feature. Apache was running as a system service, which prevented calls to external programs (with a GUI). I disabled the run-as-service feature in XAMPP, which solved the problem. A more thorough explanation can be found here: http://php.net/manual/en/book.exec.php

PHP script on my MAMP testing server can't access node_module: less

I'm trying to configure my local development environment to read .less files so that I can edit .less files during development and only convert to .css when it's time to go live. Make sense?
I'm running MAMP as my local testing server. I'm following the instructions I found here:
http://programming-perils.com/155/parse-less-files-on-the-fly-and-serve-them-as-css/#comment-920
In short, the plan is to use an htaccess file catch requests to .css files and direct them to a PHP script which compiles the .less file of same name and returns the css code.
Everything seems to be working from the command line. I can compile a .less file from the command line and it spits out the css. I know my rewrite rule is working because I can type the url into a browser and see the output of my php script. For example, if my PHP script calls echo shell_exec('pwd'); I will see a path printed in the browser.
THE PROBLEM is that I can't get the less script to run unless I SSH to the localhost as root. When I exit SSH and run the command I get "Permission denied". I suspect this is what happens when my PHP script tries to call this... so it's returning nothing.
I guess the question boils down to how can I get my PHP script to run the less compiler?
UPDATE! I solved the problem...
It turns out that the less command (path/path/lessc) needed to be sudo'ed. PHP wasn't doing this, so the shell_exec() command wasn't returning anything. That's why my echo statements DID work.
There are a lot of ways to sidestep this, but I determined that editing the list of sudoers with sudo visudo was the best for my purposes. There was a lot of helpful tips on this post. Through trial and error, I figured out that PHP uses the www-data account. Adding this line fixed my problem:
www-data ALL=(ALL) NOPASSWD: /var/root/node/npm/node_modules/less/bin/lessc
Something to remember is that you STILL have to add sudo to the command that gets fed to shell_exec(). Hope this is helpful to someone else.
Maybe it would be easier if you'd use the PHP implementation of lesscss: lessphp
It turns out that the less command (path/path/lessc) needed to be sudo'ed. PHP wasn't doing this, so the shell_exec() command wasn't returning anything. That's why my echo statements DID work...
See my edits to the question above.

How can I fix the Permission error when I call session_start()?

when I uploaded the script to the server I got this error
Warning: Unknown: open(/tmp/sess_58f54ee6a828f04116c2ed97664497b2, O_RDWR) failed: Permission denied (13) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
The error appeared when I call session_start(), although I set the permission of /tmp folder to 777.
Change session path where you can write data or contact server administrator about /tmp problem
http://php.net/manual/en/function.session-save-path.php
you will need to change your session.save_path php.ini directive
You can do that using session_save_path
If you have SSH access, here is how to correct the permission and ownership
sudo chown -R NAME_OF_USER /tmp
Replace NAME_OF_USER by the user under which runs php. You can find it by simply putting these lines in a php file:
$processUser = posix_getpwuid(posix_geteuid());
print $processUser['name'];
exit;
Check that you're not running into diskspace issues. If all the permissions are correct (and 777 ought to do it for you), then you might still get this error (for some versions of PHP and Apache) if there isn't enough space to write to the disk.
I had this problem in the following situation:
I filled some session vars with PHP
While the session was still active, I changed from PHP 5.4 to 5.3 on my host.
Reloading the page gave the error, described above.
Reset the PHP version to 5.4 again.
Used session_unset(); and session_destroy(); to clean the current session.
Changed the PHP version back to 5.3.
Now it works again.
Conclusion: For an irrelevant reason I had to change my PHP version, and while switching with sessions alive, the sessions get corrupted.
I realize that this is an old post, however I just ran into this problem, and found an easy solution.
For me, the issue was happening with one of my websites deployed locally. I hadn't tried accessing the websites using other browsers, but it was happening every time I tried to access this site via Chrome. I decided to go into the Chrome developer tools, under the application tab -- and clicking "Clear Storage". Voila -- everything is working like magic again.
Hope this helps someone else!
Additionally, you may want to use ini_set('session.save_path', '/dir/here'); assuming you have access to this function. The other ways suggested are valid.
I've just had exactly the same problem with one of my PHP scripts and I was like what did I break 'cos it worked perfectly the day before and I'm running it from my own local Puppy Linux machine so it's not even a host or anything.
The only thing I'd been doing before that was trying to get Java to work in the web browser, so some how I'd managed to get Java to work but broke PHP - oops!
Anyway I did remember that whilst trying to get Java to work I had deleted the contents of the /tmp folder to wipe anything out that may be causing a problem (it actually turned out with Java I was using the old plugin oij with the new Firefox)
To solve this problem I opened up Rox File Manager, went to the / folder and right clicked on the tmp folder -> Mount Point 'tmp' and clicked properties.
I noticed the permissions were set as Owner - Read, Write, Exec, but Group and World were only set at Read and Exec and not Write. I put a tick in Write for both Group and World and now PHP works fine again.
I don't know at what point the permissions for tmp must have changed but for PHP to use them it must be set to have Write permissions.
Add following line
ini_set('session.save_path', getcwd() . '/tmp');
before
session_start();
if you are using Apache web server, the quick fix is to go to your command line and type:
open /etc/apache2/
then from the window opened, open the file called httpd.conf and search for User or Group change these 2 lines to:
User _www
Group _www
This is because you want your server to have permission to your systems directories, especially you want to change the User or you can leave your Group to either staff or admin.
I had the same problem of permission, but on /var/lib/php/session/.
To fix it, I deleted the file and restarted php-fpm.
rm -rf /var/lib/php/session/sess_p930fh0ejjkeeiaes3l4395q96
sudo service php5.6-fpm restart
Now all works well.
For me the problem seems to be a WHM bug!
I have a bunch of add on domains and all work fine but with a subdomain it brings this error.
Strange thing but if I use the full URL with the main domain it works fine:
main-domain.com/my.subdomain.com
If I use the subdomain directly it brings "Permission denied (13)":
my.subdomain.com
The thing is all addon domains root is:
/home/xx/
But for my subdomain, don't know why, the root is: (I shouldn't have access to that dir)
/
So it´s really trying to reach: /tmp instead of /home/xx/tmp
Which also exists but don't have the right permissions
To clarify this are examples of the whole path:
/home/my-account/public_html
/home/my-account/tmp
/tmp
The workaround I used was:
session_save_path('/home/my-account/tmp');
session_start();
Using PHP 5.6 I had already used session_save_path() to point to a directory within the domain's structure. It worked fine until I upgraded to PHP 7.0, at which time I received the noted error. At PHP.net I found several comments that indicated assigning a direct path didn't always work, so I used their suggestion.
session_save_path(realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
worked perfectly. Remember to change /../session to the relative location of your actual session directory.
If :
session.gc_probability > 0
session files are created by different user(s) (e.g. root and apache).
session files are all stored in the same place (e.g. /var/lib/php/session)
Then you'll see this error when e.g. the Apache PHP process attempts to run garbage collection on the session files.
Fixes :
Reconfigure PHP so gc_probability is 0, and have a cron job removing the old/stale file(s).
Have each different user save their session files in separate place(s) (session_save_path() etc).
I initially had this issue due to nginx owning the /tmp location and php-fpm was running under 'apache' user and group due to the www.conf. I swapped out the user/group in that file and then it worked ok. You may want to check <?php echo exec('whoami'); ?> to verify.
In my case the problem was SELINUX not allowing this.
A helpful command to get suggestions on how to fix this:
sealert -a /var/log/audit/audit.log
If you want to rule out SELINUX, try disabling it for a moment. If that fixes the issue then that is the problem.

Categories