Caching Instagram API requests using PHP? - php

Here's my current script that does the API calling:
$client = "55447265ed444bb5b768ecb0765ba9cb";
$query = $_POST['q'];
$clnum = mt_rand(1,3);
$api = "https://api.instagram.com/v1/tags/".$query."/media/recent?client_id=".$client;
function get_curl($url) {
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $output;
} else{
return file_get_contents($url);
}
}
$response = get_curl($api);
$images = array();
if($response){
foreach(json_decode($response)->data as $item){
$src = $item->images->standard_resolution->url;
$thumb = $item->images->thumbnail->url;
$url = $item->link;
$images[] = array(
"src" => htmlspecialchars($src),
"thumb" => htmlspecialchars($thumb),
"url" => htmlspecialchars($url)
);
}
}
print_r(str_replace('\\/', '/', json_encode($images)));
die();
I found 2 codes that can do caching but need help integrating them into my current script. One script is longer than the other. Both scripts do a $cache variable followed by an "if, else" code then they both branch out into different codes. The 2nd code is really similar to my current script but trying to figure out how to merge them.
1st code:
// Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
$result = '<div id="instagram">'.PHP_EOL;
foreach ($jsonData->data as $key=>$value) {
$result .= "\t".'<a class="fancybox" data-fancybox-group="gallery"
title="'.htmlentities($value->caption->text).' '.htmlentities(date("F j, Y, g:i a", $value->caption->created_time)).'"
style="padding:3px" href="'.$value->images->standard_resolution->url.'">
<img src="'.$value->images->low_resolution->url.'" alt="'.$value->caption->text.'" width="'.$width.'" height="'.$height.'" />
</a>'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
return $result;
}
2nd code:
$cache = './cache.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$images = json_decode(file_get_contents($cache),true); //Decode as an json array
}
else{
// Make an API request and create the cache file
// For example, gets the 32 most popular images on Instagram
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
$title = (isset($item->caption))?mb_substr($item->caption->text,0,70,"utf8"):null;
$src = $item->images->standard_resolution->url; //Caches standard res img path to variable $src
//Location coords seemed empty in the results but you would need to check them as mostly be undefined
$lat = (isset($item->data->location->latitude))?$item->data->location->latitude:null; // Caches latitude as $lat
$lon = (isset($item->data->location->longtitude))?$item->data->location->longtitude:null; // Caches longitude as $lon
$images[] = array(
"title" => htmlspecialchars($title),
"src" => htmlspecialchars($src),
"lat" => htmlspecialchars($lat),
"lon" => htmlspecialchars($lon) // Consolidates variables to an array
);
}
file_put_contents($cache,json_encode($images)); //Save as json
}
}
//Debug out
print_r($images);
//Added curl for faster response
function get_curl($url){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $output;
}else{
return file_get_contents($url);
}
}

I used below code which is taken from your provided code and it seems to be working fine..
<?php
$client = "55447265ed444bb5b768ecb0765ba9cb";
$query = $_POST['q'];
$clnum = mt_rand(1,3);
$api = "https://api.instagram.com/v1/tags/".$query."/media/recent?client_id=".$client;
function get_curl($url) {
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $output;
} else{
return file_get_contents($url);
}
}
$images = array();
$cache = './cache.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$images = json_decode(file_get_contents($cache),true); //Decode as an json array
} else {
// Make an API request and create the cache file
// For example, gets the 32 most popular images on Instagram
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
$title = (isset($item->caption))?mb_substr($item->caption->text,0,70,"utf8"):null;
$src = $item->images->standard_resolution->url; //Caches standard res img path to variable $src
//Location coords seemed empty in the results but you would need to check them as mostly be undefined
$lat = (isset($item->data->location->latitude))?$item->data->location->latitude:null; // Caches latitude as $lat
$lon = (isset($item->data->location->longtitude))?$item->data->location->longtitude:null; // Caches longitude as $lon
$images[] = array(
"title" => htmlspecialchars($title),
"src" => htmlspecialchars($src),
"lat" => htmlspecialchars($lat),
"lon" => htmlspecialchars($lon) // Consolidates variables to an array
);
file_put_contents($cache,json_encode($images)); //Save as json
}
}
}
//Debug out
echo "<pre>";
print_r($images);

