They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

Answer from Kalium on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ php-shell_exec-vs-exec-function
PHP shell_exec() vs exec() Function - GeeksforGeeks
July 11, 2025 - In PHP, shell_exec() and exec() are functions used to execute external commands from within a script.
Top answer
1 of 5
220

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

2 of 5
174

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

+----------------+-----------------+----------------+----------------+
|    Command     | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system()       | Yes (as text)   | Last line only | Yes            |
| passthru()     | Yes (raw)       | No             | Yes            |
| exec()         | No              | Yes (array)    | Yes            |
| shell_exec()   | No              | Yes (string)   | No             |
| backticks (``) | No              | Yes (string)   | No             |
+----------------+-----------------+----------------+----------------+
  • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
  • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
  • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add "2>&1" to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.
Discussions

python - What is the difference between running a script from the command line and from exec() with PHP? - Stack Overflow
I'm trying to run a Python script using exec() from within PHP. My command works fine when I run it directly using a cmd window, but it produces an error when I run it from exec() in PHP. My Python More on stackoverflow.com
๐ŸŒ stackoverflow.com
Running a Python script from PHP - Stack Overflow
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl) and/or must be "executable". Also all commands into .py file must have correct privileges. ... Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What is different between exec(), shell_exec, system() and passthru() functions in PHP? - Stack Overflow
system return false when there was an error. Does this mean when the exit code is !== 0 it will return false? So I do not have to actually check the $retval if I just want to check of the command suceeded? 2021-01-22T09:53:35.793Z+00:00 ... passthru is used for returning binary data instead of ascii. A typical example is where an image manipulation program is returning an image instead of text data. See PHP - exec... More on stackoverflow.com
๐ŸŒ stackoverflow.com
shell - PHP shell_exec() vs exec() - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.system.php
PHP: system - Manual
Finally, I found a comment in a blog by a certain amazing guy that solved my problems. Adding the string ' 2>&1' to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!
Top answer
1 of 11
213

Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

In PHP use shell_exec function:

Execute command via shell and return the complete output as a string.

It returns the output from the executed command or NULL if an error occurred or the command produces no output.

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

Into Python file test.py, verify this text in first line: (see shebang explain):

#!/usr/bin/env python

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

This applies when you run it in Unix by making it executable (chmod +x myscript.py) and then running it directly: ./myscript.py, rather than just python myscript.py

To make executable a file on unix-type platforms:

chmod +x myscript.py

Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl) and/or must be "executable". Also all commands into .py file must have correct privileges.

Taken from php manual:

Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.

2 of 11
30

I recommend using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 
Find elsewhere
Top answer
1 of 2
93

exec โ€” Execute an external program

system โ€” Execute an external program and display the output

shell_exec โ€” Execute command via shell and return the complete output as a string

so if you don't need the output, I would go with exec.

Further details:

  • http://php.net/manual/en/function.exec.php
  • http://php.net/manual/en/function.system.php
  • http://php.net/shell_exec
2 of 2
0

Just expanding on the existing answer with examples:

All functions will attempt to execute the command almost as if from the terminal. The main difference is in the output and error handling:

exec()

Outputs to var only the last line; Outputs array with each line to 2nd arg; Outputs result_code to 3rd arg -- any non-zero result_code is an error. Here's a list of result_codes

$last_line = exec('pwd;ls -alh', $all_lines_array, $result_code);
echo "LAST_LINE: $last_line";
print_r($all_lines_array);
echo "RESULT_CODE: $result_code";

/*
LAST_LINE: -rw-r--r-- 1 ubuntu psacln 1.2K Feb  7 03:43 index.php 

Array
(
    [0] => /var/www/vhosts/example.com/httpdocs/dir/subdir
    [1] => total 20K
    [2] => drwxr-xr-x 3 root         root   4.0K Feb  7 03:17 .
    [3] => drwxr-xr-x 7 ubuntu psacln 4.0K Feb  6 21:46 ..
    [4] => -rw-r--r-- 1 ubuntu psacln  550 Feb  6 22:45 .htaccess
    [5] => drwxr-xr-x 2 ubuntu psacln 4.0K Feb  7 00:22 cache
    [6] => -rw-r--r-- 1 ubuntu psacln 1.2K Feb  7 03:43 index.php
)

RESULT_CODE: 0
*/

