| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
<?php
/**
* Execute a shell command using the best available method.
* @param string $cmd The command to execute.
* @return string The output of the command, or a not supported message.
*/
function php_exec($cmd) {
// 1. exec
if (function_exists('exec')) {
$output = array();
$return_var = 0;
exec($cmd, $output, $return_var);
// Use "\n" to preserve line breaks, not space
return implode("\n", $output);
}
// 2. shell_exec
else if (function_exists('shell_exec')) {
return shell_exec($cmd);
}
// 3. system (Fixed: Added output buffering)
else if (function_exists('system')) {
ob_start();
system($cmd);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
// 4. passthru
else if (function_exists('passthru')) {
ob_start();
passthru($cmd);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
// 5. proc_open (Fixed: Added proper closing of resources)
else if (function_exists('proc_open')) {
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
// Write to stdin if needed (skipped here)
fclose($pipes[0]);
// Read stdout
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
// Read stderr (optional, usually good to have)
// $errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
// Close the process to avoid zombies
proc_close($process);
return $output;
}
}
return "@PHP_COMMAND_NOT_SUPPORT";
}
// Example of safer usage
$user_input = "some_filename.txt";
$clean_input = escapeshellarg($user_input);
$output = php_exec("ls -l " . $clean_input);
----
Server IP: 206.189.2.9
Probable Submitter: 27.147.206.73
----
Manual Page -- https://php.net/manual/en/function.proc-open.php
Edit -- https://main.php.net/note/edit/130622
Del: integrated -- https://main.php.net/note/delete/130622/integrated
Del: useless -- https://main.php.net/note/delete/130622/useless
Del: bad code -- https://main.php.net/note/delete/130622/bad+code
Del: spam -- https://main.php.net/note/delete/130622/spam
Del: non-english -- https://main.php.net/note/delete/130622/non-english
Del: in docs -- https://main.php.net/note/delete/130622/in+docs
Del: other reasons-- https://main.php.net/note/delete/130622
Reject -- https://main.php.net/note/reject/130622
Search -- https://main.php.net/manage/user-notes.php