Yeah this works. But u need to use the cache function because the instagram api is really slow.
It doesn't matter if u take curl or file_get_contents.... the fastes way is jquery. Jquery uses the client machine php the server.. and if ure server stands away from the api servers so it takes time.

Related

How to use AZURE face recognition Rest API?

I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:

Curl and array values in curlopt_url does not work

i have a very weird issue with curl and url defined inside an array.
I have an array of url and i want perform an http GET on those urls with curl
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($station);
curl_close($station);
}
If i define my $array_station in the way below
$array_station=array("http://www.example.com","http://www.example2.com");
the code above with curl working flawlassy,but since my $array_station is build in the way below (i perform a scan of directory searchin a specific filename, then i clean the url), the curl does not work, no error showed and nothing happens..
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
$array_station=array();
$i=0;
foreach($it as $file) {
if (pathinfo($file, PATHINFO_FILENAME ) == "db_insert") {
$string = str_replace('/web/htdocs/', 'http://', $file.PHP_EOL);
$string2 = str_replace('/home','', $string);
$array_station[$i]=$string2;
$i++;
}
}
Doyou have some ideas? i'm giving up :-(
I'm on mobile right now so i cannot test it, but why are you adding a new line (PHP_EOL) to the url? Try to remove the new line or trim() the url at the end.
Add the lines of code below.
If there is a curl error it will report the error number.
If the request is made, it will show the HTTP request and response headers. The request is in $info and response header is in $head
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($station);
if (curl_errno($station)){
$response .= 'Retreive Base Page Error: ' . curl_error($station);
}
else {
$skip = intval(curl_getinfo($station, CURLINFO_HEADER_SIZE));
$head = substr($response ,0,$skip);
$response = substr($response ,$skip);
$info = var_export(curl_getinfo($station),true);
}
echo $head;
echo $info;
curl_close($station);
}

Redirect php script using CURL

I am trying to make a redirect php script, I want that script to check if the link exist and then redirect the user to the link, if it doesn't exist then it will get the next link and so on, but for some reason is not working, maybe you could give me some help on this.
<?php
$URL = 'http://www.site1.com';
$URL = 'http://www.site2.com';
$URL = 'http://www.site3.com';
$handlerr = curl_init($URL);
curl_setopt($handlerr, CURLOPT_RETURNTRANSFER, TRUE);
$resp = curl_exec($handlerr);
$ht = curl_getinfo($handlerr, CURLINFO_HTTP_CODE);
if ($ht == '404')
{ echo "Sorry the website is down atm, please come back later!";}
else { header('Location: '. $URL);}
?>
You are overwriting your $URL variable..
$URL = 'http://www.site1.com';
$URL = 'http://www.site2.com';
$URL = 'http://www.site3.com';
Put these urls in an array and go through it with a for each loop.
You have a few issues in your code. For 1, your $URL will overwrite itself, resulting in only 1 url in there. It needs to be an array:
array( 'http://www.site1.com', 'http://www.site2.com', 'http://www.site3.com' );
You can get many responses, not just a 404, so you should tell cURL to follow redirects. If the URL was a redirect itself, could get a 301 that redirects to a 200. So we want to follow that.
Try This:
<?php
function curlGet($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $httpcode == 200 ) {
return true;
}
return false;
}
$urlArray = array( 'http://www.site1.com', 'http://www.site2.com', 'http://www.site3.com' );
foreach ( $urlArray as $url ) {
if ( $result = curlGet($url) ) {
header('Location: ' . $url);
exit;
}
}
// if we made it here, we looped through every url
// and none of them worked
echo "No valid URLs found...";
http://php.net/manual/en/function.file-exists.php#74469
<?php
function url_exists($url) {
if (!$fp = curl_init($url)) return false;
return true;
}
?>
This will give you the url exists check.
to check multiple urls though, you need an array:
<?
$url_array = [];
$url_array[] = 'http://www.site1.com';
$url_array[] = 'http://www.site2.com';
$url_array[] = 'http://www.site3.com';
foreach ($url_array as $url) {
if url_exists($url){
// do what you need;
break;
}
}
?>
PS - this is completely untested, but should theoretically do what you need.

curl response showing nothing using within php

i am trying to get data from a url using curl. i've made a recursive function for this. i get the data successfully , but the problem what i am facing is that when no result is found against curl call, then the page show me nothing, only a blank page is shown.. no error at all. i've used var_dump() too for testing the response. but found nothing.
here is my recursive function
function recursive_get_scrap($offset, $page_size, $urls, $original_array){
ini_set('max_execution_time', 1800);
$of_set = $offset;
$pg_size = $page_size;
$off_sets = 'offset='.$of_set.'&page_size='.$pg_size.'';
$url = $urls.$off_sets;
$last_correct_array = $original_array;
$ch1 = curl_init();
// Disable SSL verification
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch1, CURLOPT_URL,$url);
// Execute
$result2 = curl_exec($ch1);
$info = curl_getinfo($ch1);
if(curl_errno($ch1))
{
echo 'error:' . curl_error($ch1);
//return $last_correct_array;
}
// Closing
curl_close($ch1);
if(!$result2 || strlen(trim($result2)) == 0 || $result2 == false){
echo 'no array';
}
if(isset($result2) && !empty($result2)){
echo 'in recursive function <br>';
$a1 = json_decode( $original_array, true );
$a2 = json_decode( $result2, true );
$temp_array = array_merge_recursive($a1, $a2 );
$last_correct_array = $temp_array;
$offset += 100;
$page_size = 100;
recursive_get_scrap($offset, $page_size, $urls, json_encode($last_correct_array));
}
}
now what i only want it that if noting is get against curl call then no array message should be displayed.
Use this option to curl_setopt():
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This will make curl_exec return the data instead of outputting it.
To see if it was successful you can then check $result and also
curl_error().

File_get_contents($url): failed to open stream

I have a script where I read a file using:
file_get_contents(urlencode($url));
I get this error:
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad request
I tried this, but I still get the error.
I've tried this:
ini_set('default_socket_timeout', 120);
This:
$opts = array('http'=>array('timeout' => 120));
$context = stream_context_create($opts);
$resul = file_get_contents($url,0,$context);
And this:
$opts = array('http'=>array('timeout' => 120,'header'=>'Connection : close'));
$context = stream_context_create($opts);
$resul = file_get_contents($url,false,$context);
Can you help me figure out why I get the error?
You need encode only "querystring", extract query and enconding this, after append enconded query you "url".
Note: file_get_contents requires allow_url_fopen=On in "php.ini", try use curl
Example (read my comments in code)
Note: This example get error in connection and http errors
<?php
//Set your page example
$uri = 'http://localhost/path/webservice.php?callback=&id=153&provenance=153&ret=a:1:{s:5:"infos";a:8:{s:8:"civilite";s:3:"Mme";s:5:"lname";s:0:"";s:5:"fname";s:8:"Nathalie";s:5:"email";s:17:"tometnata#free.fr";s:3:"tel";s:0:"";s:7:"adresse";s:0:"";s:6:"date_n";s:14:"10:"01/06/1969";s:2:"cp";s:0:"";}}';
//extract url
$parsed_url = parse_url($uri);
//Create fixed url
$fixed_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];
//If exists query
if (isset($parsed_url['query'])) {
$output = array();
$result = array();
//Extract querystring
parse_str($parsed_url['query'], $output);
//Encode values in querystring
forEach($output as $k => $v) {
$result[] = $k . '=' . rawurlencode($v);
}
//Append encoded querystring
$fixed_url .= '?' . implode('&', $result);
}
echo 'GET url: ', $fixed_url, '<br>';
//Get result in page
$ch = curl_init();
$timeout = 30; //set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $fixed_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
$errornum = curl_errno($ch);
$info = curl_getinfo($ch);
$status = (int) $info['http_code'];
if ($errornum !== 0) {
echo 'Error: ', curl_error($ch);
$file_contents = NULL;
} else if ($status !== 200) {
echo 'http_error: ', $status;
$file_contents = NULL;
} else {
echo 'Result:<hr>';
echo $file_contents;
}
curl_close($ch);
?>
Enable curl
Windows (Xampp): https://stackoverflow.com/a/1347340/1518921
Linux (like debian): https://stackoverflow.com/a/11724633/1518921
Mac OSX (probably outdated): https://stackoverflow.com/a/11354731/1518921

Categories