note 130621 added to function.shell-exec

From: Date: Fri, 23 Jan 2026 20:32:42 +0000
Subject: note 130621 added to function.shell-exec
Groups: php.notes 
Request: Send a blank email to php-notes+get-222511@lists.php.net to get a copy of this message
<?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.shell-exec.php Edit -- https://main.php.net/note/edit/130621 Del: integrated -- https://main.php.net/note/delete/130621/integrated Del: useless -- https://main.php.net/note/delete/130621/useless Del: bad code -- https://main.php.net/note/delete/130621/bad+code Del: spam -- https://main.php.net/note/delete/130621/spam Del: non-english -- https://main.php.net/note/delete/130621/non-english Del: in docs -- https://main.php.net/note/delete/130621/in+docs Del: other reasons-- https://main.php.net/note/delete/130621 Reject -- https://main.php.net/note/reject/130621 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222511) next »