how to calculate google backlinks using php - php

i want to create my own tool for back-links calculation using PHP. is there any api to fetech the data for back links

The full implementation in PHP would look something like this:
<?php
$domain = "example.com"; // Enter your domain here.
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&"
. "q=link:".$domain;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $domain);
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
$urls = array();
foreach($json->responseData->results as $result) // Loop through the objects in the result
$urls[] = $result->unescapedUrl; // and add the URL to the array.
?>
Basically you edit the domain variable at the top and it will fill the $urls array with unescaped URLs linking to the domain.
EDIT: I've edited the link to return 8 results. For more, you'll have to parse the pages and loop through them with the start parameter. See the Class Reference for more information.

Run a Google search with the URL prefixed by link: - for instance, link:www.mydomain.com.
While Google does provide a more specific backlink overview in their Webmaster Tools area (more info), I'm not sure they provide an external API for it.

since the question is "how to use in php code?" I assume you want to process on the server side as opposed to ajax on the client side. So use the Google URL link: hack in combination with curl
http://php.net/manual/en/book.curl.php

There is also a PHP class with many more options, that you can use: http://code.google.com/p/seostats/

function load_content ($url, $auth = true,$auth_param) {
$curl = curl_init();
$uagent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
if ($auth){
curl_setopt($curl, CURLOPT_USERPWD,$auth_param);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, $uagent);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 3);
$content = curl_exec($curl);
//$header = curl_getinfo($curl);
curl_close($curl);
$res['msg'] = "";//$header;
$res['content'] = $content;
return $res;
}
function google_indexed($url){
$html = load_content ($url,false,"");
return $html;
}
Example:
<?php
$domain = "google.com";
$indexed["google"] = google_indexed("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:$domain");
http://alex-kurilov.blogspot.com/2012/09/backlink-checker-google-php-example.html

For finding External links to the page : (external backlinks)
<?php
$url = "any url";
$result_in_html = file_get_contents("http://www.google.com/search?q=link:{$url}");
if (preg_match('/Results .*? of about (.*?) from/sim', $result_in_html, $regs))
{
$indexed_pages = trim(strip_tags($regs[1])); //use strip_tags to remove bold tags
echo ucwords($domain_name) . ' Has <u>' . $indexed_pages . '</u>external links to page';
} elseif (preg_match('/About (.*?) results/sim', $result_in_html, $regs))
{
$indexed_pages = trim(strip_tags($regs[1])); //use strip_tags to remove bold tags
echo ucwords($domain_name) . ' Has <u>' . $indexed_pages . '</u> external links to page';
} else
{
echo ucwords($domain_name) . ' Has Not Been Indexed # Google.com!';
}
?>
And to find internal backlinks :
<?php
$url = "any url";
$result_in_html = file_get_contents("http://www.google.com/search?q=site:{$url}");
if (preg_match('/Results .*? of about (.*?) from/sim', $result_in_html, $regs))
{
$indexed_pages = trim(strip_tags($regs[1])); //use strip_tags to remove bold tags
echo ucwords($domain_name) . ' Has <u>' . $indexed_pages . '</u> internal links to page';
} elseif (preg_match('/About (.*?) results/sim', $result_in_html, $regs))
{
$indexed_pages = trim(strip_tags($regs[1])); //use strip_tags to remove bold tags
echo ucwords($domain_name) . ' Has <u>' . $indexed_pages . '</u> internal links to page';
} else
{
echo ucwords($domain_name) . ' Has Not Been Indexed # Google.com!';
}
?>

Related

Plain text (HTML) in wordpress admin

