$cmd = "rm 1.txt";//delete a nonexistent file, view the error message $res = doshell ($cmd); Var_dump ($res);//The function has no restrictions. Can be placed directly in the code using Function doshell ($cmd, $cwd =null) { $descriptorspec = array ( 0 => array ("Pipe", "R"), // stdin 1 => array ("Pipe", "w"), // stdout 2 => array ( "Pipe", "W") // stderr );// $cmd = './test.sh '; // Replace with the shell script you want to execute /* * return value * Returns the resource type that represents the process, when you are finished, call the proc_close () function to close the resource. returns false if it fails. * cmd the command to execute * descriptorspec an indexed array. * the key representation descriptor for the array, 0 represents the standard input (stdin), 1 indicates standard output (stdout),2 represents a standard error (STDERR) * Array element values represent PHP how these descriptors are routed to child processes. * pipe (the second element can be a: r that transmits the read side of the pipeline to the process,w the write end of the pipeline to the process), * and file (the second element is a file name). * pipes * will be set to an indexed array, where the element is a file pointer created by the executing program that corresponds to the PHP end of the pipeline. * cwd * The initial working directory to execute the command. Must be absolute path, set this parameter to NULL indicates the use of the default (working directory of the current PHP process) * env * environment variable used by the command to execute. Setting this parameter to NULL means using the same environment variables as the current PHP process. * * */ $proc = proc_open ($cmd, $descriptorspec, $pipes, $cwd, null); // $proc is false, indicating command execution failure if ($proc == false) { return false; // do sth with HTTP response } else { $stdout = stream_get_contents ($pipes [1]); fclose ($pipes [1]); $stderr = stream_get_contents ($pipes [2]); fclose ($pipes [2]); $status = proc_close ($proc); // release proc } $data = array ( ' stdout ' => $stdout, ' stderr ' = > $stderr, ' retval ' => $status ); return $data;}
PHP executes shell command print error message