John
John

Reputation: 393

Using str_replace to remove spaces for exec()

I'm running into an issue with the function str_replace() while trying to create a shell command in PHP. In shell, when I tab-finish a line that has spaces, it comes up like this:

tar cvfz destination/filename.zip source/Name\ Of\ The\+\ Folder

So to me, this says that in order to run this command via exec(), I need to replace any spaces I would have in a string in PHP. To remedy this problem, I'm using

$q = str_replace(' ', '\ ' , $q);

at the start of my string parse, in order to format the spaces into "\ " instead of " ". The issue I'm having is that for this particular folder, it's also removing the plus symbol as well, and it formats it like this:

tar cvfz destination/Name\ Of\ The\ \ \ Folder.tgz source/Name\ Of\ The\ \ \ Folder

How can I set this up so str_replace() doesn't remove the plus sign? From my limited tests so far, it isn't removing anything out of these: -, %, @, !, (, *, ), ^, =

Upvotes: 1

Views: 723

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318638

Using string functions for this is very wrong and likely to leave security holes wide open.

PHP has a function called escapeshellarg() that does exactly what you need:

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input.

Upvotes: 3

Related Questions