PHP | shell_exec() vs exec() Function

shell_exec() Function

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. If the command fails return NULL and the values are not reliable for error checking.

Syntax:

string shell_exec( $cmd )

Parameters: This function accepts single parameter $cmd which is used to hold the command that will be executed.

Return Value: This function returns the executed command or NULL if an error occurred.



Note: This function is disabled when PHP is running in safe mode.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Use ls command to shell_exec
// function
$output = shell_exec('ls');
  
// Display the list of all file
// and directory
echo "<pre>$output</pre>";
?>

chevron_right


Output:

gfg.php
index.html
geeks.php

exec() Function

The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.

Syntax:

string exec( $command, $output, $return_var )

Parameters: This function accepts three parameters as mentioned above and described below:

  • $command: This parameter is used to hold the command which will be executed.
  • $output: This parameter is used to specify the array which will be filled with every line of output from the command.
  • $return_var: The $return_var parameter is present along with the output argument, then it returns the status of the executed command will be written to this variable.

Return Value: This function returns the executed command, be sure to set and use the output parameter.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// (on a system with the "iamexecfunction" executable in the path)
echo exec('iamexecfunction');
?>

chevron_right


Output:

geeks.php

References:



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.