Related
hello I have the following code :
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$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 = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
second function:
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
third function:
function get_final_url($url){
$redirects = get_all_redirects($url);
if (count($redirects)>0){
return array_pop($redirects);
} else {
return $url;
}
}
when I try to use the code below:
echo get_final_url("https://www.facebook.com/9gag");
this is what I get :
https://www.facebook.com/unsupportedbrowser
I think it's because I should add an user agent for my function .
any help is appreciated.
Hello i'm trying to get the final URL after following HTTP redirections in PHP i used this solution :
but for some websites this function not working for example http://tassels.com.hk ---will be --> http://www.tassels.com.hk/en/index.php
/**
* get_redirect_url()
* Gets the address that the provided URL redirects to,
* or FALSE if there's no redirect.
*
* #param string $url
* #return string
*/
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$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 = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
/**
* get_all_redirects()
* Follows and collects all redirects, in order, for the given URL.
*
* #param string $url
* #return array
*/
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
/**
* get_final_url()
* Gets the address that the URL ultimately leads to.
* Returns $url itself if it isn't a redirect.
*
* #param string $url
* #return string
*/
function get_final_url($url){
$redirects = get_all_redirects($url);
if (count($redirects)>0){
return array_pop($redirects);
} else {
return $url;
}
}
echo get_final_url("http://tassels.com.hk");
I Found it my function don't follow javascript and meta tag redirection you can use regex to read the html code and find the javascript/jQuery or meta tag redirection
code to get url form javascript and meta tag redirection :
if (preg_match('/window\.location\.replace\([\s]{0,}[\"\'](.*)[\"\'][\s]{0,}\)/i', $response, $redirect_result['1']) ||
preg_match('/\$\(location\)\.attr\([\s]{0,}[\"\'][\s]{0,}href[\s]{0,}[\"\'][\s]{0,}\,[\s]{0,}[\"\'][\s]{0,}(.*)[\s]{0,}[\"\'][\s]{0,}\)/i', $response, $redirect_result['2']) ||
preg_match('/window\.location[\s]{0,}\=[\s]{0,}[\"\'](.*)[\"\']/i', $response, $redirect_result['3']) ||
preg_match('/window\.location\.href[\s]{0,}\=[\s]{0,}[\"\'](.*)[\"\']/i', $response, $redirect_result['4']) ||
preg_match('/window\.href[\s]{0,}\=[\s]{0,}[\"\'](.*)[\"\']/i', $response, $redirect_result['5']) ||
preg_match('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $response, $redirect_result['6'])) {
for ($i = 1; $i <= 6; $i++) {
if ($redirect_result[$i]) {
$window_location_final = $redirect_result[$i];
break;
}
}
$window_location_final = end($window_location_final);
if (substr($window_location_final, 0, 1) === '/' && valid_url(trim($redirect_url))) {
$window_location_final = rtrim($redirect_url, '/') . $window_location_final;
}
$window_location_final = valid_url(trim($window_location_final), TRUE) ? trim($window_location_final) : '';
if ($window_location_final) {
$redirect_url = $window_location_final;
}
return $redirect_url;
}
any body know that how to make check.php to verify the product key
when i check what are posting on check.php here the logs of method post
Sun, 18 May 2014 07:35:13 +0000a:6 {
s: 1: "u";
s: 44: "voN92KcXNxXQE1VrV+Muq4T/KuwziiyOT8rhwpcLZko=";
s: 1: "t";
s: 10: "1400398513";
s: 1: "p";
s: 88: "TVWb+BMcajJlu4+We5RfkCEMSRnvSjjx1pqTMuLRBftnWYkSJ2tMZuVezul2sYC5uXMW+qLLKJ7r87F5Cmp7QA==";
s: 1: "k";
s: 24: "493ppO3G+CVNZB0g3g6K2w==";
s: 1: "i";
s:128: "G133zJt4a1Csa+/LYCb7Q6NVvSNABx/Hyh3VxokaQy6AB/4vMxwSzh651jN+H5EBB3JCN54W2bzgBrEV3d7IpEfope3gO8iep9EbMDPujrlM5OSnLIdZx2g1aBLBGHLv";
s: 1: "v";
s: 24: "0rL3Iq61TBoDUi5piGG//A==";
}
and here is php code of that file if any body know how to make check.php please help me thanks
<?php
class Time {
protected $productKey = '';
protected $signature = null;
protected $expiry = 864000;
protected $installed = false;
protected $timestamp = 0;
protected $url = '';
/**
* License object constructor
*
* #access public
*/
public function __construct($productKey = array())
{
$this->url = 'http://www.example.com';
if (is_file(VISICHAT_ROOT . DS . 'config.php')) {
if (0 < filesize(VISICHAT_ROOT . DS . 'config.php')) {
$this->installed = true;
$productKey = Factory::getClass('config')->license;
}
}
$this->productKey = $productKey;
$this->fetchSignature();
}
/**
* Check whether the license is valid
*
* #return boolean
*/
public function isValid()
{
if ($this->getClass() == null) {
return false;
}
return $this->getClass()->check();
}
/**
* Downloads PHP class from the example server
*
* #return string
*/
public function fetchSignature()
{
if ($this->signature == null) {
$timestamp = 343;
if ($this->installed) {
$timestamp = Factory::getClass('Setting')->getNumber('signature_timestamp');
}
if ($timestamp < time() - $this->expiry) {
$this->timestamp = time();
$ch = curl_init();
$postdata = '&u=' . $this->encryptQuery(VIDEOCHAT_URL) . '&t=' . $this->timestamp . '&p=' . $this->encryptQuery(__FILE__) . '&k=' . $this->encryptQuery($this->productKey) . '&i=' . $this->encryptQuery(php_uname()) . '&v=' . $this->encryptQuery(Factory::getVersion());
if ($this->installed) {
$postdata .= '&d=' . $this->encryptQuery(Factory::getClass('config')->database) . '&a=' . $this->encryptQuery(Factory::getClass('Setting')->get('chat_app'));
}
curl_setopt($ch, CURLOPT_URL, 'license.example.com/check.php');
curl_setopt($ch, CURLOPT_USERAGENT, 'example');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->signature = curl_exec($ch);
if ($this->installed) {
$setting = Factory::getClass('Setting');
$setting->saveProperty('signature', $this->signature);
$setting->saveProperty('signature_timestamp', $this->timestamp);
}
curl_close($ch);
}
else {
$this->signature = Factory::getClass('Setting')->get('signature');
}
}
return $this->signature;
}
/**
* Get the signature object
*
* #return class
*/
public function getClass()
{
$failedMessage = 'License verification failed.<br />Please double check your license details at: <a href=\'https://www.example.com/customers/\' target=\'_blank\'>example Customers Portal</a>';
$signature = $this->fetchSignature();
if (0 < strlen($signature)) {
$signature = $this->decrypt($signature);
}
if (substr(trim($signature), 0, 5) == 'class') {
if (!class_exists('Signature')) {
eval($signature);
}
if (class_exists('Signature')) {
$object = new Signature();
if ($this->installed) {
$setting = Factory::getClass('Setting');
$setting->saveProperty('update_contents_field', $object->getNotification());
}
return $object;
}
if ($this->installed) {
$setting = Factory::getClass('Setting');
$setting->saveProperty('update_contents_field', '<span class=\'expired\'>' . $failedMessage . '</span>');
return null;
}
} else {
if ($this->installed) {
$setting = Factory::getClass('Setting');
$setting->saveProperty('update_contents_field', '<span class=\'expired\'>' . $failedMessage . '</span>');
}
}
}
/**
* Encrypt the raw data
*
* #return decrypted string
*/
public function decrypt($data)
{
if (strlen($data) == 0) {
return '';
}
return openssl_decrypt($data, 'aes128', $this->getPassword(), false, $this->getIV());
}
/**
* Encrypt the query string data before posting
*
* #return decrypted string
*/
public function encryptQuery($data)
{
return urlencode(openssl_encrypt($data, 'aes128', substr(md5($this->url . $this->timestamp), 0, 16), false, substr(sha1($this->timestamp . $this->url), 0, 16)));
}
/**
* Encrypt the data with the given key
*
* #return encrypted data
*/
public function hashToken($token)
{
$code = $this->getClass()->getCode();
if ($code == '') {
$code = rand(10000000, 90000000);
}
return sha1($token . $code);
}
/**
* Get the initialization vector for the AES function
*
* #return string
*/
public function getIV()
{
$signature = $this->productKey . $this->getVideoChatURL() . 'example';
return substr(sha1(md5($signature) . $signature . 'example.com'), 0, 16);
}
/**
* Get the initialization vector for the AES function
*
* #return string
*/
public function getPassword()
{
$timestamp = $this->timestamp;
if ($this->installed) {
$timestamp = Factory::getClass('Setting')->getNumber('signature_timestamp');
}
$signature = $this->productKey . $this->getVideoChatURL() . __FILE__ . 'example' . $timestamp;
return sha1(sha1($signature . 'example.com') . $signature . 'www.example.com');
}
/**
* Get the video chat URL in format of http://yoursite.com/ (removes www.)
*
* #return string
*/
public function getVideoChatURL()
{
$videoChatURL = VIDEOCHAT_URL;
if (substr($videoChatURL, 0, 8) == 'https://') {
if (substr($videoChatURL, 0, 12) == 'https://www.') {
$videoChatURL = 'https://' . substr($videoChatURL, 12);
}
} else {
if (substr($videoChatURL, 0, 7) == 'http://') {
if (substr($videoChatURL, 0, 11) == 'http://www.') {
$videoChatURL = 'http://' . substr($videoChatURL, 11);
}
}
}
if (substr($videoChatURL, -1) != '/') {
$videoChatURL .= '/';
}
return $videoChatURL;
}
}
if (!(defined('VISICHAT_START'))) {
exit('Access Denied');
(bool)true;
}
?>
I have a list of URL using multiple redirection like this:
url1=>url1redirect1=>url1redirect2=>url1redirect3= >url1final
url2=>url2redirect1=>url2redirect2=>url2final
...
The list is in this format:
url1
url2
url3
I don't own all the website in the redirection chain. Some of
them are third party tracking software.
Is there a way to capture all intermediary urls and the final url
and export them into a neat csv file like this:
url1,url2,url3,
url1redirect1,url2redirect1,url3redirect1,
url1redirect2,url2redirect2,url3redirect2,
url1redirect3,url2final,url3redirect3,
url1final,,url3redirect4,
...
I've found this function called get_all_redirects that can do the job:
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$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 = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
You can use it that way:
$urls = file_get_contents("urls.txt");
$url_list = explode("\n", $urls);
$file_content = '';
foreach ($url_list as $url){
$rez = get_all_redirects($url);
$file_content .= "$url,";
foreach ($rez as $v){
$file_content .= "$v,";
}
$file_content = substr($file_content,0, -1);
$file_content .= "\n";
}
file_put_contents("output.csv", $file_content);
urls.txt is a text file containing your urls (one url in each line):
http://url1.com
http://url2.com
http://url3.com
...
http://urlN.com
#Ghilas BELHADJ
I have put your code together and it doesn't put the redirects links in to the file
I tried to echo the links and it only echo's , the originals links.txt files
here the code
<?php
function get_redirect_url($url){
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$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 = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function get_all_redirects($url){
$redirects = array();
while ($newurl = get_redirect_url($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
?>
<?php
$urls = file_get_contents("https://tradingjunkie.space/links.txt");
$url_list = explode("\n", $urls);
$file_content = '';
foreach ($url_list as $url){
$rez = get_all_redirects($url);
$file_content .= "$url,";
foreach ($rez as $v){
$file_content .= "$v,";
}
$file_content = substr($file_content,0, -1);
$file_content .= "\n";
}
file_put_contents("results.txt", $file_content);
?>
i need some advise on this one, im having trouble figuring out the array that comes from google contacts, im already extracting the email from an example i found online, but now i need to extract the name of the contact and the phone number, i am seeing this information in the array doing a print_r() but dont know how to get it.
This is are my files:
gmail.php (this one prints all the emails, here i need also name and phone)
include_once 'GmailOath.php';
$oauth =new GmailOath($consumer_key, $consumer_secret, $argarray, $debug, $callback);
$getcontact_access=new GmailGetContacts();
$request_token=$oauth->rfc3986_decode($_GET['oauth_token']);
$request_token_secret=$oauth->rfc3986_decode($_SESSION['oauth_token_secret']);
$oauth_verifier= $oauth->rfc3986_decode($_GET['oauth_verifier']);
$contact_access = $getcontact_access->get_access_token($oauth,$request_token, $request_token_secret,$oauth_verifier, false, true, true);
$access_token=$oauth->rfc3986_decode($contact_access['oauth_token']);
$access_token_secret=$oauth->rfc3986_decode($contact_access['oauth_token_secret']);
$contacts= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,$emails_count);
foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo 'email: ' . $email["address"] .'<br>';
}
}
GmailOath.php
<?php
class GmailOath {
public $oauth_consumer_key;
public $oauth_consumer_secret;
public $progname;
public $debug;
public $callback;
function __construct($consumer_key, $consumer_secret, $argarray, $debug, $callback) {
$this->oauth_consumer_key = $consumer_key;
$this->oauth_consumer_secret = $consumer_secret;
$this->progname = $argarray;
$this->debug = $debug; // Set to 1 for verbose debugging output
$this->callback = $callback;
}
////////////////// global.php open//////////////
function logit($msg, $preamble=true) {
// date_default_timezone_set('America/Los_Angeles');
$now = date(DateTime::ISO8601, time());
error_log(($preamble ? "+++${now}:" : '') . $msg);
}
function do_get($url, $port=80, $headers=NULL) {
$retarr = array(); // Return value
$curl_opts = array(CURLOPT_URL => $url,
CURLOPT_PORT => $port,
CURLOPT_POST => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true);
if ($headers) {
$curl_opts[CURLOPT_HTTPHEADER] = $headers;
}
$response = $this->do_curl($curl_opts);
if (!empty($response)) {
$retarr = $response;
}
return $retarr;
}
function do_post($url, $postbody, $port=80, $headers=NULL) {
$retarr = array(); // Return value
$curl_opts = array(CURLOPT_URL => $url,
CURLOPT_PORT => $port,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POSTFIELDS => $postbody,
CURLOPT_RETURNTRANSFER => true);
if ($headers) {
$curl_opts[CURLOPT_HTTPHEADER] = $headers;
}
$response = do_curl($curl_opts);
if (!empty($response)) {
$retarr = $response;
}
return $retarr;
}
function do_curl($curl_opts) {
$retarr = array(); // Return value
if (!$curl_opts) {
if ($this->debug) {
$this->logit("do_curl:ERR:curl_opts is empty");
}
return $retarr;
}
// Open curl session
$ch = curl_init();
if (!$ch) {
if ($this->debug) {
$this->logit("do_curl:ERR:curl_init failed");
}
return $retarr;
}
// Set curl options that were passed in
curl_setopt_array($ch, $curl_opts);
// Ensure that we receive full header
curl_setopt($ch, CURLOPT_HEADER, true);
if ($this->debug) {
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
// Send the request and get the response
ob_start();
$response = curl_exec($ch);
$curl_spew = ob_get_contents();
ob_end_clean();
if ($this->debug && $curl_spew) {
$this->logit("do_curl:INFO:curl_spew begin");
$this->logit($curl_spew, false);
$this->logit("do_curl:INFO:curl_spew end");
}
// Check for errors
if (curl_errno($ch)) {
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
if ($this->debug) {
$this->logit("do_curl:ERR:$errno:$errmsg");
}
curl_close($ch);
unset($ch);
return $retarr;
}
if ($this->debug) {
$this->logit("do_curl:DBG:header sent begin");
$header_sent = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$this->logit($header_sent, false);
$this->logit("do_curl:DBG:header sent end");
}
// Get information about the transfer
$info = curl_getinfo($ch);
// Parse out header and body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
// Close curl session
curl_close($ch);
unset($ch);
if ($this->debug) {
$this->logit("do_curl:DBG:response received begin");
if (!empty($response)) {
$this->logit($response, false);
}
$this->logit("do_curl:DBG:response received end");
}
// Set return value
array_push($retarr, $info, $header, $body);
return $retarr;
}
function json_pretty_print($json, $html_output=false) {
$spacer = ' ';
$level = 1;
$indent = 0; // current indentation level
$pretty_json = '';
$in_string = false;
$len = strlen($json);
for ($c = 0; $c < $len; $c++) {
$char = $json[$c];
switch ($char) {
case '{':
case '[':
if (!$in_string) {
$indent += $level;
$pretty_json .= $char . "\n" . str_repeat($spacer, $indent);
} else {
$pretty_json .= $char;
}
break;
case '}':
case ']':
if (!$in_string) {
$indent -= $level;
$pretty_json .= "\n" . str_repeat($spacer, $indent) . $char;
} else {
$pretty_json .= $char;
}
break;
case ',':
if (!$in_string) {
$pretty_json .= ",\n" . str_repeat($spacer, $indent);
} else {
$pretty_json .= $char;
}
break;
case ':':
if (!$in_string) {
$pretty_json .= ": ";
} else {
$pretty_json .= $char;
}
break;
case '"':
if ($c > 0 && $json[$c - 1] != '\\') {
$in_string = !$in_string;
}
default:
$pretty_json .= $char;
break;
}
}
return ($html_output) ?
'<pre>' . htmlentities($pretty_json) . '</pre>' :
$pretty_json . "\n";
}
function oauth_http_build_query($params, $excludeOauthParams=false) {
$query_string = '';
if (!empty($params)) {
// rfc3986 encode both keys and values
$keys = $this->rfc3986_encode(array_keys($params));
$values = $this->rfc3986_encode(array_values($params));
$params = array_combine($keys, $values);
uksort($params, 'strcmp');
$kvpairs = array();
foreach ($params as $k => $v) {
if ($excludeOauthParams && substr($k, 0, 5) == 'oauth') {
continue;
}
if (is_array($v)) {
// If two or more parameters share the same name,
// they are sorted by their value. OAuth Spec: 9.1.1 (1)
natsort($v);
foreach ($v as $value_for_same_key) {
array_push($kvpairs, ($k . '=' . $value_for_same_key));
}
} else {
// For each parameter, the name is separated from the corresponding
// value by an '=' character (ASCII code 61). OAuth Spec: 9.1.1 (2)
array_push($kvpairs, ($k . '=' . $v));
}
}
// Each name-value pair is separated by an '&' character, ASCII code 38.
// OAuth Spec: 9.1.1 (2)
$query_string = implode('&', $kvpairs);
}
return $query_string;
}
function oauth_parse_str($query_string) {
$query_array = array();
if (isset($query_string)) {
// Separate single string into an array of "key=value" strings
$kvpairs = explode('&', $query_string);
// Separate each "key=value" string into an array[key] = value
foreach ($kvpairs as $pair) {
list($k, $v) = explode('=', $pair, 2);
// Handle the case where multiple values map to the same key
// by pulling those values into an array themselves
if (isset($query_array[$k])) {
// If the existing value is a scalar, turn it into an array
if (is_scalar($query_array[$k])) {
$query_array[$k] = array($query_array[$k]);
}
array_push($query_array[$k], $v);
} else {
$query_array[$k] = $v;
}
}
}
return $query_array;
}
function build_oauth_header($params, $realm='') {
$header = 'Authorization: OAuth';
foreach ($params as $k => $v) {
if (substr($k, 0, 5) == 'oauth') {
$header .= ',' . $this->rfc3986_encode($k) . '="' . $this->rfc3986_encode($v) . '"';
}
}
return $header;
}
function oauth_compute_plaintext_sig($consumer_secret, $token_secret) {
return ($consumer_secret . '&' . $token_secret);
}
function oauth_compute_hmac_sig($http_method, $url, $params, $consumer_secret, $token_secret) {
$base_string = $this->signature_base_string($http_method, $url, $params);
$signature_key = $this->rfc3986_encode($consumer_secret) . '&' . $this->rfc3986_encode($token_secret);
$sig = base64_encode(hash_hmac('sha1', $base_string, $signature_key, true));
if ($this->debug) {
logit("oauth_compute_hmac_sig:DBG:sig:$sig");
}
return $sig;
}
/**
* Make the URL conform to the format scheme://host/path
* #param string $url
* #return string the url in the form of scheme://host/path
*/
function normalize_url($url) {
$parts = parse_url($url);
$scheme = $parts['scheme'];
$host = $parts['host'];
$port = $parts['port'];
$path = $parts['path'];
if (!$port) {
$port = ($scheme == 'https') ? '443' : '80';
}
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
/**
* Returns the normalized signature base string of this request
* #param string $http_method
* #param string $url
* #param array $params
* The base string is defined as the method, the url and the
* parameters (normalized), each urlencoded and the concated with &.
* #see http://oauth.net/core/1.0/#rfc.section.A.5.1
*/
function signature_base_string($http_method, $url, $params) {
// Decompose and pull query params out of the url
$query_str = parse_url($url, PHP_URL_QUERY);
if ($query_str) {
$parsed_query = $this->oauth_parse_str($query_str);
// merge params from the url with params array from caller
$params = array_merge($params, $parsed_query);
}
// Remove oauth_signature from params array if present
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
// Create the signature base string. Yes, the $params are double encoded.
$base_string = $this->rfc3986_encode(strtoupper($http_method)) . '&' .
$this->rfc3986_encode($this->normalize_url($url)) . '&' .
$this->rfc3986_encode($this->oauth_http_build_query($params));
$this->logit("signature_base_string:INFO:normalized_base_string:$base_string");
return $base_string;
}
/**
* Encode input per RFC 3986
* #param string|array $raw_input
* #return string|array properly rfc3986 encoded raw_input
* If an array is passed in, rfc3896 encode all elements of the array.
* #link http://oauth.net/core/1.0/#encoding_parameters
*/
function rfc3986_encode($raw_input){
if (is_array($raw_input)) {
//return array_map($this->rfc3986_encode, $raw_input);
return array_map(array($this, 'rfc3986_encode'), $raw_input);
// return $this->rfc3986_encode($raw_input);
} else if (is_scalar($raw_input)) {
return str_replace('%7E', '~', rawurlencode($raw_input));
} else {
return '';
}
}
function rfc3986_decode($raw_input) {
return rawurldecode($raw_input);
}
}
class GmailGetContacts {
function get_request_token($oauth, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=false) {
$retarr = array(); // return value
$response = array();
$url = 'https://www.google.com/accounts/OAuthGetRequestToken';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
$params['oauth_callback'] = $oauth->callback;
$params['scope'] = 'https://www.google.com/m8/feeds';
// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
$oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
$oauth->oauth_consumer_secret, null);
} else {
echo "signature mathod not support";
}
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = $oauth->oauth_http_build_query($params, FALSE);
$header = $oauth->build_oauth_header($params);
$headers[] = $header;
} else {
$query_parameter_string = $oauth->oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
$oauth->logit("getreqtok:INFO:request_url:$request_url");
$oauth->logit("getreqtok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
$oauth->logit("getreqtok:INFO:request_url:$request_url");
$response = $oauth->do_get($request_url, 443, $headers);
}
// extract successful response
if (!empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = $oauth->oauth_parse_str($body);
if (!empty($body_parsed)) {
$oauth->logit("getreqtok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $body_parsed;
}
function get_access_token($oauth, $request_token, $request_token_secret, $oauth_verifier, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=true) {
$retarr = array(); // return value
$response = array();
$url = 'https://www.google.com/accounts/OAuthGetAccessToken';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
$params['oauth_token'] = $request_token;
$params['oauth_verifier'] = $oauth_verifier;
// compute signature and add it to the params list
if ($useHmacSha1Sig){
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
$oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
$oauth->oauth_consumer_secret, $request_token_secret);
} else {
echo "signature mathod not support";
}
//
if ($passOAuthInHeader) {
$query_parameter_string = $oauth->oauth_http_build_query($params, false);
$header = $oauth->build_oauth_header($params);
$headers[] = $header;
} else {
$query_parameter_string = $oauth->oauth_http_build_query($params);
}
if ($usePost){
$request_url = $url;
logit("getacctok:INFO:request_url:$request_url");
logit("getacctok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = $oauth->do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
$oauth->logit("getacctok:INFO:request_url:$request_url");
$response = $oauth->do_get($request_url, 443, $headers);
}
if (!empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = $oauth->oauth_parse_str($body);
if (!empty($body_parsed)) {
$oauth->logit("getacctok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $body_parsed;
}
function GetContacts($oauth, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true,$emails_count) {
$retarr = array(); // return value
$response = array();
$url = "https://www.google.com/m8/feeds/contacts/default/full";
$params['alt'] = 'json';
$params['max-results'] = $emails_count;
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
$params['oauth_token'] = $access_token;
// compute hmac-sha1 signature and add it to the params list
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
$oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
$oauth->oauth_consumer_secret, $access_token_secret);
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader){
$query_parameter_string = $oauth->oauth_http_build_query($params, false);
$header = $oauth->build_oauth_header($params);
$headers[] = $header;
} else {
$query_parameter_string = $oauth->oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost){
$request_url = $url;
$oauth->logit("callcontact:INFO:request_url:$request_url");
$oauth->logit("callcontact:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = $oauth->do_post($request_url, $query_parameter_string, 80, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
$oauth->logit("callcontact:INFO:request_url:$request_url");
$response = $oauth->do_get($request_url, 443, $headers);
}
if (!empty($response)) {
list($info, $header, $body) = $response;
if ($body) {
$oauth->logit("callcontact:INFO:response:");
$contact = json_decode($oauth->json_pretty_print($body), true);
//echo $contact['feed']['entry'][0]['gd$email'][0]['address'];
return $contact['feed']['entry'];
}
$retarr = $response;
}
return $retarr;
}
}
?>
Can you guys help me on this one please. Thanks in advance!
Not sure if this can help you as you say you have already used print_r (are you using with braces?), but to display the contents of an array in PHP, I have always used this with success.
It displays the integer ref of the array plus the data in each field.
<?php
echo "<pre>"; //print array to console
{print_r($variable_name);}
echo "</pre>";
?>
Alternately, have you checked the information here: https://developers.google.com/google-apps/contacts/v3/#retrieving_contacts_using_query_parameters
Or try the Context.IO API - there's a call specifically for pulling contacts: http://context.io/docs/2.0/accounts/contacts
Hoping any of these might help you.
For your case for first Phone andress and Note Field .
add where you loop the contacts in gmail.php
foreach($contacts as $k => $a)
{
$phone1 = end($a['gd$phoneNumber'][0]);
$note = end($a['content']);
$adress = end($a['gd$postalAddress'][0]);