Back to Top

How to execute PHP code from the command line?

How to execute PHP code from the command line?

PHP supports functions which allow you to execute PHP code from the command line. You don’t need a browser to execute your PHP code. Today I am going to cover exec() function to execute external command using PHP.

exec(): Executes an external command but print nothing. It simply returns the last line of the command.



command – The command you want to execute
output – If output parameter is specified, the array will be filled with the output of the code.

Note that if the array already contains some elements before the exec () function call, the output of the command will be appended to the end of the array. If you do not want to combine with the previous contents of the array, you should call the function unset () with the name of the array as an argument before passing it as an argument to the exec().

return_var – If both the parameter return_var and output, when you exit this variable will contain the completion status of the external program.

Examples to use exec() fucntion

Let’s execute the basic command using the exec() function

The exec() function calls the program directly without any intermediate shell and the backtick execute the program thru a shell.

There is one more technique to use the pipeline command using 2 > &1. You can this in exec() command and it will output the shell execution error to the output of the variable.


You can write like this:

Why you need the exec() in PHP?

exec() is a function and is mainly needed to execute any command using PHP. You can also execute the external command without outputting the result or response.If the output variable is set to the function, all the execution results are included into that variable in an array form. If you need to use it to run it in the background of the program, make sure that the output has been redirected to another file, otherwise, the php will wait for it to complete the implementation and then it will continue to the browser output.

Note: If your program starts with this function and want to leave it running in the background, you should make sure that the output of this program will be sent to a file or some other output stream or else PHP will hang until the execution of the program ends.

At the same time, I want to finish. I hope everything is clear and now you have to deal with this function. If you are using exec() function to execute PHP code, let me know in the comment section that how it is useful to you? Thank you for attention. Error-free execution of your code!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

Create Custom Page Tabs for Facebook Page

Posted on 6 years ago


How to import user from CSV in WordPress?

Posted on 4 years ago


How to use HTML5 download attribute?

Posted on 3 years ago