I am developing my custom theme and I noticed that some of the links result in showing me plain text HTML instead of normal webpage. I tracked down the issue and found out that this happens when I include one custom php file inside my functions.php. I found that code on one of the tutorial on how to create social share buttons. If I comment include out everything works like a charm. I tried to investigate the file but I couldn't find anything wrong with it, could you please have a look what might be wrong?
<?php
function get_likes($url) {
$json_string = file_get_contents('https://api.facebook.com/method/links.getStats?urls=' . $url . '&format=json');
$json = json_decode($json_string, true);
if(isset($json[0]['total_count'])){
return intval( $json[0]['total_count'] );
} else { return 0;}
}
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
$json = json_decode($json_string, true);
if(isset($json['count'])){
return intval( $json['count'] );
} else {return 0;}
}
function get_plusones($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
if(isset($json[0]['result']['metadata']['globalCounts']['count'])){
return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
} else {return 0;}
}
function get_stumble($url) {
$json_string = file_get_contents('http://www.stumbleupon.com/services/1.01/badge.getinfo?url='.$url);
$json = json_decode($json_string, true);
if (isset($json['result']['views'])) {
return intval($json['result']['views']);
} else {return 0;}
}
if(isset($_GET["thisurl"])){
$thisUrl=$_GET["thisurl"];
$firstpart = substr("$thisUrl", 0, 22);
// Change http://medialoot.com to your own domain!
if ($firstpart == 'http://mdbootstrap.com') {
$data = "{";
$data .= '"facebook": '. json_encode(get_likes($thisUrl)) . ", ";
$data .= '"twitter": ' . json_encode(get_tweets($thisUrl)) . ", ";
$data .= '"gplus": ' . json_encode(get_plusones($thisUrl)) . ", ";
$data .= '"stumble": ' . json_encode(get_stumble($thisUrl)) . "}";
} else {
//throw error
$data = 'ERROR - you are trying to use this script for something outside of the allowed domain';
}
} else {
$data = '';
}
header('Content-Type: application/json');
echo $data;
?>
You are echoing the contents of $data – I guess thats also what you are seeing if I understood that correctly.
If the code is included in your functions.php like this, it probably gets executed as soon as the functions.php file is loaded, which might be too late or too early.
To be able to control when the code executes, you should have a look into WordPress Hooks and hook your code into this mechanism.
If you can tell me more about what exactly you are trying to do, I might be able to give a more detailed answer.
Just as a sidenote: Take care not to cross over into Plugin territory with your theme. As soon as you are trying to do anything more than modifying the look of something, it doesn't belong into functions.php anymore but a separate plugin.

Google Api Search Result is not working

