PHP exec() Can Run Anything - Here’s What You Need to Know

March 07, 2024

Our hero today will be the exec() function.

 

The exec() Function

 

string exec ( string $command [, array &$output [, int &$result_code ]] )

 

With the exec() function, we can execute any command from the command line within our PHP/Laravel code.

 

Example integration with the ffmpeg program:

 

 

The variables $output and $returnCode return the console output and the result code.

 

Here are the docs: https://www.php.net/manual/en/function.exec.php

 

Aside from that exec() PHP function:

  1. Has direct shell access.
  2. It returns nothing, but has $output and $resultCode variable to be provided if you want the output, which is kind strange in my opinion.
  3. Be careful with direct shell access.
  4. It is multi-platform. Works on both Linux and Windows.
  5. It can be disabled in php config.
  6. It is not limited to commands. You can execute Python, Bash etc. scripts.
  7. You can modify files using exec()  function
  8. Can Execute Malware (⚠️ Be Careful)
  9. Can be used as Automated Backups:
    exec("mysqldump -u user -p'password' database > backup.sql");
  10. Automated Deployments – Deploy code from Git:
    exec("git pull origin main && composer install && php artisan migrate");

 

 

Reach out to me! Find me on linkedin!

 

Want to stay updated? Join my newsletter and get a weekly report on the most exciting industry news! 🚀