How To I make Cache File In PHP of Json Request - php

I'm Try To Make Cache File For Quick JSON Response But I have Some Problems I got This Code in a PHP File But I can't Understand How I can Make This For $url JSON File for any JSON Response I have No Many Skills Please anyone can help me for This Problem
Here is Code What i'm Try
function data_get_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$uaa = $_SERVER['HTTP_USER_AGENT'];
curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: $uaa");
return curl_exec($ch);
}
$cache_option = true;
$id = 'DU6IdS2gVog';
$url = 'https://www.googleapis.com/youtube/v3/videos?key={Youtube_Api}&fields=items(snippet(title%2Cdescription%2Ctags))&part=snippet&id=DU6IdS2gVog';
$data = data_get_curl($url);
header('Content-Type: application/json');
echo $data;
function cache_set($id,$data,$time = 84600){
if(!$cache_option) return NULL;
$name = ROOT."/cache/".md5($id).".json";
$fh = fopen($name, "w");
fwrite($fh, serialize($data));
fclose($fh);
}
function cache_get($id){
if(!$cache_option) return NULL;
$file = ROOT."/cache/".md5($id).".json";
if(file_exists($file)){
if(time() - 84600 < filemtime($file)){
return unserialize(data_get_curl($file));
}else{
unlink($file);
}
}
return NULL;
}
Thanks In Advance

There are multiple errors with your code. You can simple use file_put_contents to add content to cache file.
Try the following example
$id = 'DU6IdS2gVog';
$cache_path = 'cache/';
$filename = $cache_path.md5($id);
if( file_exists($filename) && ( time() - 84600 < filemtime($filename) ) )
{
$data = json_decode(file_get_contents($filename), true);
}
else
{
$data = data_get_curl('https://www.googleapis.com/youtube/v3/videos?key={API_KEY}&fields=items(snippet(title%2Cdescription%2Ctags))&part=snippet&id='.$id);
file_put_contents($filename, $data);
$data = json_decode($data, true);
}

Related

Using cURL and foreach, huge loading time

