How can I run an Ubuntu command in a PHP script?

In PHP, you can use the exec function to run a command on the command line. The exec function takes a string as an argument, which is the command you want to run, and returns the output of the command as a string. Here is an example of how you can use the exec function to run an Ubuntu command in a PHP script:


    $output = exec("ls -l /var/www/html");
    echo $output;

In this example, the exec function is used to run the ls -l /var/www/html command, which lists the files and directories in the /var/www/html directory. The output of the command is stored in the $output variable and then printed out using the echo statement.

You can also use other functions such as system, passthru, shell_exec, proc_open, depending on your specific use case and need. Be careful when using any of these functions as it can lead to security vulnerabilities if not used properly.

You can also make use of escapeshellarg() function to escape any arguments passed to the shell command to avoid any command injection vulnerabilities.


Added  Jan 25, 08:45 pm

Article tags

SignUp with Email