Php Curl and Json - php

My question is I want to get acess my fb friends using curl and decode into json then i want to show only those friends whose name starting with letter a such as aman,adam etc pls help me..Following is my code.
<?php
// create a new cURL resource
$json_url="https://graph.facebook.com/100001513782830/friends?access_token=AAACEdEose0cBAPdK62FSjs4RvA21efqc8ZBKyzAesT5r4VSpu0XScAYDtKrCxk4PmcRBVzE2SLiGvs2d5FeXvZAD72ZCShwge3vk4DQqRAb8vLlm1W3";
$ch = curl_init( $json_url );
// Configuring curl options
/* $options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch );
*/// Getting results
$result = curl_exec($ch); // Getting jSON result string
$obj = json_decode($result, true);
foreach($obj[data] as $p)
{
echo '
Name: '.$p[name][first].'
Age: '.$p[age].'
';
}

You will offcourse try not to hardcode "a" but for this purpose :
foreach($obj[data] as $p){
if(strtolower(substr(trim($p[name][first]),0,1)) == 'a'){
echo 'Name: '.$p[name][first].'Age: '.$p[age];
}
}

Btw, it is not a good idea to post security tokens (in URL) to public places.
Since the name is string, you can simply iterate over that array and filter by name:
$letter = 'A';
foreach($obj['data'] as $p) {
if ($p['name'][0] == $letter) {
// do something with $p
}
}
But there is a little problem with UTF-8 -- this solution (and that one with substr too) will not work on multibyte characters. So you need to use mb_substr instead of plain substr function:
foreach($obj['data'] as $p) {
if(mb_strtolower(mb_substr($p['name'], 0, 1))) == 'Á'){
echo "Name: ", $p['name'], "\n",
"Age: ", $p['age'], "\n";
}
}

Related

PHP: Assign array to variable

