Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a shell script in PHP?

Tags:

I have a script in /var/www/myscript.sh which creates folders and runs the command svn update for my projects. I need to execute this script by calling it in a PHP file in the browser (i.e. Localhost/test.php). I tried using functions shell_exec() and exec() but those did not work. I ran my shell script in terminal with su www-data && ./myscript.sh and it worked. What else am I missing?

<?php $output = shell_exec("./myscript.sh"); ?> 

Update 5/4/2011:

I added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers and it works, but this is very insecure. Is there another way to do this?

like image 545
Rakesh Avatar asked May 04 '11 11:05

Rakesh


People also ask

How do I run a shell script in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix.

Is PHP a shell script?

PHP Shell is a shell wrapped in a PHP script. It's a tool you can use to execute arbitrary shell-commands or browse the filesystem on your remote webserver. This replaces, to a degree, a normal telnet connection, and to a lesser degree a SSH connection.


1 Answers

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');
like image 95
Residuum Avatar answered Sep 30 '22 17:09

Residuum