Hii i have this code :
$handle = popen("php -q nah.php -p=". '$part' . " 2>&1", "r");
while (!feof($handle))
{
$read = fread($handle, 2096);
echo $read;
}
pclose($handle);
And the the nah.php looks like this:
echo "yaya1\n";
$options = getopt("p:");
$part = $options["p"];
echo $part;
print_r($options);
The output of this comes out to be:
yaya1 Array (
[p] => )
While the $part in the main file has content.
What can be the error in it ?
How can i fix the error ?
Thanks
And all this is done in php-cli
You’ll want to replace the line that runs
popenwith this:This uses the
escapeshellarg()[docs] function in order to wrap the$partvariable in quotes (and escape any quotes inside it), so that it can be used as a shell argument safely.The error was that you had
$partwithin single quotes, so it was being sent to the shell directly as$partinstead of the value being replaced by PHP. The shell then tried to look for a shell variable called$partto replace it with, but since there was none, it simply replaced it with a blank.This code would also have worked:
However, that would not have wrapped the variable in single quotes, so if there were any spaces in it, only the first word would have been considered the value of argument
p, all the other ones would have been considered different arguments.It’s generally good practice to use
escapeshellarg()when sending arguments to a shell command since it takes care of quoting the argument for you.