Server data as viewed through a browser:
Ab91231 B923244 C9ds23911 D300231
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.test.com/stuff',
CURLOPT_USERAGENT => ''
));
$resp = curl_exec($curl);
// Send the request & save response to $resp
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
printing the curl response I get :
Ab91231B923244C9ds23911D300231
any idea why this is happening?
This is because of one or both of these reasons:
The server-side code detects if a browser or curl ask for the resource and sends back the data differently depending on who asks.
The browser-side has something that changes the formatting of what you see, like javascript.
Related
Hi I know that there are similar questions already in there but I have ruled them out.
So I am trying to make a simple POST method with curl and keep getting error 500. Have I missed something ?
// Get cURL resource
$curl = curl_init();
//POST request body
$post_data = array(
'subscription_uuid' => $subscription_uuid,
'merchant' => $merchant_id
);
echo "JSON in POSTFIELDS:" . json_encode($post_data, JSON_PRETTY_PRINT) . "\n";
// Set Headers, endpoint and option to output response as string
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://subscriptions-jwt.fortumo.io/subscriptions/cancel',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Content Type: application/json' ,
'Authorization: Bearer' . " " . $jwt
),
CURLOPT_POSTFIELDS => json_encode($post_data)
));
// Send the request & save response
$unsubscribe_response = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//Request URL:
echo "Unsubscribe Request URL:\n" . curl_getinfo($curl, CURLINFO_EFFECTIVE_URL) . "\n";
echo "Error Code:" . $statusCode . "\n";
And here is the response I get from that code block(simplified this using echo-s):
JSON in POSTFIELDS:{
"subscription_uuid": "<<MY-TOKEN>>",
"merchant": "<<MY-TOKEN>>"
}
Unsubscribe Request URL:
https://subscriptions-jwt.fortumo.io/subscriptions/cancel
Error Code:500
Wierd thing is that using exactly same set of headers, JSON postfields and URL in a tool such as Advanced REST client everything works fine and I get 200 response with no problem.
Something is wrong with my code. Can anyone please spot the issue? Thanks in advance!
I have an application that has a Web Services RESTful API. When I make HTTP GET requests in the browser I get XML responses back.
When I make the same request using PHP I get the correct information but it is not formatted in XML and so I can't pass it to Simple XML.
Here's my code.
<?php
//Deifne user credentials to use with requests
$user = "user";
$passwd = "user";
//Define header array for cURL requestes
$header = array('Contect-Type:application/xml', 'Accept:application/xml');
//Define base URL
$url = 'http://192.168.0.100:8080/root/restful/';
//Define http request nouns
$ls = $url . "landscapes";
//Initialise cURL object
$ch = curl_init();
//Set cURL options
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => $header, //Set http header options
CURLOPT_URL => $ls, //URL sent as part of the request
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, //Set Authentication to BASIC
CURLOPT_USERPWD => $user . ":" . $passwd, //Set username and password options
CURLOPT_HTTPGET => TRUE //Set cURL to GET method
));
//Define variable to hold the returned data from the cURL request
$data = curl_exec($ch);
//Close cURL connection
curl_close($ch);
//Print results
print_r($data);
?>
Any thoughts or suggestions would be really helpful.
S
EDIT:
So this is the response I get from the PHP code:
0x100000rhel-mlsptrue9.2.3.0101
This is the response if I use the WizTools Rest Client or a browser.
<?xml version="1.0" encoding="UTF-16"?>
<landscape-response total-landscapes="1" xmlns="http://www.url.com/root/restful/schema/response">
<landscape>
<id>0x100000</id>
<name>rhel-mlsp</name>
<isPrimary>true</isPrimary>
<version>9.2.3.010</version>
</landscape>
</landscape-response>
As you can see the information is there but the PHP is not really presenting this in a useful way.
I was able to find the answer to this question so I thought I would share the code here.
//Initialise curl object
$ch = curl_init();
//Define curl options in an array
$options = array(CURLOPT_URL => "http://192.168.0.100/root/restful/<URI>",
CURLOPT_PORT => "8080",
CURLOPT_HEADER => "Content-Type:application/xml",
CURLOPT_USERPWD => "<USER>:<PASSWD>",
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_RETURNTRANSFER => TRUE
);
//Set options against curl object
curl_setopt_array($ch, $options);
//Assign execution of curl object to a variable
$data = curl_exec($ch);
//Close curl object
curl_close($ch);
//Pass results to the SimpleXMLElement function
$xml = new SimpleXMLElement($data);
print_r($xml);
As you can see the code is not all that different, the main thing was separating the port option out of the URL and into its own option.
Hopefully this helps someone else out!!!
S
Try this
$resp = explode("\n<?", $data);
$response = "<?{$resp[1]}";
$xml = new SimpleXMLElement($response);
Does it print anything at all (your code)? Try using echo $data but hit F12 to view the results on the console.
When I was making an xml request to tmdb.org I was using this
$movie_name="Dabangg 2";
$xml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.search/en/xml/accd3ddbbae37c0315fb5c8e19b815a5/"$movie_name"");
and it was working !!
Now I have to change the URL since the response is JSON not xml
I have changed it to
<?php
$movie_name="Dabangg 2";
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
$json = file_get_contents($url);
var_dump($json);
?>
But it does not work
If you search for
http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=Dabangg 2
on browser you will get the results.
Warning: file_get_contents(http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=Dabangg 2) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST in /home/wwww/public_html/test/movie.php on line3
Please help me
Try with
urlencode($movie_name);
This function is convenient when encoding a string to be used in a
query part of a URL, as a convenient way to pass variables to the next
page.
Look on this : http://codular.com/curl-with-php
Try Below code :
<?php
$movie_name="Dabangg 2";
$movie_name = urlencode($movie_name);
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
var_dump($resp);
?>
I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>
Using PHP and CURL (unless there is a better alternative then CURL in this case), is it possible to have a php function handle the header response before downloading the file?
For example:
I have a script that downloads and processes urls supplied by the user. I would like to add a check so that if the file is not valid for my process (not a text file, too large, etc),the CURL request would be cancelled before the server wastes time downloading the file.
Update: Solution
PEAR class HTTP_Request2: http://pear.php.net/package/HTTP_Request2/
Gives you the ability to set observers to the connection and throw exceptions to cancel anytime. Works perfectly for my needs!
Using cURL, do a HTTP HEAD request to check the headers, then if it is valid (the status is 200) do the full HTTP GET request.
The basic option you must set is CURLOPT_NOBODY, which changes the requested to the type HEAD
curl_setopt($ch, CURLOPT_NOBODY, true);
Then after executing the query, you need to check the return status which can be done using curl_getinfo()
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
I know this is an old topic but just in case people comes here in the future.
With CURL, you can use CURLOPT_WRITEFUNCTION, who let's you place a callback that will be called as soon as the body response starts coming and needs to be written. In that moment you can read the headers and cancel the process and the body will not be downloaded. All in one request.
For a deeper look and code examples see PHP/Curl: inspecting response headers before downloading body
This is an example how you can solve it:
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
// Make the request
curl_setopt($curl, CURLOPT_URL, "http://docs.google.com/feeds/default/private/full");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
// Parse the response
$response = simplexml_load_string($response);
// Output data
foreach($response->entry as $file)
{
//now you can do what ever if file type is a txt
//if($file->title =="txt")
// do something
else
// do soething
echo "File: " . $file->title . "<br />";
echo "Type: " . $file->content["type"] . "<br />";
echo "Author: " . $file->author->name . "<br /><br />";
}