Unable to print Json array in php table format - php

Here is my code to print Json array in table format
<?php include 'header.php' ; ?>
<?php
$base_url = "http://tic.sugarcrmdemo.com/rest/v10";
$username = "sereneintegration";
$password = "Sugar123!";
function call(
$url,
$oauthtoken='',
$type='GET',
$arguments=array(),
$encodeData=true,
$returnHeaders=false
)
{
$type = strtoupper($type);
if ($type == 'GET')
{
$url.= "?" . http_build_query($arguments);
}
$curl_request = curl_init($url);
if ($type == 'POST')
{
curl_setopt($curl_request, CURLOPT_POST, 1);
}
elseif ($type == 'PUT')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
}
elseif ($type == 'DELETE')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl_request, CURLOPT_HEADER, $returnHeaders);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
if (!empty($oauthtoken))
{
$token = array("oauth-token: {$oauthtoken}");
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $token);
}
if (!empty($arguments) && $type !== 'GET')
{
if ($encodeData)
{
$arguments = json_encode($arguments);
}
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $arguments);
}
$result = curl_exec($curl_request);
if ($returnHeaders)
{
list($headers, $content) = explode("\r\n\r\n", $result ,2);
foreach (explode("\r\n",$headers) as $header)
{
header($header);
}
return trim($content);
}
curl_close($curl_request);
$response = json_decode($result);
return $response;
}
$url = $base_url . "/oauth2/token";
$oauth2_token_arguments = array(
"grant_type" => "password",
"client_id" => "sugar",
"client_secret" => "",
"username" => $username,
"password" => $password,
"platform" => "base"
);
$oauth2_token_response = call($url, '', 'POST', $oauth2_token_arguments);
$url = $base_url . "/SREV1_Property/48f10d2c-eca2-9163-77fb-56c7677240e2/link/srev1_property_srev1_unit";
$unit_response = call($url, $oauth2_token_response->access_token, 'GET');
$json = $unit_response;
$jd = json_decode(json_encode($json), 1);
$floors = array();
foreach ($jd->records AS $key => $obj) {
$f = $obj->unit_floor;
$id = $obj->id;
$name = $obj->name;
$suite = $obj->suite;
$sf = $obj->sf;
$floors[$f][$suite]['name'] = $name;
$floors[$f][$suite]['id'] = $id;
$floors[$f][$suite]['sf'] = $sf;
}
//sort floors in desc order
krsort($floors);
foreach($floors as $id => $floor){
ksort($floors[$id]);
}
print '<table class="data-table" >';
foreach($floors as $floor => $suites){
$sqf = 0;
print '<tr>';
print '<td>FLOOR: '.$floor.'</td>';
foreach($suites AS $suite => $value){
$sqf += $value['sf'];
print'<td>Suite:'.$suite.'<br>SF:'.$value['sf'].'</td>';
}
print '<td>'.$sqf.'</td>';
print '</tr>';
}
print '</table>';
?>
But when I try to run this code i am getting an errors like "Trying to get property of non-object " and " Invalid argument supplied for foreach()". Please help me,.
Here is the expected output

Related

GET request on the route https://coderbyte.com/api/challenges/json/json-cleaning and then clean the object