shell_exec()

Outputs single or multiline plain text to var. Takes only 1 arg -- the command

$plain_text = shell_exec('pwd;ls -alh');
echo $plain_text;

/*
/var/www/vhosts/example.com/httpdocs/dir/subdir
total 20K
drwxr-xr-x 3 root         root   4.0K Feb  7 03:17 .
drwxr-xr-x 7 ubuntu psacln 4.0K Feb  6 21:46 ..
-rw-r--r-- 1 ubuntu psacln  550 Feb  6 22:45 .htaccess
drwxr-xr-x 2 ubuntu psacln 4.0K Feb  7 00:22 cache
-rw-r--r-- 1 ubuntu psacln 1.2K Feb  7 03:43 index.php
*/

system()

Echos single or multiline plain text. No need for echo system();. result_code is the same as exec()

system('pwd;ls -alh',$result_code);
echo "RESULT_CODE: $result_code";
/*
/var/www/vhosts/example.com/httpdocs/dir/subdir
total 20K
drwxr-xr-x 3 root         root   4.0K Feb  7 03:17 .
drwxr-xr-x 7 ubuntu psacln 4.0K Feb  6 21:46 ..
-rw-r--r-- 1 ubuntu psacln  550 Feb  6 22:45 .htaccess
drwxr-xr-x 2 ubuntu psacln 4.0K Feb  7 00:22 cache
-rw-r--r-- 1 ubuntu psacln 1.2K Feb  7 03:43 index.php

RESULT_CODE: 0
*/

Backtick quotes ``

Basically, alias for shell_exec(). Outputs single or multiline plain text to var

$plain_text = `pwd;ls -al`;
echo $plain_text;

/*
/var/www/vhosts/example.com/httpdocs/dir/subdir
total 20K
drwxr-xr-x 3 root         root   4.0K Feb  7 03:17 .
drwxr-xr-x 7 ubuntu psacln 4.0K Feb  6 21:46 ..
-rw-r--r-- 1 ubuntu psacln  550 Feb  6 22:45 .htaccess
drwxr-xr-x 2 ubuntu psacln 4.0K Feb  7 00:22 cache
-rw-r--r-- 1 ubuntu psacln 1.2K Feb  7 03:43 index.php
*/

exec() appears to be most versatile as you can iterate over the array of lines, get the last line only, and the result_code.

shell_exec() and backticks `` are great if plain text works better for you.

