screenshot using googlepagespeed api - php

Below is my code to capture the screenshot of of webpage. But i get the output of the same as how in the image below. Kindly suggest on what is the mistake i am committing. Also kindly suggest the method to save this screenshot to the server?
<?php
$url='https://www.google.com';
$stratedy = 'mobile' ;
$apiReqUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';
$apiKey = 'my_api_key' ;
$curl = curl_init();
curl_setopt($curl, CURL_OPTURL, $apiReqUrl.'?url='.$reqUrl.'
&key='.$apiKey.'&screenshot=true&strategy='.$stratedy);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($curl);
$data = json_decode($result, true);
$img = str_replace(array('_','-'), array('/','+'), $data['screenshot']
['data']);
echo '<img src="data:image/jpeg;base64,'.$img.'">';
?>

If you can, try using the HTML version from Generating Screenshots of URLs using Google's secret magic API. All you need to do is to call the API and it's free (I guess).
For example in PHP:
<?php
$url = "https://praveen.science/";
// Hit the Google PageSpeed Insights API.
// Catch: Your server needs to allow file_get_contents() to make this run. Or you need to use cURL.
$response = file_get_contents('https://www.googleapis.com/pagespeedonline/v2/runPagespeed?screenshot=true&url='.urlencode($url));
// Convert the JSON response into an array.
$googlePagespeedObject = json_decode($response, true);
// Grab the Screenshot data.
$screenshot = $googlePagespeedObject['screenshot']['data'];
// Fix url encoded base64
$screenshot = str_replace(array('_','-'), array('/','+'), $screenshot);
// Build the Data URI scheme and spit out an <img /> Tag.
echo "<img src=\"data:image/jpeg;base64,{$screenshot}\" alt=\"Screenshot\" />";
// Or.. base64 decode and store
file_put_contents('...', base64_decode($screenshot));
Or in JavaScript:
$(function() {
// Get the URL.
var url = "https://praveen.science/";
// Prepare the URL.
url = encodeURIComponent(url);
// Hit the Google Page Speed API.
$.get("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + url, function(data) {
// Get the screenshot data.
var screenshot = data.screenshot;
// Convert the Google's Data to Data URI scheme.
var imageData = screenshot.data.replace(/_/g, "/").replace(/-/g, "+");
// Build the Data URI.
var dataURI = "data:" + screenshot.mime_type + ";base64," + imageData;
// Set the image's source.
$("img").attr("src", dataURI);
});
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<h1>Hard Coded Screenshot of my Website:</h1>
<img src="//placehold.it/300x50?text=Loading+Screenshot..." alt="Screenshot" />

There are a lot of APIs available on the internet to take screenshots. Something like https://www.purplescreenshots.com/ has example of integrating screenshots too.

Related

Get Google Search Images using php

Search on Google images with car keyword & get car images.
I found two links to implement like this,
PHP class to retrieve multiple images from Google using curl multi
handler
Google image API using cURL
implement also but it gave 4 random images not more than that.
Question: How to get car images in PHP using keyword i want to implement like we search on Google?
Any suggestion will be appreciated!!!
You could use the PHP Simple HTML DOM library for this:
<?php
include "simple_html_dom.php";
$search_query = "ENTER YOUR SEARCH QUERY HERE";
$search_query = urlencode( $search_query );
$html = file_get_html( "https://www.google.com/search?q=$search_query&tbm=isch" );
$image_container = $html->find('div#rcnt', 0);
$images = $image_container->find('img');
$image_count = 10; //Enter the amount of images to be shown
$i = 0;
foreach($images as $image){
if($i == $image_count) break;
$i++;
// DO with the image whatever you want here (the image element is '$image'):
echo $image;
}
This will print a specific number of images (number is set in '$image_count').
For more information on the PHP Simple HTML DOM library click here.
i am not very much sure about this ,but still google gives a nice documentation about this.
$url = "https://ajax.googleapis.com/ajax/services/search/images?" .
"v=1.0&q=barack%20obama&userip=INSERT-USER-IP";
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */);
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...
this is from the official Google's developer guide regarding image searching.
for more reference you can have a reference of the same here.
https://developers.google.com/image-search/v1/jsondevguide#json_snippets_php
in $url you must set the search keywords.

fetch all youtube videos using curl

I'm a beginner at PHP. I have one task in my project, which is to fetch all videos from a YouTube link using curl in PHP. Is it possible to show all videos from YouTube?
I found this code with a Google search:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.youtube.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
echo $contents;
curl_close ($ch);
?>
It shows the YouTube site, but when I click any video it will not play.
You can get data from youtube oemebed interface in two formats Xml and Json which returns metadata about a video:
http://www.youtube.com/oembed?url={videoUrlHere}&format=json
Using your example, a call to:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json
So, You can do like this:
$url = "Your_Youtube_video_link";
Example :
$url = "http://www.youtube.com/watch?v=m7svJHmgJqs"
$youtube = "http://www.youtube.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo $result['html'];
Try it...Hope it will help you.
You could use curl to retrieve the Google main page (or an alternative page) and parse the returned html using a library such as html5lib. If you wanted to try this approach the first step could be to 'view source' on the relevant page and look at how the links are structured.
A more elegant way to approach the problem could be to use the Youtube API (a way to interact with the Youtube system), which may allow you to retrieve the links directly. e.g it may be possible to just ask the Youtube API to send you the links. Try this.
You can also get all youtube's channel videos using file_get_contents
bellow is sample and working code
<?php
$Youtube_API_Key = ""; // you can obtain api key : https://developers.google.com/youtube/registering_an_application
$Youtube_channel_id = "";
$TotalVideso = 50; // 50 is max , if you want more video you need Youtube secret key.
$order= "date"; ////allowed order : date,rating,relevance,title,videocount,viewcount
$url = "https://www.googleapis.com/youtube/v3/search?key=".$Youtube_API_Key."&channelId=".$Youtube_channel_id."&part=id&order=".$order."&maxResults=".$TotalVideso."&format=json";
$data = file_get_contents($url);
$JsonDecodeData=json_decode($data, true);
print_r($data);
?>

How to get Vine video url

I love vinepeek and want to make something better.
I have the Vine link e.g. http://vine.co/v/bJqWrOHjMmU, however this is a link to a page, not the video URL.
I know it's new, but does Vine have an API, or how else would I be able to get the url of the video? I'm still puzzled as to how Vinepeek gets the video url?
It is in the page source; you could parse it with a JavaScript bookmarklet
function qry(sr) {
var qa = [];
for (var prs of sr.split('&')) {
var pra = prs.split('=');
qa[pra[0]] = pra[1];
}
return qa;
}
var alpha = document.querySelector('[name=flashvars]').getAttribute('value');
var bravo = qry(alpha);
bravo.src;
Result
https://vines.s3.amazonaws.com/videos/08C49094-DFB4-46DF-8110-EEEC7D4D6115-1133-000000B8AD9BE72C_1.0.1.mp4?versionId=TQGtC5O7G7H34TleFA2LF0Er9tI8VZUe
Source
The JSON API has the following URL: http://vinepeek.com/video
You can use a web inspector / console / developer tool to check the source code.
<video id="post_html5_api" class="vjs-tech" loop="" preload="auto" src="https://vines.s3.amazonaws.com/videos/08C49094-DFB4-46DF-8110-EEEC7D4D6115-1133-000000B8AD9BE72C_1.0.1.mp4?versionId=TQGtC5O7G7H34TleFA2LF0Er9tI8VZUe"></video>
The URL is:
https://vines.s3.amazonaws.com/videos/08C49094-DFB4-46DF-8110-EEEC7D4D6115-1133-000000B8AD9BE72C_1.0.1.mp4?versionId=TQGtC5O7G7H34TleFA2LF0Er9tI8VZUe
This is a simple function which i use to get video src from curl result.
http://vine.co/v/bJqWrOHjMmU
function getVineVideoFromUrl($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
preg_match('/twitter:player:stream.*content="(.*)"/', $res, $output);
return $output[1];
}
result
https://vines.s3.amazonaws.com/v/videos/08C49094-DFB4-46DF-8110-EEEC7D4D6115-1133-000000B8AD9BE72C_1.0.1.mp4?versionId=ms6ePoPeFm6NQZkeNHegV3k_ZLV4bz9x

equal of php in asp.net

what is the equivalent code in asp.net language???
<?php
$ch = curl_init("http://irnafiarco.com/queue");
$request["queue"] = file_get_contents("/path_to_my_xml_file/my_xml_file.xml");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($ch);
curl_close ($ch);
echo $response;
?>
in http://irnafiarco.com/queue a Listener that get requst xml file and saver xml file.
Using WebRequest, this will be the basic code
var req = WebRequest.Create(#"http://irnafiarco.com/queue"))
// prepare the request
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
// push the file contents into request body
var data = "queue=" + System.IO.File.OpenText(filePath).ReadToEnd();
var bytes = System.Text.Encoding.Ascii.GetBytes(data );
request.ContentLength = bytes.Length;
var rs = req.GetRequestStream();
rs.Write(bytes, 0, bytes.Length);
rs.Close ();
// get the response
var resp = req.GetResponse();
var sr = new System.IO.StreamReader(resp.GetResponseStream());
var result = sr.ReadToEnd();
Disclaimer: untested code
EDIT:
Added the post parameter name ("queue") which I have missed in first draft. Also added content-length for the request. This code should get you started. The basic idea is you need to simulate exact post request generated by PHP code. Use tool such as Fiddler/ Firebug on FF to inspect & compare request/response from PHP and .NET code.
Further, I suspect that the PHP code may generating request with content type as multipart/form-data. However, I believe that server should also able to support the post body with application/x-www-form-urlencoded (because we have only one parameter in body) but in case it doesn't work and you must generate POST body as multipart/form-data then it will be little more involved. See this SO question where accepted answer has given the sample code for the same : Upload files with HTTPWebrequest (multipart/form-data)
Take a look at WebRequest, WebProxy classes which are inline with what you're after...
WebRequest request = WebRequest.Create(url);
request.Proxy = new WebProxy("http://blahblahblah", true)
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// handle response here
Also, see here, and here, though may not be relevant for your implementation
Examples of using these to fetch XML abound, i.e.:
System.Net.HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("yourURL.xml");
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
System.Net.HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
System.IO.Stream responseStream = webResponse.GetResponseStream();
System.Xml.XmlTextReader reader = new XmlTextReader(responseStream);
//Do something meaningful with the reader here
reader.Close();
webResponse.Close();

Not storing POST data (json)

I have this bit of javascript:
var jsonString = "some string of json";
$.post('proxy.php', { data : jsonString }, function(response) {
var print = response;
alert(print);
and this bit of PHP (in proxy.php):
$json = $_POST['json'];
//set POST variables, THIS IS WHERE I WANT TO POST TO!
$url = 'http://my.site.com/post';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, "data=" . urlencode($json));
//execute post (the result will be something like {"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"})
$result = curl_exec($ch);
$response = json_decode($result);
$imageHref = 'http://my.site.com/render?picid=' . $response['picid'];
//close connection
curl_close($ch);
echo $imageHref;
I am trying to post data to an external site using a proxy. From there, I append the picid that the site responds with and append it to the URL to get the image URL.
Am I missing something here? I am not getting anything in response and it seems like my data is not even being posted (when I try echo $json after the first line in proxy.php, I get an empty string). Why am I not able to echo the JSON? Is my implementation correct?
Thanks!
In your Javascript code, you are using this :
{ data : jsonString }
So, from your PHP code, should you not be reading from $_POST['data'], instead of $_POST['json'] ?
If necessary, you can use var_dump() to see what's in $_POST :
var_dump($_POST);
Edit after the comment : if you are getting a JSON result such as this :
{"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"}
This is a JSON object -- which means, after decoding it, you should access it as an object in PHP :
$response = json_decode($result);
echo $response->pic;
Note : I don't see a picid element in that object -- maybe you should instead use pic ?
Here too, though, you might want to use var_dump(), to see how your data looks like :
var_dump($response);
try this:
$json = $_POST['data'];
or even better do
var_dump($_POST);
to see what is actually in your post when you start

Categories