I have the following code:
<?php
error_reporting(E_ALL & ~E_NOTICE);
set_time_limit(1000);
$f = $_GET['location'].'.txt';
if ( !file_exists($f) ) {
die('Location unavailable');
}
$file = fopen($f, "r");
$i = 0;
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
function get_thumbs($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
foreach ($members as $id){
// echo $id.'<br/>'; // do something with each line from text file here
$id = preg_replace('/\s+/', '', $id);
$link = 'http://localhost/cvr/get.php?id='.$id.'&thumb=yes&title=yes';
$content = get_thumbs($link);
echo $content;
}
?>
Where get.php is using almost the same above cURL function to grab data from a website and parse it.
In the txt file I have like 20 ids to get data from but the foreach seems to take a very long time to load, like 30+ seconds. Any advice?
I am a php beginner so please don't be very hard on me.
Thanks!

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

How to check a url exist or not in php

I want to check the url
http://example.com/file.txt
exist or not in php. How can I do it?
if(! # file_get_contents('http://www.domain.com/file.txt')){
echo 'path doesn't exist';
}
This is the easiest way to do it. If you are unfamiliar with the #, that will instruct the function to return false if it would have otherwise thrown an error
The would use the PHP curl extension:
$ch = curl_init(); // set up curl
curl_setopt( $ch, CURLOPT_URL, $url ); // the url to request
if ( false===( $response = curl_exec( $ch ) ) ){ // fetch remote contents
$error = curl_error( $ch );
// doesn't exist
}
curl_close( $ch ); // close the resource
Try this function on Ping site and return result in PHP.
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
$filename="http://example.com/file.txt";
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
OR
if (fopen($filename, "r"))
{
echo "File Exists";
}
else
{
echo "Can't Connect to File";
}
I am agree with the response, I got success by doing this
$url = "http://example.com/file.txt";
if(! #(file_get_contents($url))){
return false;
}
$content = file_get_contents($url);
return $content;
You can follow the code to check the file exist at location or not.

how to save facebook profile picture using php graph Api

i am using this curl class for saving the file -->
class CurlHelper
{
/**
* Downloads a file from a url and returns the temporary file path.
* #param string $url
* #return string The file path
*/
public static function downloadFile($url, $options = array())
{
if (!is_array($options))
$options = array();
$options = array_merge(array(
'connectionTimeout' => 5, // seconds
'timeout' => 10, // seconds
'sslVerifyPeer' => false,
'followLocation' => false, // if true, limit recursive redirection by
'maxRedirs' => 1, // setting value for "maxRedirs"
), $options);
// create a temporary file (we are assuming that we can write to the system's temporary directory)
$tempFileName = tempnam(sys_get_temp_dir(), '');
$fh = fopen($tempFileName, 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $options['connectionTimeout']);
curl_setopt($curl, CURLOPT_TIMEOUT, $options['timeout']);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $options['sslVerifyPeer']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $options['followLocation']);
curl_setopt($curl, CURLOPT_MAXREDIRS, $options['maxRedirs']);
curl_exec($curl);
curl_close($curl);
fclose($fh);
return $tempFileName;
}
}
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$sourceFilePath = CurlHelper::downloadFile($url, array(
'followLocation' => true,
'maxRedirs' => 5,
));
this above code will give me the temporary url in $sourceFilePath variable now i want to store that image in my image folder. I am stuck here...please help me in this...thank you in advance.
There is a pretty easy option for this:
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$data = file_get_contents($url);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
You don´t even need anything else then.
Or if file_get_contents is disabled (usually it isn´t), this should also work:
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://graph.facebook.com/shashankvaishnav/picture');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
Edit: This is not possible anymore, since you can´t use the username for API calls anymore. You have to use an (App Scoped) ID after authorizing a User with the Facebook API instead of the username.
$filename = 'abcd.jpg';
$to = 'image/'.$filename;
if(copy($sourceFilePath,$to))
echo 'copied';
else
echo 'error';
$profile_Image = 'http://graph.facebook.com/shashankvaishnav/picture';
$userImage = $picturtmp_name . '.jpg'; // insert $userImage in db table field.
$savepath = '/images/';
insert_user_picture($savepath, $profile_Image, $userImage);
function insert_user_picture($path, $profile_Image, $userImage) {
$thumb_image = file_get_contents($profile_Image);
$thumb_file = $path . $userImage;
file_put_contents($thumb_file, $thumb_image);
}
$fbprofileimage = file_get_contents('http://graph.facebook.com/senthilbp/picture/');
file_put_contents('senthilbp.gif', $fbprofileimage);

Save facebook profile image using cURL

I'm trying to save a users profile image on facebook using CURL. When I use the code below, I save a jpeg image but it has zero bytes in it. But if I exchange the url value to https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/211398_812269356_2295463_n.jpg, which is where http://graph.facebook.com/' . $user_id . '/picture?type=large redirects the browser, the image is saved without a problem. What am I doing wrong here?
<?php
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
?>
There is a redirect, so you have to add this option for curl
// safemode if off:
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
but if you have safemode if on, then:
// safemode if on:
<?php
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
#list($header, $data) = #explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = #parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (#$url['query']?'?'.$url['query']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init(get_right_url($url));
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
If you can't process the redirect, try this instead:
Make the request to https://graph.facebook.com/<USER ID>?fields=picture and parse the response, which will be in JSON format and look like this - e.g. for Zuck you get this response:
{
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg"
}
Then make your curl request directly to retrieve the image from that cloud storage URL
set
CURLOPT_FOLLOWLOCATION to true
so that it follows the 301/302 redirect the reads the image file from final location.
i.e.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
I managed to do it this way, works perfectly fine:
$data = file_get_contents('https://graph.facebook.com/[App-Scoped-ID]/picture?width=378&height=378&access_token=[Access-Token]');
$file = fopen('fbphoto.jpg', 'w+');
fputs($file, $data);
fclose($file);
You just need an App Access Token (APPID . '|' . APPSECRET), and you can specify width and height.
You can also add "redirect=false" to the URL, to get a JSON object with the URL (For example: https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpa1...)
CURLOPT_FOLLOWLOCATION has been removed in PHP5.4, so it´s not really an option anymore.

Categories