Dealing with curl to get count for tweets containing that url - php

I was using following code to decode the tinyurl from twitter:
function MyURLDecode($url)
{
$ch = #curl_init($url);
#curl_setopt($ch, CURLOPT_HEADER, TRUE);
#curl_setopt($ch, CURLOPT_NOBODY, TRUE);
#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$url_resp = #curl_exec($ch);
preg_match('/Location:\s+(.*)\n/i', $url_resp, $i);
if (!isset($i[1]))
{
return $url;
}
return $i[1];
}
$url = MyURLDecode($url);
This using this result to get tweet count value:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Above code works fine. But due to some issue I need to change the Url Decoding function which is as below:
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
This code gives decoded url correctly, infact with better accuracy then previous one but now result of this does not works with this function:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Rather givig correct count value, it always gives 0.
Can someone tell me what is wrong here?
full code:
<?php
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
/* preg_match('/Location:\s+(.*)\n/i', $fileContents, $i);
if (!isset($i[1]))
{
return '';
}
else
$fileContents = $i[1]; */
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
$url = expandUrlLongApi('http://t.co/SFdM0wjtGA');
echo "Url is : $url <br/>";
$url = get_twitter_url_count($url);
?>

Related

How can I create Google Alert in php

I have spend much of time on it, but did not found any working solution ...
I have tried the following code .. but always else case is running "didnt find login form1"
I have tried another coders11 inplemented api but it was also deprecated...
I found many other solutions but not in php ... I am looking for solution in php...
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');```
You can't login into google alerts with password and email anymore, you would have to pre-create cookies by login into google alerts and copying them out of the dev console and then passing them as argument when doing a curl request. Check out my google alerts api i have written in php. Maybe that helps you out https://github.com/Trivo25/google-alerts-api-php

php json_decode is not working Properly

When i am Decoding using commented "$jsonString" String it is working very well.
But after using curl it is not working, showing Null.
Please Help Me in this.
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
$url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';
if ($jsonString != '') {
$json = str_replace(array('[', ']'), '', $jsonString);
echo $json;
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
}
}
After curl I used following concept to get only JSON data from HTML Page.
1) fetchData.php
$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;
2) JSONprocess.php
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
ob_start(); // begin collecting output
include_once 'fetchData.php';
$result = ob_get_clean(); // Completed collecting output
// Now it will show & take only JSON Data from Div Tag
$json = str_replace(array('[', ']'), '', $result);
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}

Codeigniter recursive function not returning value

I have issues with codeigniter recursive function which returns blank value. below is my function.
function recursive_data($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = (array) json_decode($output);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
return $instaArr['data'];
} else {
return $this->recursive_data($instaArr['pagination']->next_url);
}
}
I am calling this above function in another function like this
$return_data = $this->recursive_data($url);
It is returning blank value. while it is printing the value in commented code print_r($instaArr)
please use it as bellow.
function recursive_data($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = json_decode($output,true);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
return $instaArr['data'];
} else {
return $this->recursive_data($instaArr['pagination']->next_url);
}
}
What about this ?
function recursive_data($url)
{
$objCurlData = new stdClass();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = (array) json_decode($output);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
$objCurlData->data = $instaArr['data'];
} else {
$objCurlData->objChild = $this->recursive_data($instaArr['pagination']->next_url);
}
return $objCurlData;
}

PHP function return a variable?

I am having a hard time finding out how to get a function to return a variable that I can use outside of the function, I have tried
return $response
and I have tried
return $response = $anothervariable
But the only way I have been able to get it to work is to echo the response and just put the html in there, I know there is a better way to do this, the problem is I can't figure it out. Any help would be appreciated!
function OpenCNAM($ph) {
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
if($response != "") {
echo '<span title="'.$response.'"> 888-452-1505</span>';
} else {
echo 'Nada';
}
}
OpenCNAM('8884521505');
return $response;
is correct statement. It will return $response variable if program flow reaches at that point.
You can also pass parameters to function by reference like &$any_variable to set it with the desire value inside the function and play with it outside the function, after the function call.
Remodify your code like this.
function OpenCNAM($ph) {
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
$str="";
if($response != "") {
$str= '<span title="'.$response.'"> 888-452-1505</span>';
} else {
$str= 'Nada';
}
return $str; //<---------- We are returning here
}
echo OpenCNAM('8884521505'); //<--- If you want to output.. or just $response = OpenCNAM('43535'); if you want to store it in a variable.
Just return the texts then you can do like this
function OpenCNAM($ph) {
//...
//...
if($response != "") {
return '<span title="'.$response.'"> 888-452-1505</span>';
} else {
return 'Nada';
}
}
$foo = OpenCNAM('8884521505');
Then, you can do what you want with $foo
try this
function OpenCNAM($ph)
{
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
if($response != "")
{
$res = '<span title="'.$response.'"> 888-452-1505</span>';
}
else
{
$res = 'Nada';
}
return $res;
}
$return_res = OpenCNAM('8884521505');
echo $return_res;
If you aren't going to use the returned data anywhere, then echo will do just fine for you.
This was answered in PHP echo function return value vs echo inside function

Retrieve Android Market mylibrary with curl

I am trying to retrieve this page using curl in php. This page of course requires you to log in because it displays different apps for each user. I have been following the work done on this page, however am not having much success.
So far, in his example I am able to successfully populate the auth variable with the auth token. In the next step however (Below the comment for logging into Android Market) I run into troubles. The output variable that he says should have a 302 code results in a "The document has moved" page which links me back to the Google log in page.
Here is a pastebin to show exactly what I am trying. http://pastebin.com/9Fs9GWxk
Additionally if anyone knows what steps I need to do after this to actually get the page I need that would be amazing. Thanks
Here is something I came up with today for this question that has been modified to work for you:
<?php
$USERNAME = 'you#gmail';
$PASSWORD = 'yourpasswd';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIEJAR);
curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIEJAR);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&continue=https://market.android.com/mylibrary');
$data = curl_exec($ch);
$formFields = getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
// var_dump($formFields);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
//var_dump($result);
if (preg_match('/^2\d{2}/', curl_getinfo($ch, CURLINFO_HTTP_CODE)) == false) {
die("Login failed");
var_dump(curl_getinfo($ch), $result);
} else {
curl_setopt($ch, CURLOPT_URL, 'https://market.android.com/mylibrary');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPGET, true);
$result = curl_exec($ch);
echo $result;
}
function getFormFields($data)
{
if (preg_match('/(<form id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}

Categories