Skip to content
Advertisement

How can i implement escapeshellarg inside a URL?

The user supplies two variables via a HTML form called username and name. They are used to execute a shell command which is currently unsafe. I have the following PHP code:

(exec("cat /opt/application/userdata/$username/following | grep -w $name"))

I am trying to implement escapeshellarg, but can’t get it working by following the official PHP documentation, i have tried:

(exec("cat /opt/application/userdata/ .escapeshellarg($username)/following | grep -w .escapeshellarg($name)"))

But this is not working and i think its a syntax error. How do i format this properly?

Advertisement

Answer

What’s happening is that you are currently trying to run a function inside of a string. This is possible with extra steps, but is not desirable.

What you want to do is concatenate the string with the output of the function. You can inline that in this manner:

exec('cat /opt/application/userdata/' . escapeshellarg($username) . '/following | grep -w ' . escapeshellarg($name))

(noticed I used single quotes ['], as no expansion is happening within the string, this is somewhat faster and keeps it separate)

Or you can perform the operation earlier, and simply include (“expand”) the variables in the string, like your first example hints at:

$username = escapeshellarg($username);
$name = escapeshellarg($name);
exec("cat /opt/application/userdata/$username/following | grep -w $name")

(noticed I used double quotes ["] as there is expansion happening within the string)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement