I have this url DespegarAPI and as you can see the content is OK. Is a JSON response.
I need that content through my own file and I use curl o file_content but the response I this my file
I have this in my file
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.despegar.com/cities?pagesize=30");
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Thanks for the response!
It's because the content is gzipped, here's a quick example to get you going.
<?php
function despegar($endpoint, array $params = array()) {
$url = sprintf(
'http://api.despegar.com/%s?%s',
$endpoint,
empty($params) ? null : http_build_query($params)
);
$handle = curl_init($url);
curl_setopt_array($handle, array(
CURLOPT_ENCODING => 'gzip',
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ( ! $response || 200 != $code) {
throw new Exception(
sprintf('(%d) Failed to obtain data from %s.', $code, $url),
$code
);
}
return json_decode($response);
}
try {
$cities = despegar('cities', array('pagesize' => 10));
foreach ($cities->cities as $city) {
printf("%s\n", $city->countryId);
}
}catch(Exception $exception) {
echo $exception->getMessage();
}
Related
I tried get page by curl like this
$headers = array(
"Content-Type: application/json",
);
$myCurl = curl_init($url);
curl_setopt($myCurl, CURLOPT_USERAGENT, "php");
curl_setopt($myCurl, CURLOPT_URL, $url);
curl_setopt($myCurl, CURLOPT_HTTPHEADER, $headers);
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array( $myCurl, $options );
$response = curl_exec($myCurl);
$httpCode = curl_getinfo($myCurl, CURLINFO_HTTP_CODE);
if(curl_errno($myCurl)){
$handle = fopen('myCurlError.txt', 'a+');
fwrite($handle, print_r(curl_error($myCurl), true) . "\n");
fclose($handle);
}
if(!curl_errno($myCurl)){
curl_close($myCurl);
$ret = json_decode($response, true);
} else {
curl_close($myCurl);
}
page that I tried to get by curl return result of function that end like this
echo json_encode($result);
that must return this
{"success":true,"redirect":"https:myurl"}
in log of function it show result but curl dont get this result and return errors:
504 or 500 or this Operation timed out after 2001 milliseconds with 0 out of -1 bytes received
I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';
I am using following php library for to work with Taleo
Taleo : http://www.oracle.com/us/products/applications/taleo/overview/index.html
PHP library : https://github.com/Polzme/Taleo
Taleo REST API documentation: http://www.oracle.com/technetwork/documentation/default-1841567.html
POST /candidate/{id}/resume
I wanted to use above API for my project
I wanted to create candidate and upload resume for them using api.
I went through the library code but i didn't found any file or any code line, which is related to resume or attachment
Can you please help me with simple example with library or without library.
Here is working the example, some how I am able to get it worked
<?php
function getCurlValue($filename, $contentType, $postname)
{
// PHP 5.5 introduced a CurlFile object that deprecates the old #filename syntax
// See: https://wiki.php.net/rfc/curl-file-upload
if (function_exists('curl_file_create')) {
return curl_file_create($filename, $contentType, $postname);
}
// Use the old style if using an older version of PHP
$value = "#{$filename};filename=" . $postname;
if ($contentType) {
$value .= ';type=' . $contentType;
}
return $value;
}
function Curl_file_upload($url, $postData)
{
$filename = '/Users/bhushan/Downloads/resume.pdf';
$cfile = getCurlValue($filename,'application/pdf','resume.pdf');
//NOTE: The top level key in the array is important, as some apis will insist that it is 'file'.
$data = array('file' => $cfile);
$ch = curl_init();
$options = array(CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true, //Request header
CURLOPT_HEADER => true, //Return header
CURLOPT_SSL_VERIFYPEER => false, //Don't veryify server certificate
CURLOPT_POST => true,
CURLOPT_COOKIE =>"authToken=".$_SESSION['authToken'],
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($ch, $options);
$output = $result = curl_exec($ch);
$header_info = curl_getinfo($ch,CURLINFO_HEADER_OUT);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
curl_close($ch);
return $output;
}
function curl_call($url, $postData)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
if(!isset($_SESSION['authToken']) || empty($_SESSION['authToken']))
{
$data = array('orgCode' => 'xxxx', 'userName' => 'xxxx', 'password' => 'xxx');
echo $json = curl_call('https://xxx.xxx.taleo.net/ldd01/ats/api/v1/login', $data);
$json = json_decode($json, true);
if(isset($json['response']['authToken'])) $_SESSION['authToken'] = $json['response']['authToken'];
}
else if(isset($_SESSION['authToken']) && !empty($_SESSION['authToken']))
{
$params = array();
echo $json = Curl_file_upload('https://xxx.xxx.taleo.net/ldd01/ats/api/v1/object/candidate/58/resume', $params);
}
I use this code to get a response/result from the other server and I want to know how can I check if the site is alive?
$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php
All you really have to do is a HEAD request to see if you get a 200 OK message after redirects. You do not need to do a full body request for this. In fact, you simply shouldn't.
function check_alive($url, $timeout = 10) {
$ch = curl_init($url);
// Set request options
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => "page-check/1.0"
));
// Execute request
curl_exec($ch);
// Check if an error occurred
if(curl_errno($ch)) {
curl_close($ch);
return false;
}
// Get HTTP response code
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Page is alive if 200 OK is received
return $code === 200;
}
here is the simpler one
<?php
$yourUR="http://sitez.com";
$handles = curl_init($yourUR);
curl_setopt($handles, CURLOPT_NOBODY, true);
curl_exec($handles);
$resultat = curl_getinfo($handles, CURLINFO_HTTP_CODE);
echo $resultat;
?>
Check a web url status by PHP/cURL function :
Condition is , If HTTP status is not 200 or 302, or the requests takes longer than 10 seconds, so the website is unreachable...
<?php
/**
*
* #param string $url URL that must be checked
*/
function url_test( $url ) {
$timeout = 10;
$ch = curl_init();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
$http_respond = curl_exec($ch);
$http_respond = trim( strip_tags( $http_respond ) );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
if ( ( $http_code == 200 ) || ( $http_code == 302 ) ) {
return true;
} else {
// you can return $http_code here if necessary or wanted
return false;
}
curl_close( $ch );
}
// simple usage:
$website = "www.example.com";
if( !url_test( $website ) ) {
echo $website ." is down!";
} else {
echo $website ." functions correctly.";
}
?>
You can try with cURL:
curl -I "<URL>" 2>&1 | awk '/HTTP\// {print $2}'
It will return 200 when it's alive
Keep it short and simple...
$string = #file_get_contents('http://domain.com/curl.php');
If $string is null or empty the page is probably unreachable (or actually doesnt output anything).
How can I do this in PHP? e.g.
bit.ly/f00b4r ==> http://www.google.com/search?q=cute+kittens
In Java, the solution is this:
You should issue a HEAD request to
the url using a HttpWebRequest
instance. In the returned
HttpWebResponse, check the
ResponseUri.
Just make sure the AllowAutoRedirect
is set to true on the HttpWebRequest
instance (it is true by default).
(Thx, casperOne)
And the code is
private static string GetRealUrl(string url)
{
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Head;
WebResponse response = request.GetResponse();
return response.ResponseUri.ToString();
}
(Thx, Fredrik Mork)
But I want to do it in PHP. HOWTO? :)
The time to try, you already found the answer.
Still, I would have gone with something like this :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://bit.ly/tqdUj");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
var_dump($url);
Some explanations :
the requested URL is the short one
you don't want the headers
you want to make sure the body is not displayed -- probably useless
you do not want the body ; ie, you want a HEAD request, and not GET
you want locations to be followed, of course
once the request has been executed, you want to get the "real" URL that has been fetched
And, here, you get :
string 'http://wordpress.org/extend/plugins/wp-pubsubhubbub/' (length=52)
(Comes from one of the last tweets I saw that contained a short URL)
This should work with any shortening-URL service, independantly of their specific API.
You might also want to tweak some other options, like timeouts ; see curl_setopt for more informations.
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
Did you read the bit.ly API? specifically here ?
I can't see the issue. Are you talking about possible redirects ?
CREDIT GOES TO http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // 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;
print($header[0]);
return $header;
}
$thisurl = "http://www.example.com/redirectfrom";
$myUrlInfo = get_web_page( $thisurl );
echo $myUrlInfo["url"];
Here is my solution. I coded it, because none of the above worked correctly.
function get_final_location($url, $index=null) {
if (is_array($url)) {
$headers = $url;
}
else {
$headers = get_headers($url, 1)['Location'];
if (count($headers) == 0) {
return $url;
}
}
if (is_null($index)) {
$to_check = end($headers);
$index = count($headers) - 1;
}
else {
$to_check = $headers[$index];
}
if (!filter_var($to_check, FILTER_VALIDATE_URL) === false) {
if (count($headers) - 1 > $index) {
$lp = parse_url($headers[$index], PHP_URL_SCHEME) . "://" . parse_url($headers[$index], PHP_URL_HOST) . $headers[$index+1];
}
else {
$lp = $to_check;
}
}
else {
$index--;
$lp = landingpage($headers, $index);
}
return $lp;
}