Posting JSON to URL using PHP curl - php

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;
}
?>

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);

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);

Related

cURL returning "Object not found!"

I'm having problem with cURL, it's returning no result or "Object not found!"
I know the site actually provide their own API, but i need more information to be grabbed.
How to solve this problem ?
here's the code
<?php
$URL = "http://myanimelist.net/manga.php?q=nisekoi";
//Initl curl
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
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;
}
echo get_web_page($URL)['content'];
?>

curl not redirecting as expected

Any idea why this function is not redirecting to paypal.com and instead I am staying on the same page? curl is activated on the server, safe mode is off and openbasedir is turned off too.
function curl_post($url, array $post = NULL, array $options = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
curl_post("https://www.paypal.com/cgi-bin/webscr",$_POST);
Any idea what am I doing wrong?
After you make curl request:
foreach ($parameters as $key => $value) {
$requestParams[] = $key . '=' . $value;
}
$requestParams = implode ('&', $requestParams);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
You should get exact url, to know where you should be redirected:
$location = curl_getinfo($ch)['redirect_url'];
And then redirect:
header('Location: '. $location);
cURL is just a library for initiating and firing HTTP and FTP requests.
Your code just sends a HTTP POST request to the PayPal server.
In order to redirect the user, send a Location header (before any output!):
header('Location: https://www.paypal.com/...');

Getting SESSION_ID from skrill server

Please help me i am having some trouble.
What i want to do is integrate moneybooker in my website.
I studied the "Merchant Integration Manual version 6.17" in 2.3.2 Topic where i have to create and get a SESSION_ID form skrill server by sending payment parameters by post and get the SESSION_ID this session will hold my transaction information like amount and my account.
By using below code i can't retrieve the SESSION_ID from their server.
$url = "https:www.moneybookers.com/app/payment.pl";
$post_data = array (
"prepare_only" => 1,
"amount" => 10,
"currency" => 'USD',
"detail1_description" => "Description",
"detail1_text" => "Text",
"pay_to_email" => "****my**accoutn#yahoo.com"
);
$head = get_web_page($url, $post_data);
echo "<pre>";
print_r($head);
echo "</pre>";
function get_web_page( $url, $post_data )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
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 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//we are doing a POST request
curl_setopt($ch, CURLOPT_POST, 1);
//adding the post variables to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$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;
}
The above code works for other sites but not for moneybooker.
But when i submit simple html form, session id is created and shown but i am not being redirected to my site !!
Try adding cookies support
$fh = fopen("cookies.txt", "a+") or die("Can't open file!");
fclose($fh);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
When you set CURLOPT_POSTFIELDS with an array, the request will be sent as multipart/form-data, try changing that line to:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

PHP Curl and JSON confusion

I'm trying to understand how getting an access_token works with CURL.
$url = "https://api.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => '',
'client_secret' => '',
'grant_type' => '',
'redirect_uri' => '',
'code' => $_GET['code']
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
I'm supposed to get a JSON string with this right?
I tried a various of things to output the string
$test = json_decode($result);
print_r($test);
$arr = json_encode($result,true);
foreach($arr as $val){
echo $val['access_token'];
}
Am I doing this wrong?
I believe the correct JSON output should be something like this :
{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg"
}
}
But this is not working? I'm trying to get the access_token from the server.
Any help would be appreciated! Thank you
Try use below function to get content
$response = get_web_page($url);
$resArr = array();
$resArr = json_decode($response);
//echo"<pre>"; print_r($resArr); echo"</pre>";
function get_web_page($url) {
$options = array (CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // 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 );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
$header ['errno'] = $err;
$header ['errmsg'] = $errmsg;
$header ['content'] = $content;
return $header ['content'];
}

How to get the real URL after file_get_contents if redirection happens?

I'm using file_get_contents() to grab content from a site, and amazingly it works even if the URL I pass as argument redirects to another URL.
The problem is I need to know the new URL, is there a way to do that?
If you need to use file_get_contents() instead of curl, don't follow redirects automatically:
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
var_dump($http_response_header);
Answer inspired by: How do I ignore a moved-header with file_get_contents in PHP?
You might make a request with cURL instead of file_get_contents().
Something like this should work...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
$l = trim($r[1]);
Source
Everything in one function:
function get_web_page( $url ) {
$res = array();
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // do not return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
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 );
$res['content'] = $content;
$res['url'] = $header['url'];
return $res;
}
print_r(get_web_page("http://www.example.com/redirectfrom"));
A complete solution using the bare file_get_contents (note the in-out $url parameter):
function get_url_contents_and_final_url(&$url)
{
do
{
$context = stream_context_create(
array(
"http" => array(
"follow_location" => false,
),
)
);
$result = file_get_contents($url, false, $context);
$pattern = "/^Location:\s*(.*)$/i";
$location_headers = preg_grep($pattern, $http_response_header);
if (!empty($location_headers) &&
preg_match($pattern, array_values($location_headers)[0], $matches))
{
$url = $matches[1];
$repeat = true;
}
else
{
$repeat = false;
}
}
while ($repeat);
return $result;
}
Note that this works only with an absolute URL in the Location header. If you need to support relative URLs, see
PHP: How to resolve a relative url.
For example, if you use the solution from the answer by #Joyce Babu, replace:
$url = $matches[1];
with:
$url = getAbsoluteURL($matches[1], $url);
I use get_headers($url, 1);
In my case redirect url in get_headers($url, 1)['Location'][1];

Categories