PHP post Rest API

1.9k Views Asked by At

I'm searching all day long what's happen with my api call from php page but can't find a working solution. Simple, I have one rest api which needs 2 parameters, it returns a json message. Calling the api from postman for example, it works fine. Calling from my php page, it blocks my webserver until timeout raises.

my block is (one of found here on SO):

        $url = HOST . '/users/verifyemail';
        $userID = $_GET['userID'];
        $key = $_GET['key'];            

        $postdata = http_build_query(
            array(
                'userID' => $userID,
                'apiKey' => $key
            )
        );              

        try
        {

            $opts = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-Type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );
            $context  = stream_context_create($opts);

            $response = file_get_contents($url, false, $context);
            if ($response) {
                echo "OK";
            } else {
                echo "NOK !";
            }
        } catch (Exception $ex) {
            echo $ex;
        }  

Even the catch isn't called.

In my webserver I have this:

[Wed Jun 17 20:39:18 2015] ::1:52312 [200]: /emailValidation.php?userID=16&key=1212
[Wed Jun 17 20:39:18 2015] ::1:52313 [200]: /users/verifyemail

As everything was fine...

My PHPInfo

Any idea ?

Thank you !

2

There are 2 best solutions below

7
On

please try php-curl:

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "$url",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        userID => "$userID",
        apiKey => "$key",
    )

));

$response = curl_exec($curl);
curl_close($curl);

phpinfo output

0
On

In fact, Kasper Franz was right. Even having PHP installed as third part in my mac, it was using the built-in instance and the problem was about the single thread.

Changing the configuration resolved the issue.

Thank you AirPet for your prompt help too ;-)