This is the practice code:
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
print_r(json_decode($data, true));
?>
and I tried this
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
print_r(json_decode($data, true));
echo "<pre>" . print_r($newdata, 1) . "</pre>";
foreach ($newdata as $key => $value) {
if (!is_array($value)) {
echo "key: " . $key . " Value: " . $value . "<br>";
if (!empty($value)) && $value !== "-" && $value !== "N/A") {
$new_array[$key] = $value;
}
}
else {
foreach ($value as $k => $v) {
if (!empty($v) && $v !== "-" && $v !== "N/A") {
$new_array[$key][$k] = $v;
}
}
}
}
echo "<pre>" . print_r($new_array, 1) . "</pre>";
?>
although i am unable to succeeded
To perform a GET request on the route https://coderbyte.com/api/challenges/json/json-cleaning and then clean the object according to the following rules: Remove all keys that have values of N/A, -, or empty strings. If one of these values appear in an array, remove that single item from the array. Then console log the modified object as a string.
How to accomplish this?
Can be done with recursive function as follow:
function clean_obj($data) {
if (is_array($data)) {
foreach ($data as $key => $val) {
if ($val == 'N/A' || $val == '-' || $val == '') {
unset($data[$key]);
}
if (is_array($val)) {
$data[$key] = clean_obj($val);
}
}
}
return $data;
}
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$newData = json_decode($data, true);
$new_array=clean_obj($newData);
echo "<pre>" . print_r($new_array, 1) . "</pre>";
Try this
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$newData = json_decode($data, true);
filterNAPlusEmptyStrings($newData);
function filterNAPlusEmptyStrings(&$newData) {
foreach ($newData as $key => $value ) {
if (is_array($value)) {
filterNAPlusEmptyStrings($value);
}
if ($value === '' || $value === 'N/A' || $value === '-' ) {
unset($newData[$key]);
}
}
}
echo "<pre>" . print_r($newData, 1) . "</pre>";
TRY THIS:-
<?php
// Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count); // 128
?>
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/json-cleaning');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$arr = json_decode($data, true);
$myArr = array();
foreach($arr as $keys => $values) {
if(is_array($values)){
$otherArr = array();
foreach($values as $key=>$value){
if (!($value == 'N/A' || $value == '-' || $value == ''))
$otherArr[$key] = $value;
}
$myArr[$keys] = $otherArr;
}
else{
if (!($values == 'N/A' || $values == '-' || $values == ''))
$myArr[$keys] = $values;
}
}
print_r($myArr);
?>

How to use AZURE face recognition Rest API?

I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:

PHP: Line running twice when a POST is called first

I have a few lines of code in a script, and if part A executes, then part B executes TWICE (that is: the cron.php file is added to the crontab TWICE). This is odd, because if I comment out part A, part B only executes ONCE.
Why is this happening? What am I missing?
// Part A
$url = "https://api.sendgrid.com/apiv2/customer.add.json";
$input = "api_user=$sendgrid_user_account&api_key=$sendgrid_master_password&username=$custname.domain.com&website=$sendgridsubuserdomain&password=$sendgridsubusersmtppass&con firm_password=$sendgridsubusersmtppass&first_name=$first&last_name=$last&address=$sendgridsubuseraddress&city=$sendgridsubusercity&state=$sendgridsubuserstate&zip=$ sendgridsubuserzip&email=$email&country=$sendgridsubusercountry&company=$custname&phone=$sendgridsubuserphone";
$sendgrid_output = postCurl($url, $input, false, false);
// Part B
chdir("/etc/nginx/");
exec("2>&1 ./addcron.sh $custname");
Supporting functions:
function postUrl($url, $data, $headers = null, $json_format = true) { // json format is only used if $data is also formatted as a string
$curl_result = postCurl($url, $data);
if($curl_result != false) return $curl_result;
$data_query = http_build_query($data);
$opts = array('http' => array('method' => 'POST', 'content' => $data_query));
if($headers) {
$opts['http']['header'] = $headers;
}
else {
$opts['http']['header'] = "Content-type: application/x-www-form-urlencoded";
}
$st = stream_context_create($opts);
$fp = fopen($url, 'rb', false, $st);
if(!$fp) {
//$result = http_post_fields($url, $data); TODO: add back in once AWS's PHP updated to include http_post_fields function
//if(!empty($result)) return $result;
}
$result = stream_get_contents($fp);
if(empty($result)) {
//$result = http_post_fields($url, $data);
//if(!empty($result)) return $result;
}
return false; // if all else fails, false
}
function postCurl($url, $values, $boolean_return = false, $json_format = true) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if(is_array($values)) {
$values_string = "";
foreach($values as $key => $value) $values_string .= "$key=$value&";
$values_string = substr($values_string, 0, -1); // remove last "&"
}
else { // if it's not an array, assume JSON
$values_string = $values;
if($json_format == true) {
$input_array = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($values_string));
}
else {
$input_array = array('Content-Length: ' . strlen($values_string));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $input_array);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $values_string);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
if($boolean_return == false) curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
The addcron.sh script:
#!/bin/bash
custname="$1"
(crontab -l; echo "* * * * * /usr/bin/php -f /var/www/html/$custname/cron/cron.php" ) | crontab -

DOM Xpath wordpress Grab content