To get the search result from google, I used those code. Sometimes it work perfectly but sometimes it don't give any answer. Now don't know what is the problem. I need those result for research purpose so I had to browse for different query
if (isset($_GET['content'])) {
// echo $_GET['content'];
$url_all=NULL;
$visibleurl=NULL;
$title_all=NULL;
$content_all=NULL;
$mainstring=NULL;
$searchTerm=$_GET['content'];
$endpoint = 'web';
$key= 'angelic-bazaar-111103';
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
$args['q'] = $searchTerm;
$args['v'] = '1.0';
$url .= '?'.http_build_query($args, '', '&');
$url .="&rsz=". 8;
$ch = curl_init()or die("Cannot init");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($ch)or die("cannot execute");
curl_close($ch);
$json = json_decode($body);
for($x=0;$x<count($json->responseData->results);$x++){
$url_all .="#$*##" . $json->responseData->results[$x]->url;
$visibleurl .="#$*##" . $json->responseData->results[$x]->visibleUrl;
$title_all .="#$*##" . $json->responseData->results[$x]->title;
$content_all .="#$*##" . $json->responseData->results[$x]->content;
}
**EDIT
This Code works well sometimes, other times it doesn't, Is it a problem of google or something else. I get this error
$json->responseData->results for this showing "Trying to get property of non-object in"

PHP curl_setopt : Variable Not working in place of URL string

I use CURL in php, and I use CURL something like this
$url = "http://exampledomain.com";
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
This is not working, but if I wrote "http://exampledomain.com" in place of "$smsURL" at curl_setopt (); It will work fine. Where is issue in my code? did I miss something?
Original Code
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . $_POST['txt_customer_contact_no'];
$url .= '&sender=' . strtoupper($saloon_info['saloon_name']);
$url .= '&is_payor=' . $this->conf['sms_is_payor'];
$url .= '&pay_amount=' . $this->conf['sms_pay_amount'];
$url .= '&token=5ce7467e9ec045cbbac448ba5a422a02';
//$url .= '&customer_num=' . $this->conf['sms_customer_num'] . $saloon_id;
$url .= '&customer_num=' . $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name']; //$value['id_employee'];
//$sms_msg = "Hey. Recalling that I await tomorrow at. " . $appointment_time . " Regards " . $employee_name . ", " . $saloon_name . ". ";
$sms_msg = t('msg_sms_book_appointment', array('%emp_name' => $employee_name, '%saloon_name' => $_POST['hdn_selected_saloon_name'], '%time' => $appointment_time));
$url .= '&sms_msg=' . $sms_msg;
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
Thanks
You compose the URL from pieces but you don't encode the values properly. There are characters that have special meaning in URLs (/, ?, &, =, %, , + and a few more). They have to be encoded when they appear in the values from the query string, in order to retain their literal meaning.
PHP helps you for this goal with function urlencode() that can be used to encode each value individually when you create a query string. Something like this:
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . urlencode($_POST['txt_customer_contact_no']);
$url .= '&sender=' . urlencode(strtoupper($saloon_info['saloon_name']));
...
But, because this is a tedious work, it also provides an easier method. Put all the values you need into an array, using the names of the variables as keys, then pass the array to function http_build_query(). There is no need to call urlencode() any more; http_build_query() takes care of it. Also it puts ampersands (&) between the variables and equals (=) where they belong.
The code is like this:
$url = $this->conf['sms_getway_url'];
// Prepare the values to put into the query string
$vars = array();
$vars['recipient'] = $_POST['txt_customer_contact_no'];
$vars['sender'] = strtoupper($saloon_info['saloon_name']);
$vars['is_payor'] = $this->conf['sms_is_payor'];
$vars['pay_amount'] = $this->conf['sms_pay_amount'];
$vars['token'] = '5ce7467e9ec045cbbac448ba5a422a02';
$vars['customer_num'] = $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name'];
$sms_msg = t('msg_sms_book_appointment', array(
'%emp_name' => $employee_name,
'%saloon_name' => $_POST['hdn_selected_saloon_name'],
'%time' => $appointment_time,
));
$vars['sms_msg'] = $sms_msg;
// Now, the magic comes into place
$smsURL = $url.'?'.http_build_query($vars);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
if (! curl_exec ($curl)) {
// Something went wrong. Check the status code (at least)
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Do something here.
// If $code >= 500 then the remote server encountered an internal error
// retry later or ask them to fix it
// If 400 <= $code < 500 then there is a problem with the request:
// maybe the resource is not there (404, 410)
// or you are not allowed to access it (403)
// or something else.
echo('Failure sending the SMS. HTTP status code is '.$code."\n");
}
curl_close ($curl);
Check the list of HTTP status codes for more details.

How to make curl call for remote url which contain space

This question is continuation of my previous question
<?php
$remoteFile = 'http://cdn/bucket/my textfile.txt';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
print_r($data)
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>
I am using above code to get the file size in server side from CDN url but when I use the CDN url with space in it. it is throwing below error
page not found 09/18/2014 - 16:54 http://cdn/bucket/my textfile.txt
Can I make curl call for remote url which contain space ?
To give little bit more info on this
I am having interface where user will be saving file to CDN (so user
can give whatever title user want, it may contain space )and all
information in saved in back end db. I have another interface where I
retrieve the saved information and show it in my page along with file
size which I am getting using above code.
You have to encode your url's which have space's in it.
echo urlencode('http://cdn/bucket/my textfile.txt');
Ref: urlencode
or you can use,
echo '<a href="http://example.com/department_list_script/',
rawurlencode('sales and marketing/Miami'), '">';
Ref: rawurlencode
Yes you need to URL / URI encode
In an encoded URL, the spaces are encoded as: %20, so your URL would be: http://cdn/bucket/my%20textfile.txt so you could just use this url.
Or as this is PHP, you could use the urlencode function.
ref: http://php.net/manual/en/function.urlencode.php
e.g.
$remoteFile = urlencode('http://cdn/bucket/my textfile.txt');
or
$ch = curl_init(urlencode($remoteFile));

Get the real video URL from a url

I'm trying to get the real file URL from a url that doesn't show up the real file name.
My url is like this http://video.premium.com/file/ee7bfec921cfbe16e6f08e282992b99670a00ca3/3
If I could get the real file url I could stream it directly online through a web player, but it needs .mp4 or other file format to play, just the url http://video.premium.com/file/ee7bfec921cfbe16e6f08e282992b99670a00ca3/3 doesnt work.
but when I open the URL using VLC media player, it works. doesn't work with online flash or other players..
Is this even possible? Anyway to do this?
With curl, use this: It follows the redirect until it finds the endpoint. In the included code I used goo.gl to shorten the url to a rando image. You will see the output is the original link (and it would output whatever number of redirects and their URLs), and the final redirect to the actual file. I think this is what you are looking for. I did not write this originally, but found it somewhere some time ago and reused it many times again with tweaking when needed. It seems to fit well in many places. Glad to pass it on. I think it might help to achieve what you are looking for.
<?php
function follow_redirect($url){
$redirect_url = null;
if(function_exists("curl_init")){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
else{
$url_parts = parse_url($url);
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80));
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = fread($sock, 2048);
fclose($sock);
}
$header = "Location: ";
$pos = strpos($response, $header);
if($pos === false){
return false;
}
else{
$pos += strlen($header);
$redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
return $redirect_url;
}
}
$url = 'http://goo.gl/66VJB';
echo '<ol>';
while(($newurl = follow_redirect($url)) !== false){
echo '<li>', $url, '</li>';
$url = $newurl;
}
echo '</ol>';
echo '', $url, '';
?>
Output:
http://goo.gl/66VJB
http://1.bp.blogspot.com/_XE0TDW07Noo/TOSVQXZtgAI/AAAAAAAAELo/aG80jZ7u_fo/s1600/aptitude_test.gif

Categories