Running External Programs from Laravel: A Complete Guide
Laravel is known for building web applications, but it’s also powerful enough to run external programs like C binaries, Python scripts, or system commands. In this guide, we’ll explore why and how you can do it, with real-world examples.
Why Run External Programs from Laravel?
- 🚀 Offload heavy computation to C/C++ for speed
- 🧠 Run Python scripts for AI/ML tasks
- 🎬 Use tools like
ffmpegfor video processing - ⚙️ Automate system tasks (backups, cron jobs, etc.)
If it runs on your server’s terminal, Laravel can orchestrate it.
Methods to Run Programs
1. exec()
$results = [];
$status = 0;exec('ls -la', $results, $status);dd($results, $status);
✅ Pros: Captures output + exit code
⚠️ Cons: Only last line by default unless you use an array
2. shell_exec()
$output = shell_exec('python3 ' . storage_path('app/scripts/hello.py'));
echo $output;✅ Pros: Returns all output as a string
⚠️ Cons: No direct exit status
3. system() / passthru()
$status = 0;
system('ffmpeg -i input.mp4 output.mp4', $status);✅ Pros: Real-time or binary output
⚠️ Cons: Less flexible if you need to process output
4. Symfony Process (Recommended)
use Symfony\Component\Process\Process;$process = new Process(['ls', '-la']);
$process->run();if (!$process->isSuccessful()) {Get Mohammad Tareq Aziz Sifate’s stories in your inbox
Join Medium for free to get updates from this writer.
throw new \Exception($process->getErrorOutput());
}echo $process->getOutput();
✅ Pros: Exception handling, async, cross-platform
⚠️ Cons: Slightly more verbose
Real-World Examples
🔹 Compile & Run a C Program
$sourceFile = storage_path('app/calc_interest.c');
$binaryFile = storage_path('app/calc_interest');exec("gcc $sourceFile -o $binaryFile 2>&1", $compileOutput, $compileStatus);if ($compileStatus !== 0) {
return implode("\n", $compileOutput);
}exec("$binaryFile 1000 5 10 2 2>&1", $runOutput);return $runOutput[0] ?? null;
🔹 Convert Videos with FFmpeg
$input = storage_path('app/uploads/video.mp4');
$output = storage_path('app/processed/video.mp4');exec("ffmpeg -i $input -vf scale=1280:720 $output 2>&1", $log, $status);dd($log, $status);
🔹 Run a Python Script
$image = storage_path('app/uploads/image.png');
$script = storage_path('app/scripts/analyze.py');$output = shell_exec("python3 $script $image");
echo $output;Security Considerations
- 🚫 Never execute untrusted user input directly
- 🔒 Use Docker or sandboxing for unsafe code
- ⏳ Move long jobs to Laravel Queues
- 📝 Always log output and exit codes
Conclusion
Laravel isn’t just a backend framework — it can act as a bridge to external programs. With the right precautions, you can safely combine the best of PHP, C, Python, and system tools inside a single app.




