Bash and PHP quoting command line arguments
I have a PHP program that uses a Bash script to convert a pdf. However, if the filename contains spaces, it does not pass through the Bash script correctly.
How do you avoid filenames with spaces inside a Bash script? Do you need to do something special to specify the filename for the "OUTFILE" variable?
Bash script:
#!/bin/bash
INFILE=$1
OUTFILE=${INFILE%.*}
gs \
-q \
-dSAFER \
-dBATCH \
-dNOPAUSE \
-sDEVICE=png256 \
-r150x150 \
-sOutputFile=${OUTFILE}.png \
${INFILE}
PHP script:
echo "converting: ".$spool.$file . "\n";
system("/home/user/bin/pdf2png.sh " . escapeshellarg($spool . $file));
Edit: I've removed the quotes around the escapeshellarg () variable. However, this did not fix the problem. I think it is in the Bash script variable OUTFILE.
source to share
Given your code, I would try, firstly, to remove the single quotes that you insert arround in the parameter: they shouldn't be necessary as you are using escapeshellarg
.
For example, a file temp.php
might contain:
$spool = "ab cd/";
$file = "gh ij";
system("sh ./test.sh " . escapeshellarg($spool . $file) . "");
And test.sh
:
#!/bin/bash
INFILE=$1
echo $1
With this, the output is:
$ php temp.php
ab cd/gh ij
Which looks like what you expect.
If I get my single quotes back, like this:
system("sh ./test.sh '" . escapeshellarg($spool . $file) . "'");
The output is broken again:
$ php temp.php ab
escapeshellarg
is escaping the data for you (with the right quotes and all that, depending on the operating system), you don't have to do it yourself.
source to share