Alex Kirwan
Alex Kirwan

Reputation: 45

PHP Simple Api post request

Hi there I never develop in php but I have to create a small function to do a post request to my meteor node application. The end point works fine I have been testing it. I am trying to use the post request to get my login token back. Providing username and password it should return json data even it is incorrect it returns json data saying login refused.

It seem noting is happening tho. My return data seems to always be null.

As I said I never really used php nore do I plan on using it much. But here is my code probably very easy mistake to fix.

<?php 

$ch = curl_init();

$params = array(
        "username" => "apilogin",
        "password" => "12345"
);

echo httpPost("http://127.0.0.1:3000/api/login", $params);


function httpPost($url,$params)
{
  $postData = http_build_query($params);

    $ch = curl_init();  

    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_POST, count($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


    $output=curl_exec($ch);
    // Check for errors
    if($output === FALSE){
        echo "false";
        die(curl_error($ch));
    }

    // Decode the response
    $output = json_decode($response, TRUE);
    curl_close($ch);
    return $output;
}
?>

Upvotes: 0

Views: 1097

Answers (1)

Gerjan
Gerjan

Reputation: 163

change:

$output = json_decode($response, TRUE);

into:

$output = json_decode($output, TRUE);

you never made a variable $response

Upvotes: 1

Related Questions