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.

+2


source to share


4 answers


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



"${INFILE}"

      

+3


source


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.

+1


source


To avoid the filename with spaces, just use.

My Tar Ball.tar

My\ Tar\ Ball.tar

      

So, for what you want, you either need to make sure your arguments contain backslashes when the script is called, or you will need to add input validation.

0


source


0


source







All Articles