i've tried a lot of things to achieve this but none of them seem to
work. Im using PHP 7.4
Let's say i have this:
$othervar = array();
$var = array(1, 2, 3);
$othervar = $var;
THIS doesn't work for me, var_dump($othervar) returns
array(1) { [0]=> string(5) "Array" }
I've tried using array_push, i DON'T WANT to use array_merge because i
need to assign two arrays to one variable. This is what i need to do:
$variable = array();
$variable["type1"] = $data; //Array 1
$variable["type2"] = $otherData; //Array 2
This doesn't work either.
Barmar showed me here that this works so i must be doing it wrong somewhere else.
I'll explan the whole code:
To login to my webpage, i send a request trough AJAX request with jQuery.
function SendData(data, btn, actionOnSuccess, shouldReplace = false, elementToReplace = "", getServerData = true, htmlData = "") {
if (!loading)
{
ToggleLoading();
data.push({name: "action", value: $(btn).data("action")});
data.push({name: "attr", value: JSON.stringify($(btn).data("attr"))});
$.post("SendRequest.php", data)
.done(function (r) {
if (!r.success)
//ajax sent and received but it has an error
else
//ajax sent and it was successfull
})
.fail(function () {
//ajax call failed
});
}
else {
//This determines if some request is already executing or not.
}
}
"action" and "attr" are encrypted values that i send to reference some actions on the system (i'll show more here):
The code goes from AJAX to SendRequest.php where it executes an action let's say, login.
The first lines of SendRequest.php are:
require "Functions.php";
$apiAction = Decrypt($_POST["action"]); //Action
$actionData = json_decode(Decrypt($_POST["attr"])); //Attr
$finalPost = $_POST;
foreach ($actionData as $key => $value) { $finalPost[$key] = $value; }
$finalPost["loggedin_ip"] = $_SERVER['REMOTE_ADDR'];
$result = APICall($apiAction, $finalPost);
Then, this is what i want to achieve to communicate with my API:
function APICall($option, $data = array())
{
session_start();
$post = array("uData" => ArrayToAPI($_SESSION), "uPost" => ArrayToAPI($data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_URL, "https://apiurl?" . $option); //option is the ACTION to perform on API (let's say "login") it is an encrypted word on a data-attr atribute on every form/button that creates a communication with API.
$returned = curl_exec($ch);
curl_close ($ch);
$newData = json_decode($returned, true);
return $newData;
}
function ArrayToAPI($array)
{
$toApiData = array();
foreach ($array as $key=>$value) {
if (is_array($value))
$toApiData[$key] = ArrayToAPI($value);
else
$toApiData[$key] = Encrypt($value);
}
return $toApiData;
}
This is what i have on API side:
ob_start();
var_dump($_POST);
$result = ob_get_clean();
$api->EndRequest(false, array("errorDesc" => "a - " . $result));
function EndRequest(bool $task_completed, array $data = array())
{
$jsonData = array();
$jsonData['success'] = $task_completed;
$jsonData['data'] = $data;
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsonData, JSON_FORCE_OBJECT);
exit;
}
This ALWAYS returns
array(2) { ["uData"]=> string(5) "Array" ["uPost"]=> string(5) "Array" }
I hope im more clear now, thanks.
The problem is with the request being sent out from your code because of this line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
CURLOPT_POSTFIELDS doesn't support multi-level arrays. Your array values (which the keys are pointing to) are cast to string, which ends up as Array. Use:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
.. instead to "properly" serialize multidimensional arrays in a post request ("properly" as there are many ways to do just that, but it matches the expected PHP format - with [] to denote arrays).

This Convert JSON in Array return is null

i need to transform a return JSON in Array, to manipulate the datas, but when trying this array is set as null, i need to use htmlentities why this return in navigator was messed up by the html tags in json.
this is my code:
<?php
try {
function listTasks() {
$ch = curl_init();
$token = 'token';
curl_setopt_array($ch, [
CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/idproject/tasks/',
CURLOPT_HTTPHEADER => [
'X-Angie-AuthApiToken: ' . $token,
'Content-Type: application/json',
'x-li-format: json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);
$result = curl_exec($ch);
$convert = htmlentities($result, ENT_QUOTES, "UTF-8"); // I did this because the return had html tags that gave problems with browser display.
$tasks = json_decode($convert, true); //this is where I convert to array.
// for ($i = 0; $i < count($tasks); $i++) {
// if ($tasks[$i]["task_list_id"] == 55979) {
// $tasks_name[$i] = $tasks[$i]["name"];
// }
// }
var_dump($tasks); // here it returns null, if I put print_r returns nothing.
curl_close($ch);
// return $result;
}
listTasks();
} catch (Error $e) {
print_r($e->getMessage());
}
// print_r($_POST['email']));
Someone can help me ?
If the cURL request is responding with JSON format, you should first decode it with
json_decode
and then only use
htmlentities
for specify array index'es to clear the text. Then you use your way, you make json string invalid, so it can't decode it. anyway you should not use mixed json with html to display it into browser.

Failed read content from json using cUrl in PHP

This is my first time using web service. My PHP server get the json data from .net server where it is encoded to base64.
The problem now is, i failed to read each attribute inside the data:
Array ( [JSONDataResult] => {"file":"iVBORw0KGgoAAAANSUhEUgAAALUAAAEZCAYAAADR+mSIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABhuSURBVHhe7ZiBcuM4smz3\/3\/6PkrPjCgfppBMFWB53DgRx2whs4raMWJ7dv938H8\/KVGdjkR1qrNx+13ehftTU9w889V+vVOHqySq05GoTnU2br\/Lu3B\/aoqbZ77ar3fqcJVEdToS1anOxu13eRfuT01x88xX+\/VOHa6SqE5HojrV2bj9Lu\/C\/akpbp75ar\/eeT2cids\/O6cp6Xzad6zeR1PS+bSfovYfz+vhTNz+2TlNSefTvmP1PpqSzqf9FLX\/eF4PZ+L2z85pSjqf9h2r99GUdD7tp6j9x\/N6OBO3f3ZOU9L5tO9YvY+mpPNpP0XtP57XwwpzJ3E5Wd0n6fyn+93c4eZdTlyfuZOo\/HheDyvMncTlZHWfpPOf7ndzh5t3OXF95k6i8uN5PawwdxKXk9V9ks5\/ut\/NHW7e5cT1mTuJyo\/n9bDC3ElcTlb3STr\/6X43d7h5lxPXZ+4kKj+e18MKcydJc0pUZyRRnSr56ZwSl5O07+A+StLcSVR+PK+HFeZOkuaUqM5IojpV8tM5JS4nad\/BfZSkuZOo\/HheDyvMnSTNKVGdkUR1quSnc0pcTtK+g\/soSXMnUfnxvB5WmDtJmlOiOiOJ6lTJT+eUuJykfQf3UZLmTqLy43k9rDB3EpcT1\/90TtjvSlyewn2UqM5IkuZOovLjeT2sMHcSlxPX\/3RO2O9KXJ7CfZSozkiS5k6i8uN5PawwdxKXE9f\/dE7Y70pcnsJ9lKjOSJLmTqLy43k9rDB3EpcT1\/90TtjvSlyewn2UqM5IkuZOovLjeT2c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\/yCvfqF3z9\/t1c9JtzKr92pu8x\/j8YukJ6PswavzispGcy57xau5V+cnLt9sNpvNZrPZbDabzWaz2Ww2m81M\/ve\/\/wclQxXDBQHQjQAAAABJRU5ErkJggg==","fileSize":"8484","returnCode":"0"} )
There are 3 columns:
file
fileSize
returnCode
I have tried to get data using Object, Array or json but always failed.
//$json = json_decode($data, true); //array
//$json = json_decode($data); //object
//echo $result; //JSONDataResult
Below is one of the FAILED method. The full process coding:
<?php
if (isset($_GET['submit'])) {
$project_code = $_GET['project_code'];
$url = "http://1.2.3.4/to/file/process";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, curlopt_httpheader, array ("Content-type:application/json"));
$result = curl_exec($curl);
curl_close($curl);
$data = file_get_contents($url);
$json = json_decode($data, true); //array
//$json = json_decode($data); //object
//echo $result; //JSONDataResult
//print_r($json);
foreach ($json as $key => $value) {
if (!is_array($value)) {
//always goes here
echo "not array: ".$key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo "is array: ".$key . '=>' . $val . '<br/>';
}
}
}
}
?>
Guys help me to read the content. I do not mind using which method as long as i can read each column inside the content. Many-many thank you.
[jangankecamsaya]
Assuming the data you posted in the question is the output of print_r($json);, it is clear that $json is an array that contains only one value (the big JSON) associated to the key JSONDataResult. It basically looks like this:
$json = array('JSONDataResult' => '{"file":"iVBORw0KGgoAAAANSUhEUgAAALUAAAEZCAYAAADR+mSIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABhuSURBVHhe7ZiBcuM4smz3\/3\/6PkrPjCgfppBMFWB53DgRx2whs4raMWJ7dv938H8\/KVGdjkR1qrNx+13ehftTU9w889V+vVOHqySq05GoTnU2br\/Lu3B\/aoqbZ77ar3fqcJVEdToS1anOxu13eRfuT01x88xX+\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YevDu32cjLcqIuzZ2z1TtP1Nlm8+1ivHuRRnMrdp6os80\/jrs4yUV6nFdP2OfnB3fO7s5t\/mFWXqTaeXfnu3Obf5RXl2HGRXI77u58d27zD\/K4CLRy55y5Oqu8yuu5yyv1XOWbzWaz2Wx+Feqv6vOs\/nV+evLq\/ORTmWKUbf4gry5IJe18KmPnwSjb\/FFGF+Ek7fx0dqLOTkbZ5o\/x+GUrK\/z8YNT56exEnZ2Mss0f487leNWpklH+KlO9k1F2os5ORtnmj3HncqQXiIy6NRu9d5SdqLOTUbb5Y9y5HOkFqox67j31s+s+UGcno2zzx7hzOd65QKdklD0Y5a+yes58lG02m81ms\/kI6q\/jevYq33+Nb34t6aUeZZvNr6BzqTebX8njkipP6p9P1Nlm82twl\/bVBd4Xe\/NrefdSP9gXe\/MrSS\/1KNtsfgXppX7wONsXerPZbDabTYPRv06cmcpH2QOV1RmVP1BZPWP24NX5g3ezzX+U85f56hdeqZ9H2cnj7E6v4vKT2hu9491s8we48wsddV5dkFfnilFWcTvr53ezzR\/gzi9UXYJTcp6NZpKsorJXc6PPrrv5j+N+oUn+6s+KUVfN3jlTn6snqrf5Q4x+oXd+2bws9BU1Y0\/N3TlTnZOaJXOb\/yCvfqF3z9\/t1c9JtzKr92pu8x\/j8YukJ6PswavzispGcy57xau5V+cnLt9sNpvNZrPZbDabzWaz2Ww2m81M\/ve\/\/wclQxXDBQHQjQAAAABJRU5ErkJggg==","fileSize":"8484","returnCode":"0"}');
A call to json_decode($json['JSONDataResult'], TRUE) decodes the big string into an array like this:
array(
'file' => 'iVBORw0KGgoAAAANSUhEUgAAALUAAAEZCAYAAADR+mSIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABhuSURBVHhe7ZiBcuM4smz3/3/6PkrPjCgfppBMFWB53DgRx2whs4raMWJ7dv938H8/KVGdjkR1qrNx+13ehftTU9w889V+vVOHqySq05GoTnU2br/Lu3B/aoqbZ77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zD/K4CLRy55y5Oqu8yuu5yyv1XOWbzWaz2Wx+Feqv6vOs/nV+evLq/ORTmWKUbf4gry5IJe18KmPnwSjb/FFGF+Ek7fx0dqLOTkbZ5o/x+GUrK/z8YNT56exEnZ2Mss0f487leNWpklH+KlO9k1F2os5ORtnmj3HncqQXiIy6NRu9d5SdqLOTUbb5Y9y5HOkFqox67j31s+s+UGcno2zzx7hzOd65QKdklD0Y5a+yes58lG02m81ms/kI6q/jevYq33+Nb34t6aUeZZvNr6BzqTebX8njkipP6p9P1Nlm82twl/bVBd4Xe/NrefdSP9gXe/MrSS/1KNtsfgXppX7wONsXerPZbDabTYPRv06cmcpH2QOV1RmVP1BZPWP24NX5g3ezzX+U85f56hdeqZ9H2cnj7E6v4vKT2hu9491s8we48wsddV5dkFfnilFWcTvr53ezzR/gzi9UXYJTcp6NZpKsorJXc6PPrrv5j+N+oUn+6s+KUVfN3jlTn6snqrf5Q4x+oXd+2bws9BU1Y0/N3TlTnZOaJXOb/yCvfqF3z9/t1c9JtzKr92pu8x/j8YukJ6PswavzispGcy57xau5V+cnLt9sNpvNZrPZbDabzWaz2Ww2m81M/ve//wclQxXDBQHQjQAAAABJRU5ErkJggg==',
'fileSize' => 8484,
'returnCode' => 0,
);
The value of file is encoded using base64. The complete code should look like this:
// Decode the JSON
$fileInfo = json_decode($json, TRUE);
// Decode the file content
$content = base64_decode($fileInfo['file']);
// Visually inspect its the decoded file content
print_r($content); // Congratulations, it's a PNG!
// Put the content in a file
file_put_contents('...the file path here...', $content);
// Use getimagesize() to learn about the image type
// an rename the file using the correct termination.
Btw, the value of fileSize is the length of the file field, i.e. the content encoded using base64, not the length of the actual PNG file on disk (as I would expect).
You tried to
$json = json_decode($data[0], true); //array
???
(mind the access on the first field on $data)

oAuth signature creation issue with PHP (posting photoset to Tumblr)

I've made a simple script that posts images on tumblr.
everything is fine, but I've noticed some performance issues right after I've changed the host provider (my new host is limited and cheaper).
now, after debugging the script and after contacting the tumblr api helpdesk, I'm stuck on a problem:
there are 3 functions:
function oauth_gen($method, $url, $iparams, &$headers) {
$iparams['oauth_consumer_key'] = CONSUMER_KEY;
$iparams['oauth_nonce'] = strval(time());
$iparams['oauth_signature_method'] = 'HMAC-SHA1';
$iparams['oauth_timestamp'] = strval(time());
$iparams['oauth_token'] = OAUTH_TOKEN;
$iparams['oauth_version'] = '1.0';
$iparams['oauth_signature'] = oauth_sig($method, $url, $iparams);
$oauth_header = array();
foreach($iparams as $key => $value) {
if (strpos($key, "oauth") !== false) {
$oauth_header []= $key ."=".$value;
}
}
$str = print_r($iparams, true);
file_put_contents('data1-1.txt', $str);
$oauth_header = "OAuth ". implode(",", $oauth_header);
$headers["Authorization"] = $oauth_header;
}
function oauth_sig($method, $uri, $params) {
$parts []= $method;
$parts []= rawurlencode($uri);
$iparams = array();
ksort($params);
foreach($params as $key => $data) {
if(is_array($data)) {
$count = 0;
foreach($data as $val) {
$n = $key . "[". $count . "]";
$iparams []= $n . "=" . rawurlencode($val);
//$iparams []= $n . "=" . $val;
$count++;
}
} else {
$iparams[]= rawurlencode($key) . "=" .rawurlencode($data);
}
}
//debug($iparams,"iparams");
$str = print_r($iparams, true);
file_put_contents('data-1.txt', $str);
//$size = filesize('data.txt');
$parts []= rawurlencode(implode("&", $iparams));
//debug($parts,"parts");
//die();
$sig = implode("&", $parts);
return base64_encode(hash_hmac('sha1', $sig, CONSUMER_SECRET."&". OAUTH_SECRET, true));
}
these 2 functions above comes from an online functional example, they have always worked fine.
this is the function I use to call the APIs and the oAuth:
function posta_array($files,$queue,$tags,$caption,$link,$blog){
$datArr = array();
$photoset_layout = "";
foreach ($files as $sing_file){
$dataArr [] = file_get_contents($sing_file);
$photoset_layout .= "1";
}
$headers = array("Host" => "http://api.tumblr.com/", "Content-type" => "application/x-www-form-urlencoded", "Expect" => "");
$params = array(
"data" => $dataArr,
"type" => "photo",
"state" => $queue,
"tags"=>$tags,
"caption"=>$caption,
"photoset_layout" => $photoset_layout,
"link"=>str_replace("_","",$link)
);
debug($headers,"head");
oauth_gen("POST", "http://api.tumblr.com/v2/blog/$blog/post", $params, $headers);
debug($headers,"head 2");
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Tumblr v1.0");
curl_setopt($ch, CURLOPT_URL, "http://api.tumblr.com/v2/blog/$blog/post");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: " . $headers['Authorization'],
"Content-type: " . $headers["Content-type"],
"Expect: ")
);
$params = http_build_query($params);
$str = print_r($params, true);
file_put_contents('data_curl1.txt', $str);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
debug($response,"response");
return $response;
}
this is the function with some problems, I try to explain:
I called the oauth_gen passing the parameters array to it, the oauth_gen creates the oauth header that I later used here: "Authorization: " . $headers['Authorization'],.
As I stated, everything is working smoothly, until I have tried to post a gif photoset of 6 files for a total of 6Mb (tumblr permit 2Mb each file and 10Mb total).
PHP runs out of memory and return an error, here it starts my debugging, after a while I contacted the tumblr api helpdesk, and they answer in this way:
You shouldn't need to include the files in the parameters used for
generating the oauth signature. For an example of how this is done,
checkout one of our official API clients.
This changes everything. Untill now, I passed the entire parameters array to the oauth_gen, which, calling the oauth_sig, will rawencode everything into the array (binary strings of gif files inlcuded), with a result of a binary file of about 1Mb becomes at least 3Mb of rawurlencoded string.
and that's why I had memory issues. Nice, so, as the helpdesk say, I've changed the call to the oauth_gen in this way:
$new_array = array();
oauth_gen("POST", "http://api.tumblr.com/v2/blog/$blog/post", $new_array, $headers);
seams legit to me, I passed a new array to the function, the function then generate the oAuth, the headers are passed back and I can use them into the posting call, the result was:
{"meta":{"status":401,"msg":"Unauthorized"},"response":[]}
asking more to tumblr api helpdesk leads only to more links to their documentation and their "tumblr php client" which I can't use, so it isn't a option.
Does anyone has experience with oAuth and can explain me what I'm doing wrong? as far as I understand, the trick is into the encrypted data the oauth_sig create, but I can't figure out how to proceed.
I really want to understand the oauth, but more I read about it and more the tumblr helpdsek seams right to me, but... the solution doesn't work, and works only if I let the oauth function to encrypt the entire data array (with the images and everything) but I can understand that this is wrong... help me.
UPDATE 1
I've tried a new thing today, first I created the empty array, then passed by reference to the oauth_genand only after generating the signature, I've added to the same array all the other fields about the post itself, but the result is the same.
UPDATE 2
reading here: http://oauth.net/core/1.0a/#signing_process
seems that the parameters of the request must all be used for the signature, but this is not totally clear (if someone could explain it better, I really appreciate).
this is weird, because if it's true, it go against the words of the Tumblr help desk, while if it's not true, there is a little confusion in the whole process.
by the way, at this time, I'm stile struck in the same point.
After digging couple of hours into the issue, debugging, reviewing tumblr api and api client, registering a test account and trying to post some images. The good news is finally I come up with a solution. It is not using a native CURL only, you need guzzle and an OAuth library to sign the requests.
Tumblr guys are correct about signing the request. You don't need to pass image data to sign the request. If you check their official library you can see; https://github.com/tumblr/tumblr.php/blob/master/lib/Tumblr/API/RequestHandler.php#L85
I tried to fix the issue with native CURL library but unfortunately I was not successful, either I was signing the request in a wrong way or missing something in the request header, data etc. I don't know actually, Tumblr api is really bad at informing you what you are doing wrong.
So I cheated a little bit and start to read Tumblr api client code, and I come up with a solution.
Here we go, first you need two packages.
$ composer require "eher/oauth:1.0.*"
$ composer require "guzzle/guzzle:>=3.1.0,<4"
And then the PHP code, just define your keys, tokens, secrets etc. Then it should be good to go.
Since the signing request does not include picture data, it is not exceeding memory limit. After signing the request actually we are not getting the contents of the files into our post data array. We are using addPostFiles method of guzzle, which takes care of file addition to POST request, does the dirty work for you. And here is the result for me;
string(70) "{"meta":{"status":201,"msg":"Created"},"response":{"id":143679527674}}"
And here is the url;
http://blog-transparentcoffeebouquet.tumblr.com/
<?php
ini_set('memory_limit', '64M');
define("CONSUMER_KEY", "");
define("CONSUMER_SECRET", "");
define("OAUTH_TOKEN", "");
define("OAUTH_SECRET", "");
function request($options,$blog) {
// Take off the data param, we'll add it back after signing
$files = isset($options['data']) ? $options['data'] : false;
unset($options['data']);
$url = "https://api.tumblr.com/v2/blog/$blog/post";
$client = new \Guzzle\Http\Client(null, array(
'redirect.disable' => true
));
$consumer = new \Eher\OAuth\Consumer(CONSUMER_KEY, CONSUMER_SECRET);
$token = new \Eher\OAuth\Token(OAUTH_TOKEN, OAUTH_SECRET);
$oauth = \Eher\OAuth\Request::from_consumer_and_token(
$consumer,
$token,
"POST",
$url,
$options
);
$oauth->sign_request(new \Eher\OAuth\HmacSha1(), $consumer, $token);
$authHeader = $oauth->to_header();
$pieces = explode(' ', $authHeader, 2);
$authString = $pieces[1];
// POST requests get the params in the body, with the files added
// and as multipart if appropriate
/** #var \Guzzle\Http\Message\RequestInterface $request */
$request = $client->post($url, null, $options);
$request->addHeader('Authorization', $authString);
if ($files) {
if (is_array($files)) {
$collection = array();
foreach ($files as $idx => $f) {
$collection["data[$idx]"] = $f;
}
$request->addPostFiles($collection);
} else {
$request->addPostFiles(array('data' => $files));
}
}
$request->setHeader('User-Agent', 'tumblr.php/0.1.2');
// Guzzle throws errors, but we collapse them and just grab the
// response, since we deal with this at the \Tumblr\Client level
try {
$response = $request->send();
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
$response = $request->getResponse();
}
// Construct the object that the Client expects to see, and return it
$obj = new \stdClass;
$obj->status = $response->getStatusCode();
$obj->body = $response->getBody();
$obj->headers = $response->getHeaders()->toArray();
return $obj;
}
$files = [
"/photo/1.jpg",
"/photo/2.jpg",
"/photo/3.png",
"/photo/4.jpg",
"/photo/1.jpg",
"/photo/2.jpg",
"/photo/3.png",
"/photo/4.jpg",
"/photo/1.jpg",
"/photo/2.jpg",
];
$params = array(
"type" => "photo",
"state" => "published",
"tags"=> [],
"caption"=>"caption",
"link"=>str_replace("_","","http://stackoverflow.com/questions/36747697/oauth-signature-creation-issue-with-php-posting-photoset-to-tumblr"),
"data" => $files,
);
$response = request($params, "blog-transparentcoffeebouquet.tumblr.com");
var_dump($response->body->__toString());