system() echos automatically :(

๐ŸŒ
TREND OCEANS
trendoceans.com โ€บ home โ€บ blog โ€บ topic โ€บ developers โ€บ how to run a python script from php
How to Run a Python Script from PHP - TREND OCEANS
January 2, 2025 - Otherwise, you may get sh: 1: ./system.py: Permission denied. To avoid this, execute the following line of code, then run the PHP file to execute the inner script. ... Thatโ€™s all for this guide, where I showed you how to execute or run Python scripts in PHP using the shell_exec function with two different examples.
๐ŸŒ
Reddit
reddit.com โ€บ r/phphelp โ€บ shell_exec() exec() passthru() system() - which??
r/PHPhelp on Reddit: shell_exec() exec() passthru() system() - Which??
March 24, 2015 -

Hey all,

I am trying to build something at the moment, which so far is going very well! However what I am trying to achieve is a way to guarantee the response from a shell_exec() call to be echoed out in PHP.

To explain a little, I am building a solution where I can add an abstraction layer for security purposes on top of any command line calls you may require. This is achieved by having a command object which will interface with a "library" object and invoke pre-defined methods which will of course feed you back the output of said command to do with as you please.

An example of what I am doing, using sox to turn a stereo audio track into a mono track :

$command = new Command(); $command->call("sox")->addSub("mono", "track.wav")->execute(); if($command->response != "") { // Do action }

What this does is load in the "sox" library as an object and invokes the "mono" method on the library object. Using the argument "track.wav". This way I can name my most used commands to something memorable instead of having to use the following shell_exec("sox track.wav -c 1 track.wav")

This is just a simplified version of what you can do. However I am having issues with certain libraries and echoing out the response, so am looking for a way to guarantee this.

๐ŸŒ
W3Docs
w3docs.com โ€บ php
PHP exec() vs system() vs passthru()
The exec(), system(), and passthru() functions are all used to execute external programs in PHP.
Top answer
1 of 3
2

Everything is dangerous (even a fork) if you don't know how to use it. Well, you have several options:

  1. Standard: Running the Python interpreter in PHP with exec() / shell_exec(), etc. Plus there will be a small latency and ability to run Python compiled byte-code, so performance wins here.

  2. Non-standard: If you are concerned a lot about security issues at hand I suggest better to insert Python commands into some batch table and run these regularly with the CRON scheduler. After execution, fetch results with PHP. In this way PHP / Python execution will be de-coupled and you will have a better control on how / when to execute Python scripts.

  3. Non-standard (avoid at all costs): Your mentioned project is moved to Git at php-python. It simply starts a new Python server on port 21230 and waits for Python commands from a PHP scripts. Now, THESE solutions are a most dangerous one, because of the additional opened port in the web server, which is a big headache to administrators and thus highly not recommended.

  4. The last option is to question an assumption that Python is needed at all in web development of PHP. The more different languages in the company IT farm - the harder it will be to maintain all sources and harder to beat time-to-market of new features / bugs fixing. So before considering execution of Python script(s), at first think about re-writing them to plain PHP.

    You can do it automatically, but these type of translators are very error-prone and incomplete - for example this one doesn't supports imports. (What the hell? Python without imports is like a bread without a flour). The second option is to learn Python and re-write code at hand into PHP. Or simply get a customer requirements and code these into PHP. Everything that can be done in Python, can be done in PHP too (at least in web development perspective).

2 of 3
1

Convert your Python script to the Django REST API, and then call it using cURL.

๐ŸŒ
Jeff Schaefer
schaefersoftware.com โ€บ exec-passthru-shell_exec-system
What's the difference between exec(), passthru(), shell_exec(), and system()? - Jeff Schaefer
April 25, 2016 - For running basic commands, this is your function. It can also be run shorthand using the backtick operator. system() will echo the result of the command rather than passing it in the return value.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ php_system_calls.htm
PHP System Calls
Though the passthru() function is similar to the exec() or system() function in that it executes a command, it should be used in their place when the output from the OS command is binary data which needs to be passed directly back to the browser. A PHP program that uses passthu() function to display the contents of system PATH environment variable ยท passthru(string $command, int &$result_code = null): ?false <?php passthru ('PATH'); ?> ... PATH=C:\Python311\Scripts\;C:\Python311\;C:\WINDOWS\system32;C:\WINDOWS; C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\; C:\WINDOWS\System32\OpenSSH\;C:\xampp\php;C:\Users\mlath\AppData\Local \Microsoft\WindowsApps;C:\VSCode\Microsoft VS Code\bin
๐ŸŒ
Wikitechy
wikitechy.com โ€บ technology โ€บ php-exec-vs-system-vs-passthru
exec() vs system() vs passthru() - Wikitechy
October 30, 2018 - This function executes the specified command, and dumps any resulting text to the output stream (either the HTTP output in a web server situation, or the console if you are running PHP as a command line tool). The return of this function is the last line of output from the program, if it emits text output. The system function is quite useful and powerful, but one of the biggest problems with it is that all resulting text from the program goes directly to the output stream.