Php commands in cmd

How to execute PHP scripts on the command line

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

In PHP, there is a provision for one to successfully execute PHP codes on the command prompt and terminal. To do this, you should do the following.

  1. You must have successfully installed PHP, either stand-alone or in a bundle, and it must be working. To check if it is installed and is the right version, change the directory into the folder where you installed it, like c:/php , and use the following command on your terminal or cmd:

If you don’t have PHP installed, you can install it as shown below.

On Windows

  • Download it from the official site.
  • Extract the file and store it in a folder, preferably named php , in your C just like so: c:/php
  • Next, place this folder in your environment variable path so that it can be recognized by the command line.

On Linux

To install on Linux, use the command:

apt-get install php5-common libapache2-mod-php5 php5-cli 

You can change the php5 to your version of choice.

On MAC

You can run the command below on your terminal to install PHP.

curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3 

Now that you have PHP installed and running, we can execute our scripts on the command line or terminal.

Читайте также:  Serialisation and deserialization in java

Executing your scripts

  • Next, head to your terminal or command prompt and change the directory into the folder containing your PHP files. Let’s say something like this:
  • Lastly, enter the following command into your cmd or terminal to run the script file named prog1.php :

The complete code to run our sample script will be as follows.

And with that, you have successfully run your PHP script on the command line or terminal, depending on which you use.

Let’s see the image of the execution of my sample prog1.php script on my cmd.

One last thing: you can also start your development server on the cmd and see your code run on the browser. To do that, enter this code in your command line or terminal.

php -S localhost:port -t your_folder/ 

Where your_folder stands for the folder containing the php code to be executed.

You should have something like the image below if you have your browser and cmd opened up.

Источник

exec

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n , is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec() .

If the result_code argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Returns false on failure.

To get the output of the executed command, be sure to set and use the output parameter.

Errors/Exceptions

Emits an E_WARNING if exec() is unable to execute the command .

Throws a ValueError if command is empty or contains null bytes.

Changelog

Version Description
8.0.0 If command is empty or contains null bytes, exec() now throws a ValueError . Previously it emitted an E_WARNING and returned false .

Examples

Example #1 An exec() example

// outputs the username that owns the running php/httpd process
// (on a system with the «whoami» executable in the path)
$output = null ;
$retval = null ;
exec ( ‘whoami’ , $output , $retval );
echo «Returned with status $retval and output:\n» ;
print_r ( $output );
?>

The above example will output something similar to:

Returned with status 0 and output: Array ( [0] => cmb )

Notes

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note:

On Windows exec() will first start cmd.exe to launch the command. If you want to start an external program without starting cmd.exe use proc_open() with the bypass_shell option set.

See Also

  • system() — Execute an external program and display the output
  • passthru() — Execute an external program and display raw output
  • escapeshellcmd() — Escape shell metacharacters
  • pcntl_exec() — Executes specified program in current process space
  • backtick operator

User Contributed Notes 20 notes

This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.

function execInBackground ( $cmd ) <
if ( substr ( php_uname (), 0 , 7 ) == «Windows» ) <
pclose ( popen ( «start /B » . $cmd , «r» ));
>
else <
exec ( $cmd . » > /dev/null &» );
>
>
?>

(This is for linux users only).

We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

// You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
$process = new Process ( ‘ls -al’ );

// or if you got the pid, however here only the status() metod will work.
$process = new Process ();
$process . setPid ( my_pid );
?>

// Then you can start/stop/ check status of the job.
$process . stop ();
$process . start ();
if ( $process . status ()) echo «The process is currently running» ;
>else echo «The process is not running.» ;
>
?>

/* An easy way to keep in track of external processes.
* Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
* @compability: Linux only. (Windows does not work).
* @author: Peec
*/
class Process private $pid ;
private $command ;

public function __construct ( $cl = false ) if ( $cl != false ) $this -> command = $cl ;
$this -> runCom ();
>
>
private function runCom () $command = ‘nohup ‘ . $this -> command . ‘ > /dev/null 2>&1 & echo $!’ ;
exec ( $command , $op );
$this -> pid = (int) $op [ 0 ];
>

public function setPid ( $pid ) $this -> pid = $pid ;
>

public function getPid () return $this -> pid ;
>

public function status () $command = ‘ps -p ‘ . $this -> pid ;
exec ( $command , $op );
if (!isset( $op [ 1 ]))return false ;
else return true ;
>

public function start () if ( $this -> command != » ) $this -> runCom ();
else return true ;
>

public function stop () $command = ‘kill ‘ . $this -> pid ;
exec ( $command );
if ( $this -> status () == false )return true ;
else return false ;
>
>
?>

Источник

How to execute PHP code using command line ?

PHP Installation for Windows Users: Follow the steps to install PHP on the Windows operating system.

  • Step 1: First, we have to download PHP from it’s official website. We have to download the .zip file from the respective section depending upon on our system architecture(x86 or x64).
  • Step 2: Extract the .zip file to your preferred location. It is recommended to choose the Boot Drive(C Drive) inside a folder named php (ie. C:\php).
  • Step 3: Now we have to add the folder (C:\php) to the Environment Variable Path so that it becomes accessible from the command line. To do so, we have to right click on My Computer or This PC icon, then Choose Properties from the context menu. Then click the Advanced system settings link, and then click Environment Variables. In the section System Variables, we have to find the PATH environment variable and then select and Edit it. If the PATH environment variable does not exist, we have to click New. In the Edit System Variable (or New System Variable) window, we have to specify the value of the PATH environment variable (C:\php or the location of our extracted php files). After that, we have to click OK and close all remaining windows by clicking OK.

PHP Installation for Linux Users:

apt-get install php5-common libapache2-mod-php5 php5-cli

PHP Installation for Mac Users:

    Mac users can install php using the following command.

curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3

After installation of PHP, we are ready to run PHP code through command line. You just follow the steps to run PHP program using command line.

  • Open terminal or command line window.
  • Goto the specified folder or directory where php files are present.
  • Then we can run php code using the following command:

We can also start server for testing the php code using the command line by the following command:

php -S localhost:port -t your_folder/

Note: While using the PHP built-in server, the name of the PHP file inside the root folder must be index.php, and all other PHP files can be hyperlinked through the main index page.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Источник

Оцените статью