converting twitter short url to original and getting numbers of tweets containing that url

Here I am getting url from tweets, converting that url to long url.
And then getting count value for numbers of tweets containing that url.
$reg_exUrl = "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.]|[~])*)/";
// The Text you want to filter for urls
$text = "Make this Xmas super powerful with #Krrish3 on http://t.co/PHOdAqnzkT !\ ";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
preg_match_all($reg_exUrl, $text, $urls);
foreach ($urls[0] as $url) {
echo "{$url}<br>";
$full = MyURLDecode($url);
echo "full is: $full<br>";
$feedUrl = "http://urls.api.twitter.com/1/urls/count.json?url=$full";
$json = file_get_contents($feedUrl);
$code = json_decode($json,true);
var_dump($code);
echo "1";
echo "Numbers of tweets containing this link : ", $code['count'];
echo "2";
}
} else {
echo $text;
}
Problem
Decoding some twitter tiny urls again give biturl(i.e. again tiny url)
Getting number of tweets(count value) containig that url. Above code give it, but for most of url it show 0 though they have count value
Any suggestion for improvement?
If you wish to fetch last url from short url, you can use curl:
function get_follow_url($url) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_NOBODY => true,
CURLOPT_FOLLOWLOCATION => true,
));
curl_exec($ch);
$follow_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $follow_url;
}
To fetch the number of tweets, you can use 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;
}
So here is use example of this functions:
$short_url = 'http://t.co/5rgJb3mbQ6';
echo "Short url: $short_url\n";
$follow_url = get_follow_url($short_url);
echo "Follow url: $follow_url\n";
$url_count = get_twitter_url_count($follow_url);
echo "Url count: $url_count\n";
Output would be something like:
Short url: http://t.co/5rgJb3mbQ6
Follow url: http://global.yamaha-motor.com/race/wgp-50th/race_archive/riders/hideo_kanaya/
Url count: 6

Categories