I have a plugin that i want to modified but im stuck here is the php function:
function wpr_ezinemarkpost($keyword,$num,$start,$optional="",$comments="",$options,$template,$ua,$proxy,$proxytype,$proxyuser) {
global $wpdb,$wpr_table_templates;
$page = $start / 20;
$page = (string) $page;
$page = explode(".", $page);
$page=(int)$page[0];
$page++;
if($page == 0) {$page = 1;}
$prep = floor($start / 20);
$numb = $start - $prep * 20;
$search_url = "http://www.freewptube.com/demo4/";
// make the cURL request to $search_url
if ( function_exists('curl_init') ) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
if($proxy != "") {
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
if($proxyuser) {curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);}
if($proxytype == "socks") {curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);}
}
curl_setopt($ch, CURLOPT_URL,$search_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
$html = curl_exec($ch);
if (!$html) {
$return["error"]["module"] = "Article";
$return["error"]["reason"] = "cURL Error";
$return["error"]["message"] = __("cURL Error Number $search_url","wprobot").curl_errno($ch).": ".curl_error($ch);
return $return;
}
curl_close($ch);
} else {
$html = #file_get_contents($search_url);
if (!$html) {
$return["error"]["module"] = "Article";
$return["error"]["reason"] = "cURL Error";
$return["error"]["message"] = __("cURL is not installed on this server!","wprobot");
return $return;
}
}
// parse the html into a DOMDocument
$dom = new DOMDocument();
#$dom->loadHTML($html);
// Grab Product Links
$xpath = new DOMXPath($dom);
$paras = $xpath->query("//div[#class='boxtitle']//h2/a");
$x = 0;
$end = $numb + $num;
if($paras->length == 0) {
$posts["error"]["module"] = "Article";
$posts["error"]["reason"] = "No content";
$posts["error"]["message"] = __("No (more) articles found. $search_url","wprobot");
return $posts;
}
if($end > $paras->length) { $end = $paras->length;}
for ($i = $numb; $i < $end; $i++ ) {
$para = $paras->item($i);
if(empty($para)) {
$posts["error"]["module"] = "Article";
$posts["error"]["reason"] = "No content";
$posts["error"]["message"] = __("No (more) articles found. $search_url","wprobot");
print_r($posts);
return $posts;
} else {
$target_url = $para->getAttribute('href');
// make the cURL request to $search_url
if ( function_exists('curl_init') ) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
if($proxy != "") {
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
if($proxyuser) {curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);}
if($proxytype == "socks") {curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);}
}
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
$html = curl_exec($ch);
if (!$html) {
$return["error"]["module"] = "Article";
$return["error"]["reason"] = "cURL Error";
$return["error"]["message"] = __("cURL Error Number $search_url","wprobot").curl_errno($ch).": ".curl_error($ch);
return $return;
}
curl_close($ch);
} else {
$html = #file_get_contents($target_url);
if (!$html) {
$return["error"]["module"] = "Article";
$return["error"]["reason"] = "cURL Error";
$return["error"]["message"] = __("cURL is not installed on this server!","wprobot");
return $return;
}
}
// parse the html into a DOMDocument
$dom = new DOMDocument();
#$dom->loadHTML($html);
// Grab Article Title
$xpath1 = new DOMXPath($dom);
$paras1 = $xpath1->query("//div[#class='textsection']/h2");
$para1 = $paras1->item(0);
$title = $para1->textContent;
if (empty($title)) {
$return["error"]["module"] = "Article";
$return["error"]["reason"] = "IncNum";
$return["error"]["message"] = __("Video content skipped. ","wprobot");
return $return;
}
// Grab Article
$xpath2 = new DOMXPath($dom);
$paras2 = $xpath2->query("//div[#id='screen']/div[#class='videosection']");
$para2 = $paras2->item(0);
$string = $dom->saveXml($para2);
if ($options['wpr_eza_striplinks']=='yes') {$string = wpr_strip_selected_tags($string, array('a'));}
$articlebody .= $string. ' ';
// Grab Ressource Box
$xpath3 = new DOMXPath($dom);
$paras3 = $xpath3->query("//div[#id='extras']//h4/a");
$ressourcetext = "";
for ($y = 0; $y < $paras3->length; $y++ ) { //$paras->length
$para3 = $paras3->item($y);
$ressourcetext .= $dom->saveXml($para3);
}
$title = utf8_decode($title);
// Split into Pages
if($options['wpr_eza_split'] == "yes") {
$articlebody = wordwrap($articlebody, $options['wpr_eza_splitlength'], "<!--nextpage-->");
}
$post = $template;
$post = wpr_random_tags($post);
$post = str_replace("{article}", $articlebody, $post);
$post = str_replace("{authortext}", $ressourcetext, $post);
$noqkeyword = str_replace('"', '', $keyword2);
$post = str_replace("{keyword}", $noqkeyword, $post);
$post = str_replace("{Keyword}", ucwords($noqkeyword), $post);
$post = str_replace("{title}", $title, $post);
$post = str_replace("{url}", $target_url, $post);
if(function_exists("wpr_rewrite_partial")) {
$post = wpr_rewrite_partial($post,$options);
}
if(function_exists("wpr_translate_partial")) {
$post = wpr_translate_partial($post);
}
/* We are adding a call to this function to ensure that our keyword is used at least once */
$posts[$x]["unique"] = $target_url;
$posts[$x]["title"] = $title;
$posts[$x]["content"] = $post;
$x++;
}
}
return $posts;
}
i already made it to grab the title and the embed video but i want to also grab the thumbails located at the homepage. how can we make the thumbnails go to the top of the embed video code? by the way this is a wordpress plugin that i am modifying for me to use.
thanks

