0

I have the following JSON code:

{"username":"user1","password":"123456"}

That I need to pass to a url, lets say: http://api.mywebsite.com

I'm an extreme php newb, so I've been following a curl tutorial, but here is my current PHP code:

<?php

function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => true,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle compressed
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;

}

?>

2 Answers 2

1

You might want to look into the CURLOPT_POSTFIELDS AND CURLOPT_POST options. These allow you to do a POST request and pass the data set into the CURLOPT_POSTFIELDS in the request.

Something in the lines of this:

$body = 'bar=1&foo=2&baz=3';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
Sign up to request clarification or add additional context in comments.

Comments

0

When you want to use normal GET Params:

$jsonString ='{"username":"user1","password":"123456"}';
$params = json_decode($jsonString);

$getParams = '';
$first = true;
foreach ($params as $key => $param){
    if ($first){
        $getParams .= '?';
        $first = false;
    } else{
        $getParams .= '&';
    }

    $getParams .= $key .'=' .$param;
}

echo $getParams;
get_web_page($url . $getParams);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.