views:

596

answers:

4

I have a PHP program that uses a Bash script to convert a pdf. However if the filename contains spaces it is not passed through the bash script correctly.

How do you escape filenames with spaces within a bash script? Do you have to do something special to quote 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 removed the quotes around the escapeshellarg() variable. This however did not fix the problem. Which I think is in the Bash script OUTFILE variable.

A: 

To escape a file name with spaces, just use .

My Tar Ball.tar

My\ Tar\ Ball.tar

So for what you have you will either need to make sure that your arguments contain the back slashes when the script is called, or you will need to add some input checking.

AluKa
A: 

Take a look at escapeshellcmd() and escapeshellarg()

VolkerK
+1  A: 

Hi,

Considering your code, I would try by, first, removing the single-quotes you are inserting arround the parameter : those shouldn't be necessary, as you are using escapeshellarg.

For instance, the temp.php file might contain :

$spool = "ab cd/";
$file = "gh ij";
system("sh ./test.sh " . escapeshellarg($spool . $file) . "");

And the test.sh :

#!/bin/bash
INFILE=$1
echo $1

With those, the output is :

$ php temp.php
ab cd/gh ij

Which looks like what you expect.


If I put back the single-quotes, like this :

system("sh ./test.sh '" . escapeshellarg($spool . $file) . "'");

The output is broken again :

$ php temp.php
ab

escapeshellarg is escaping data for you (with the right quotes and all that, depending on the operating system), you don't have to do that yourself.

Pascal MARTIN
I removed my extra quotations around the escapeshellarg. However the bash script is giving me an undefined filename.
jjclarkson
Oh ; in this case, there is probably a problem in the shell-script :-( First of all, what if you try putting double-quotes arround ${INFILE} in the last line ? maybe you'll have to do the same thing with ${OUTFILE}.png, btw ;; if it still doesn't work, what do you get if you do an "echo" of your two variables, from the shell-script ? is it what you expect ?
Pascal MARTIN
+2  A: 

In the last line of your shell script, put quotes around the variable reference:

"${INFILE}"
Dennis Williamson
This worked! I added quotes around the variables on the last 2 lines of the bash script. ...-sOutputFile="${OUTFILE}.png" \"${INFILE}"
jjclarkson