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>';
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)
How can I detect if external website working or not? I have thinked about HTTP ERROR MESSAGE. In general something as:
if ( <<something(url)>> != 200 ) {
// website defined in url working (up)
} else {
// website defined in url not working (down)
}
200 is code that define a success querying url. Just so understood reading here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Try using CURL. The example is adapted from cur_getinfo()
// Create a curl handle
$ch = curl_init('http://stackoverflow.com/');
//Return only headers
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
$info = curl_getinfo($ch);
// Close handle
curl_close($ch);
if ( isset($info) && $info['http_code'] == 200 )
echo "Website is up!";
else
echo "Website is down.";
I am trying to use Google Analytics Measurement protocol (available with Universal Analytics) to track an offline event.
I am using the documentation here : https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#event
Here is the CURL I am calling :
https://www.google-analytics.com/collect?v=1&tid=UA-5520857-25&cid=1260961011.1389432370&t=event&ec=Test-event-cat&ea=Test-event-action&el=&ev=
I get the cid (client ID) via :
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
Here is the full CURL call :
$getString = 'https://www.google-analytics.com/collect?';
$getString .= http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getString);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
// TEST
echo 'CURL call : '.$getString.'<br />';
echo 'Response : <pre>';
print_r($info);
echo '</pre>';
It returns a 200 HTTP code (but I've read that its always the case, even if something is wrong).
No event is shown in my Google Analytics account, even on the real time section.
Do you have any idea about what I am doing wrong ?
Thank you
The problem was that I wasn't setting the el and ev parameters.
The correct call is :
https://www.google-analytics.com/collect?v=1&tid=UA-5520857-25&cid=1260961011.1389432370&t=event&ec=Test-event-cat&ea=Test-event-action&el=test-label&ev=1
The request in Measurement protocol, does not work, if there is no User-Agent
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);
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