For some reason my CURL isnt working now, all i did was change the url (as before i was using this to call info from the need for speed world servers) and it worked flawlessly, now I am trying to use it with IMDBAPI and it gives me an error.
url i type in:
http://localhost/movie.php?title=The Green Mile
Code:
<?php
$title = $_GET['title'];
//optional comment out or delete
error_reporting(E_ALL);
// The POST URL and parameters
$request = 'http://www.imdbapi.com/?t='.$title.'&r=XML';
// Get the curl session object
$session = curl_init($request);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
// Get HTTP Status code from the response
$status_code = array();
preg_match('/\d\d\d/', $response, $status_code);
// Check for errors
switch( $status_code[0] ) {
case 200:
// Success
break;
case 503:
die('Service unavailable. An internal problem prevented us from returning data to you.');
break;
case 403:
die('Forbidden. You do not have permission to access this resource, or are over your rate limit.');
break;
case 400:
// You may want to fall through here and read the specific XML error
die('Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
break;
default:
die('Your call returned an unexpected HTTP status of:' . $status_code[0]);
}
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$movieInfo = simplexml_load_string($xml);
$movieTitle = $movieInfo->movie['title'];
echo "Title: $movieTitle <br />";
?>
Error:
Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.
I am a noob to CURL so any help is appreciated.
You should urlencode() the $title.
http://www.imdbapi.com/?t=The%20Green%20Mile&r=XML
This one works fine for me. Try to rawurlencode that title
$title = rawurlencode($title);
As Shi said,you need encode the values:
$title = rawurlencode($_GET["title"]);
You can get the http code of your request with:
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
Related
I started my PHP script using file_get_contents(), I'm using an online data base and I can get JSON from it using URL, but sometimes (and I can't help it) I get back some 40* or 50* errors responses code, and I wondered if you guys could tell me what's better to use between cURL and file_get_contents, because basically everytime I'll have to check response code and switch case on it to determine what I do next.
200 => get file
403 => print "error"
502 => print 'bad gateway'
...
Hope I was clear, thanks in advance!
How to get the status of an HTTP response?
Using cURL
The function curl_getinfo() get information regarding a specific transfer. The second parameter of this function allows to get a specific information. The constant CURLINFO_HTTP_CODE can be used to get the HTTP status code of the HTTP response.curl_getinfo() should be called after curl_exec() and is relevant if curl_exec()' return is not false. If the response is false, don't forget to use curl_error() in this case to get a readable string of the error.
$url = 'https://stackoverflow.com';
$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); // required to get the HTTP header
$response = curl_exec($curlHandle);
$httpCode = $response !== false ? curl_getinfo($curlHandle, CURLINFO_HTTP_CODE) : 0;
curl_close($curlHandle);
var_dump($httpCode); // int(200)
Using streams
The function stream_get_meta_data() retrieves header/meta data from streams/file pointers
$url = 'https://stackoverflow.com';
$httpCode = 0;
if ($fp = fopen($url, 'r')) {
$data = stream_get_meta_data($fp);
[$proto, $httpCode, $msg] = explode(' ', $data['wrapper_data'][0] ?? '- 0 -');
}
fclose($fp);
var_dump($httpCode); // int(200)
I've got the OneNote API PHP Sample (thanks jamescro!) working with all the POST examples, but there's no GET example and I haven't managed to put together code of my own that works. Here's what I've tried without success:
// Use page ID returned by POST
$pageID = '/0-1bf269c43a694dd3aaa7229631469712!93-240BD74C83900C17!600';
$initUrl = URL . $pageID;
$cookieValues = parseQueryString(#$_COOKIE['wl_auth']);
$encodedAccessToken = rawurlencode(#$cookieValues['access_token']);
$ch = curl_init($initUrl);
curl_setopt($ch, CURLOPT_URL, $initUrl); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (! $response === false) {
curl_close($ch);
echo '<i>Response</i>: '. htmlspecialchars($response);
}
else {
$info = curl_getinfo($ch);
curl_close($ch);
echo '<i>Error</i>: ';
echo var_export($info);
}
It just returns 'Error' with an info dump. What am I doing wrong?
without information on the specific error I'm not sure what issue you are hitting. Try looking at the PHP Wordpress plugin here: https://github.com/wp-plugins/onenote-publisher/blob/master/api-proxy.php
look at what is sent to wp_remote_get - there are necessary headers that are needed.
Also make sure you have the scope "office.onenote" when you request the access token.
If you need more help, please add information about the specific URL you are attempting to call, as well as the contents of your headers. If you have any errors, please include the output.
Solved:
As Jay Ongg pointed out, "there are necessary headers that are needed".
After adding more detailed error checking and getting a 401 response code, I added:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:text/html\r\n".
"Authorization: Bearer ".$encodedAccessToken));
... and could access the requested page.
I have the following code in order to call a Web Service from php, using curl:
<?php
echo "Init<br />";
$url = 'http://server-ip/applications/time2gate.aspx?x=1182&y=365&map=1002&gate=B3&mode=time2gate&session=5fdf288d-01b0-414a-ba2a-58d3f624e453';
$ch = curl_init($url);
echo "1";
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$status_code = array();
preg_match('/\d\d\d/', $resp, $status_code);
switch($status_code[0]) {
case 200:
echo "Success<br />";
break;
case 503:
die('Your call to Web Service failed and returned an HTTP 503.');
break;
case 403:
die('Your call to Web Service failed and returned an HTTP status of 403.');
break;
case 400:
die('Your call to Web Services failed and returned an HTTP status of 400.');
break;
default:
die('Your call to Web Services returned an unexpected HTTP status of:' . $status_code[0]);
}
if(curl_errno($ch))
{
echo 'error' . curl_error($ch);
}
curl_close($ch);
?>
The problem is that I receive HTTP response codes like 163, 815, 329... Why is this happening? What do these codes mean? I checked Apache's error log and I have not seen any errors on my code. Also, I tested a call to the url provided and it works with Mozilla's Poster Add-on.
Any ideas? I am working with php 5, on Ubuntu 12.
Thank you,
Nick
When I need to make API calls I use a simple library available on GitHub: https://github.com/rmccue/Requests
I've put an example below which uses this library and it will print out the full response from the API.
<?php
require_once('library/Requests.php');
$url = 'http://server-ip/applications/time2gate.aspx?x=1182&y=365&map=1002&gate=B3&mode=time2gate&session=5fdf288d-01b0-414a-ba2a-58d3f624e453';
// Next, make sure Requests can load internal classes
Requests::register_autoloader();
// Now let's make a request!
$request = Requests::get($url, array('Accept' => 'application/json'));
echo '<pre>';
print_r($request);
echo '</pre>';
Am using Curl to send sms using a gateway , a, getting 200 when everything is ok and 400 if its not send now , i should get other things from the gateway such as phone number and other information , so am i missing something ?
// if the Form is submited
//if (isset($_POST['PhoneNumber'])) {
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Fetch Phone Number and escape it for security
$Phone = mysql_real_escape_string($_POST['PhoneNumber']);
// Fetch Text and escape it for security
$Text = mysql_real_escape_string($_POST['Text']);
// Structure the URl
$url = "http://xxxxxxxxxxx:xxxx?PhoneNumber=".urlencode($Phone)."&Text=".urlencode($Text)."&User=xxx&Password=xxx";
// Handeling the Curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode=="200"){
// if everything is okey , the gateway returns 200 which means OK
echo "Massage Was Sent , Thank you ";
} elseif ($httpCode=="400"){
// if there was an error , the form returns a 400 which means that the sms Failed
echo "Massage was not sent , Please Try Again";
}
// Cloase the Curl Connection
curl_close($handle);
Thank you Best regards,
$response should contain the response, try:
echo '<pre>';
print_r($response);
echo '</pre>';
to show its content
I basically created a script using Curl and PHP that sends data to the website e.g. host, port and time. Then it submits the data. How would I know if the Curl/PHP actually sent those data to the web pages?
$fullcurl = "?host=".$host."&time=".$time.";
Any ways to see if they actually sent the data to those URLs on My MYSQL?
You can use curl_getinfo() to get the status code of the response like so:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, I'm assuming you don't care about the result content
curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
// everything went better than expected
} else {
// the request did not complete as expected. common errors are 4xx
// (not found, bad request, etc.) and 5xx (usually concerning
// errors/exceptions in the remote script execution)
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
For reference: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Or, if you are making requests to some sort of API that returns information on the result of the request, you would need to actually get that result and parse it. This is very specific to the API, but here's an example:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, but this time we care about the result
$result = curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
// let's pretend this is the behaviour of the target server
if ($result == 'ok') {
// everything went better than expected
} else {
die('Request failed: Error: ' . $result);
}
in order to be sure that curl sends something, you will need a packet sniffer.
You can try wireshark for example.
I hope this will help you,
Jerome Wagner