0

I am trying to find out if a curl call was successful or not in php, the equivalent in bash would be:

`eval curl -f --data $payload http://localhost/service`
if [ $? -ne 0 ]; then
    echo passed
else
    echo failed
fi

so far I have this in php but it does not work:

    `eval curl -f --data $PAYLOAD "http://localhost/service"`;
    if ( $? == 0 )
        echo fail;
    else
        echo passed;

however I get the following error PHP Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) or '$'

the payload looks like the folioing:

    $PAYLOAD="'payload={ 
    \"firstname\":\"$firstname\",
    \"id\":\"$id\", 
    \"author_lastname\":\"$lastname\"
    }' "

thanks in advance!

godzilla
  • 3,005
  • 7
  • 44
  • 60
  • `$?` is not a valid variable identifier. Your entire PHP code is everything but valid PHP code. – N.B. Jul 29 '15 at 10:20

2 Answers2

4

Why not just use PHP's curl library?

https://secure.php.net/manual/en/ref.curl.php

Then you can use the built in error functions to catch exceptions.

1

As user2405162 mentioned it'd be better to use PHP's curl library, but if you really want to use shell instead, do it like this:

exec("curl -f --data $PAYLOAD \"http://localhost/service\"", $output, $status);
// constant on left side, to catch assignment 
// instead of comparison typos
if ( 0 == $status )
    echo "fail";
else
    echo "passed";

Backquote syntax only returns output in PHP, no status code is provided. Yet you can try some workarounds:

$status = `curl -f --data $payload http://localhost/service > /dev/null; echo $?`
if ( $status == 0 )
    echo "fail";
else
    echo "passed";

As mentioned in this question: getting output and exit status from shell_exec()

Community
  • 1
  • 1
ptkoz
  • 2,388
  • 1
  • 20
  • 28