New Bing API PHP example doesnt work - php

Microsoft's own PHP example for new Bing API doesn't work. I tried in many ways, it just shows:
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page
using the credentials that you supplied.
Example Coding given in the official documentation is below, it breaks up at
'proxy' => 'tcp://127.0.0.1:8888',
I am 100% sure my key is correct, and when I just enter it in the browser url it works fine, i.e
https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27love+message%27
(you need to put the API key as your password and username can be anything)
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>PHP Bing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Type in a search:
<input type="text" id="searchText" name="searchText"
value="<?php
if (isset($_POST['searchText']))
{
echo($_POST['searchText']);
}
else
{
echo('sushi');
}
?>"
/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
// Replace this value with your account key
$accountKey = 'BKqC2hIKr8foem2E1qiRvB5ttBQJK8objH8kZE/WJVs=';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';
$context = stream_context_create(array(
'http' => array(
//'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');
echo($request);
$response = file_get_contents($request, 0, $context);
print_r($response);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">');
echo('<img src="' . $value->Thumbnail->MediaUrl. '"></li>');
}
echo("</ul>");
}
?>
</form>
</body>
</html>
I have tried both google API and Yahoo API both, none of those were as difficult as this.

after days of argument with microsoft techinchal support they accpeted that it didnt work
here is the proper coding which uses CURL do this in the BING API, apply CURL method instead of the file_get_contents which can’t pass the correct authentication information from Linux client to BING service.
<html>
<head>
<title>PHP Bing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Type in a search:
<input type="text" id="searchText" name="searchText"
value="<?php
if (isset($_POST['searchText']))
{
echo($_POST['searchText']);
}
else
{
echo('sushi');
}
?>"
/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
$credentials = "username:xxx";
$url= "https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27{keyword}%27";
$url=str_replace('{keyword}', urlencode($_POST["searchText"]), $url);
$ch = curl_init();
$headers = array(
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rs = curl_exec($ch);
echo($rs);
curl_close($ch);
return $rs;
}
?>
</form>
</body>
</html>

I had to add
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
in order to make it work, at least in my local copy (WAMP).
Hope it helps, I have been messing with this all the day.

$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';
This is part of the prob
This wont give the url bing is looking for
e.g. https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27love+message%27
it would be
https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query=%27love+message%27
whereas you want a web not an image search and also format and other parameters shld be after the query
"image" should be "web"
I just spent 3 days trying to get this to work.

I've just posted an example of how to connect to Bing/Azure API using Unirest Library here: https://stackoverflow.com/a/20096151/257815

Related

Downloads file instead of executing

Running on OSX, on PHP 5.6.30. I am trying to execute a script from a html file, and it downloads the file instead. NOTE: this doesn't work right as the html file should be .php, but that is also downloading instead of opening it.
I have tried:
uncommenting LoadModule php5_module libexec/apache2/libphp5.so
adding AddHandler application/x-httpd-php5 .php to /etc/apache2/httpd.conf
restarting apache (sudo /usr/sbin/apachectl restart)
moving my file to www/script.php
checking that script.php is executable
You can see it at https://reteps.github.io/website.html, and I have only tested on google chrome.
HTML (should be .php)
<!doctype html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="navbar.css">
</head>
<body>
<div id="menu">
Home
Github
School Projects
<a href="side.html" >Side Projects</a>
Blog
</div>
<form action="www/script.php" method="get">
<input type="text" name="quizid" placeholder="kahoot id">
<input type="submit" value="Go">
</form>
<p id="output">Nothing yet...</p>
</body>
</html>
PHP
#!/usr/bin/php
<?php
$username = 'USERNAME#gmail.com';
$password = 'PASSWORD';
$loginUrl = 'https://create.kahoot.it/rest/authenticate';
$kahootId = htmlentities($_GET['quizid']);
$pageUrl = 'https://create.kahoot.it/rest/kahoots/' . $kahootId;
$loginheader = array();
$loginheader[] = 'content-type: application/json';
$loginpost = new stdClass();
$loginpost->username = $username;
$loginpost->password = $password;
$loginpost->grant_type = "password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($loginpost));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$loginheader);
$store = curl_exec($ch);
curl_close($ch);
$token = json_decode($store,true)["access_token"];
//get questions
$quizheader = array();
$quizheader[] = 'authorization: ' . $token;
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: ".$token."\r\n"
)
);
$context = stream_context_create($options);
$raw_result = file_get_contents($pageUrl, false, $context);
$result = json_decode($raw_result,true)["questions"];
$myoutput = $_POST['output'];
header( "Location: website.html?output=$myoutput" );
print_r($result)
?>
From the GitHub Pages documentation: https://help.github.com/articles/what-is-github-pages/:
GitHub Pages is a static site hosting service and doesn't support server-side code such as, PHP, Ruby, or Python.