Twitter oAuth: getting an error 215

I have the following code in one of my classes:
public function build_httpheader ($options = NULL)
{
if (!$this->oauth_token && !$this->oauth_token_secret && !$this->http_method) {
throw new Exception('The oauth_token, oauth_token_secret and the http method must be set');
}
$url = $this->base_uri;
$url_curl = $this->base_uri;
if ($options) {
$this->options = $options;
$url .= '?';
$url_curl .= '?';
$count = count($options);
foreach($options as $key => $value) {
$count = $count--;
if ($count) {
$url .= '&'.$key.'='.$value;
$url_curl .= '&'.$key.'='.rawurlencode($value);
} else {
$url .= $key.'='.$value;
$url_curl .= $key.'='.rawurlencode($value);
}
}
}
$this->url = $url_curl;
/**
* #internal Create a 32 chars unique string to
* use as the nonce value
*/
list($usec, $sec) = explode(" ", microtime());
$usec = str_replace('0.', '', $usec);
$nonce_str = utf8_encode($sec.$usec.'ABCD'.$sec);
$oauth_nonce = md5($nonce_str);
/**
* #internal Create the initial oAuth array
*/
$oauth = array (
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => $this->$oauth_nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $this->oauth_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
/**
* #internal generate basic info
*/
$t_oauth = array();
ksort($oauth);
foreach($oauth as $key=>$value){
$t_oauth[] = "$key=" . rawurlencode($value);
}
$base_info = $this->http_method."&" . rawurlencode($url) . '&' . rawurlencode(implode('&', $t_oauth));
$composite_key = rawurlencode($this->consumer_secret) . '&' . rawurlencode($this->oauth_token_secret);
$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth_string = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value) {
$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$oauth_string .= implode(', ', $values);
$this->http_headers = array ($oauth_string, 'Expect:');
}
public function tw_curl_api_call ()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->http_headers);
if ($this->http_method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
}
if ( ($this->http_method != 'POST') && ($this->http_method != 'GET') ) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->http_method);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$result = json_decode(curl_exec($ch), TRUE);
$info = curl_getinfo($ch);
curl_close($ch);
return array ('result' => $result, 'info' => $info);
}
Another script uses this class as follows:
$options = array ('resources' => 'help,users,search,statuses');
$tw_wrapper->build_httpheader ($options);
$results = $tw_wrapper->tw_curl_api_call ();
I am however getting an error 215 (bad authentication data). Any ideas (I am aware that there are existing PHP oAuth classes and twitter wrappers, but it does not seem as if any of them has completely migrated to the 1.1 API).
Have you had a look at Codebird? It has support for 1.1 and works well for what I've needed. YMWV of course.
A simple example:
Codebird::setConsumerKey('KEY', 'SECRET');
$cb = Codebird::getInstance();
$cb->setToken('AUTH_KEY', 'AUTH_SECRET');
$result = $cb->statuses_userTimeline(array(
'include_rts' => true,
'screen_name' => 'hansnilsson',
));

Categories