JSON_DECODE returning NULL from cURL response even though encode format seems correct?

EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
I'm trying to take a login from my test.php file and cURL it to a site which uses the data to simulate a login on another page (I know this is tedious, but this isn't the full extent of what I'm doing as a whole, just where I have the problem). So I post an encoded json to the index.php url which has no problem decoding it. The information passed is then used and the decoded json is edited to show successful or unsuccessful login. The json is then encoded once again and echoed onto the page and held in $contents on test.php. When I try to decode it on this file I get NULL everytime. I've tried a ton of things and am just starting to think I made a stupid mistake somewhere so I'm desperately looking for any help here.
-If I echo $contents it shows:
{"user":"user","pass":"password","success":true}
-If I var_dump(trim($contents)) it shows (formatted exactly as shown):
string(364) "
{"user":"user","pass":"password","success":true} "
-last_json_error_msg shows:
SYNTAX ERROR
-I've tried trimming, utfencoding, iconv, setting curl headers and literally everything I've seen recommended on other posts here.
Any help at all would be greatly appreciated. Thanks in advance guys.
test.php:
<html>
<head>
<meta charset="UTF-8">
<title>TITLE</title>
</head>
<body>
<form action="test.php" method=POST>
<input type="text" name="user">
<input type="password" name="pass">
<input type="submit" value="Submit">
</form>
<?php
function logInfo(){
class data{
public $user = "";
public $pass = "";
public $success = false;
}
$data = new data();
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch, CURLOPT_URL, [URL TO INDEX.PHP]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("data"=>$json));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$contents = curl_exec($ch);
curl_close($ch);
$array = json_decode($contents, true);
var_dump($array);
//VAR_DUMP SHOWS NULL
}
if(isset($_POST['user']) && isset($_POST['pass'])){
logInfo();
}
?>
</body>
</html>
index.php:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
header('Context-type: application/json');
function logInfo(){
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
if(isset($_POST['data'])){
logInfo();
}
?>
</body>
</html>
EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
index.php is printing HTML before the JSON (weren't you suspicious when var_dump() said that the string is 365 characters long, but you can only see about 50?). When the script is being used to return JSON, it can't produce any other output.
So check for the data parameter before printing any output. And if it's found, exit the script after sending the JSON, so you don't print the HTML.
<?php
if(isset($_POST['data'])){
logInfo();
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
</body>
</html>
<?php
function logInfo(){
header('Context-type: application/json');
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
A simpler solution would probably be to put the code that returns logInfo() into a different script.
You should do
json_encode(get_object_vars($data));
in logInfo function
A couple of things I would recommend. It's not a good practice to define a class inside a function. You should have your class in a separate file. It helps keep your code organised.
Secondly, its good to follow either snake case or camel case for defining classes / methods / functions etc.
Snake case eg: my_function_name_to_execute
Camel case eg: MyFunctionNameToExecute
Try to check resulting JSON syntax using this library https://github.com/Seldaek/jsonlint
UPDATE
It correctly detects extra HTML from index.php and other possible problems.
Following example
use Seld\JsonLint\JsonParser;
$parser = new JsonParser();
$exception = $parser->lint('<html>{"user":"user","pass":"password","success":true}');
echo $exception->getMessage();
will output:
Parse error on line 1:
<html>{"user":"user"
^
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Getting InvalidRegistration in implementing GCM PHP script

I'm implementing push notification in android. I have implemented client side coding in android properly. Its working fine and already created Google API key.
Problem: But when I am sending the push notification from the server(this script is written in php) then I am getting error. The error is like this-
{"multicast_id":8690314483687932029,"success":0,"failure":1,"canonical_ids":0,"results": [{"error":"InvalidRegistration"}]}
And my server side script is like this.
<?php
//Generic php function to send GCM push notification
function sendMessageThroughGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Update your Google Cloud Messaging API Key
define("GOOGLE_API_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$headers = array(
`` 'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
<?php
//Post message to GCM when submitted
$pushStatus = "GCM Status Message will appear here";
if(!empty($_GET["push"])) {
$gcmRegID = file_get_contents("GCMRegId.txt");
$pushMessage = $_POST["message"];
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("m" => $pushMessage);
$pushStatus = sendMessageThroughGCM($gcmRegIds, $message);
}
}
//Get Reg ID sent from Android App and store it in text file
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regId"];
file_put_contents("GCMRegId.txt",$gcmRegID);
echo "Done!";
exit;
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) in PHP</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("textarea").val("");
});
function checkTextAreaLen(){
var msgLength = $.trim($("textarea").val()).length;
if(msgLength == 0){
alert("Please enter message before hitting submit button");
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<div id="formdiv">
<h1>Google Cloud Messaging (GCM) in PHP</h1>
<form method="post" action="/gcm/gcm.php/?push=true" onsubmit="return checkTextAreaLen()">
<textarea rows="5" name="message" cols="45" placeholder="Message to send via GCM"> </textarea> <br/>
<input type="submit" value="Send Push Notification through GCM" />
</form>
</div>
<p id="status">
<?php echo $pushStatus; ?>
</p>
</body>
</html>
I am new in android. I'm not able to do find what is the exact problem. Please help me, thanks in advance.
change this in your path
action="/gcm/gcm.php/?push=true"
to
action="test/gcm/gcm.php/?push=true"
here test is the folder on the server and gcm is a sub folder. gcm.php should be put in the subfolder.

Azure won't cURL a google site search xml

I'm running the XML to PHP install of paid Google site search.
https://code.google.com/p/google-csbe-example/downloads/detail?name=gss.php&can=2&q=
My initial implementation runs perfectly on a LAMP server, however I now have to run a PHP environment on the Windows Azure Platform.
It appears as though the $url variable is not being passed through cURL, as the $result varaible returns as NULL.
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
If i modify the value of $url to a different remote xml file, with a little adjustment to the output structure, I get the expected results.
I have tried several different troubleshooting steps including:
cURL: alternate xml feed renders
simplexml: alternate rss feed renders
permissions: site permissions aren't required google cse dashboard
alternate azure site: tested and failed
alternate LAMP hosted site: tested and success
alternate search setup: this had no effect
is the domain blocked to google: don't think so
url queries blocked: not sure if this is causing any issues
I'm stumped.
Any help would be greatly appreciated.
Thanks!
Here's the full code (minus the cx number):
<?php
//ini_set('display_startup_errors',1);
//ini_set('display_errors',1);
//error_reporting(-1);
$q = $_GET['q'];
$q = urlencode($q);
//WRAPPED IN A IF STATEMENT SO PROMOTED RESULTS SHOW UP ON THE FIRST PAGE
if(isset($_GET['start'])){
$start = $_GET['start'];
}
$your_cx_number = 'enter_your_paid_google_site_search_cx_number';
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
//curl_setopt($ch, CURLOPT_POSTFIELDS, "postparam1=postvalue"); // add POST fields
//submit the xml request and get the response
$result = curl_exec($ch);
curl_close($ch);
//now parse the xml with
$xml = simplexml_load_string($result);
$START = $xml->RES['SN'];
$END = $xml->RES['EN'];
$RESULTS = $xml->RES->M;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search results</title>
</head>
<body>
<form action="search-test.php" id="searchform" >
<input type="text" name="q" placeholder="Search..." <?php if(isset($_GET['q'])) { echo 'value="' . $_GET['q'] . '"' ; }?> id="search-text" size="25" autocomplete="off" />
<input type="submit" id="search-button" title="Search" value="" />
</form>
<p>The url of the XML output</p>
<?php
//extract the title, link and snippet for each result
if ($xml->RES->R) {
foreach ($xml->RES->R as $item) {
$title = $item->T;
$link = $item->U;
$snippet = $item->S;
echo '<h3>' . $title . '</h3>
<p>' . $title . '</p>
<p>' . $snippet . '</p>
<hr />';
}
}
?>
</body>
</html>
cURL error reporting returned an error code : 60
Curl error: 60 - SSL certificate problem: unable to get local issuer certificate
A search for a similar error provided the solution
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Add in the line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
The full cURL function is now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_errno($ch) . ' - ' .curl_error($ch);
$info = curl_getinfo($ch);
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
echo $info['http_code'];
}
}
curl_close($ch);

Twitter API -> updating profile bg image with php

So far I have been trying to update the twitter profile bg image thr the twitter api with php... and without success
Many examples on the web, including this one:
Updating Twitter background via API
and this one
Twitter background upload with API and multi form data
do not work at all, most ppl throw out answers without actually testing the code.
I found that directly submit the image to the twitter.com thr html form, it will work:
<form action="http://twitter.com/account/update_profile_background_image.xml" enctype="multipart/form-data" method="post">
File: <input type="file" name="image" /><br/>
<input type="submit" value="upload bg">
</form>
(although the browser will prompt you for the twitter account username and password)
However, if I want to go thr the same process with php, it fails
<?php
if( isset($_POST["submit"]) ) {
$target_path = "";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
// "The file ". basename( $_FILES['myfile']['name']). " has been uploaded<br/>";
} else{
// "There was an error uploading the file, please try again!<br/>";
}
$ch = curl_init('http://twitter.com/account/update_profile_background_image.xml');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $_POST['name'] . ':' . $_POST['pass']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode(file_get_contents($target_path))));
$rsp = curl_exec($ch);
echo "<pre>" . str_replace("<", "<", $rsp) . "</pre>";
}
?>
<form enctype="multipart/form-data" method="post">
<input type="hidden" name="submit" value="1"/>
name:<input type="text" name="name" value=""/><br/>
pass:<input type="password" name="pass" value=""/><br/>
File: <input type="file" name="myfile" /><br/>
<input type="submit" value="upload bg">
</form>
The strange thing of this code is that.. it successfully returns the twitter XML, WITHOUT having the profile background image updated. So at the end it still fails.
Many thanks for reading this. It will be great if you can help. Please kindly test your code first before throwing out answers, many many thanks.
This is what works for me (debug stuff left in):
$url = 'http://twitter.com/account/update_profile_background_image.xml';
$uname = 'myuname';
$pword = 'mypword';
$img_path = '/path/to/myimage.jpg';
$userpwd = $uname . ':' . $pword;
$img_post = array('image' => '#' . $img_path . ';type=image/jpeg',
'tile' => 'true');
$opts = array(CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $img_post,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => $userpwd,
CURLOPT_HTTPHEADER => array('Expect:'),
CURLINFO_HEADER_OUT => true);
$ch = curl_init();
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
echo $err . '<br />';
echo '----------------' . '<br />';
print_r($info);
echo '----------------' . '<br />';
echo htmlspecialchars($response) . '<br />';
echo '</pre>';
Have you confirmed that the image you expect is present and being sent (i.e. echo out the base64 encoded data for verification)? Is it GIF/PNG/JPG and under the 800 kilobyte limit set by the API?
I think you're using the CURLOPT_POSTFIELDS method wrong. You need to put and # sign in front of the full path to the file according to the documentation for curl PHP. You are not supposed to output the whole file contents.
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
This is an example from the documentation.
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
I hope this helps.
Right now no one can actualy update the profile background image nor the profile image.
Twitter is working to fix that issue till then there is no fix.

Categories