Twitter API -> updating profile bg image with php - 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.

Related

Slack Incoming Webhook with PHP form

I'm trying to create a PHP script that automatically pushes text from <textarea> in my webform to Slack channel.
HTML:
<form action="http://main.xfiddle.com/<?php echo pf_file('g7f-ds0'); ?>" method="post" id="myform" name="myform">
<textarea name="text" id="" rows="3" cols="30">
</textarea> <br /><br />
<button id="mysubmit" type="submit" name="submit">Submit</button><br /><br /></form>
I managed to write a PHP script that posts hard coded message to Slack like this:
<?php
//API Url
$url = 'https://hooks.slack.com/services/T02NZ01FU/B08TTAPGE/000000000000000000';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$payload = array(
’text' => 'Testing text with PHP'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($payload);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
But for some reason when I try to get text from <textarea name="text" rows="3" cols="30"></textarea> and save it into a variable then it doesn't work. I add this to the beginning of PHP to set the text variable:
if(isset($_POST['submit']))
$textdata = $_POST['text'];
and then change the $payload to
'text' => $textdata
A simple example of how to use slack incoming webhook with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here
There are two likely issues here.
The PHP formatting in your post is incorrect.
Replace ’text' => 'Testing text with PHP' with
'text' => 'Testing text with PHP'
Your curl is not set up correctly. Please see the following posts to debug curl and to fix what is likely wrong - no trusted SSL certificates

PHP string from HTTP post to another server

I will be using PHP further on this site, otherwise interested in learning more python to achieve these results.
I start with a search form that allows the user to enter in the 'findme' value which needs to be translated to a url. (for example purposes I will use findme = 12345678)
<form name="search" method="post" action="search.php" target="_blank" novalidate>
<input type="text" name="findme" />
<input type="submit" name="submit" value="submit" />
</form>
And then, I would like to retrieve a string within a HTTP post response page from a second server and store a url as a PHP string.
First I need to submit the form to another server, here is my attempt at search.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://another.server.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'surname' => 'surname',
'name' => 'name',
'findme' => 'findme'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
The other server responds by serving a new page (ie. https://another.server.com/response.html), I want to then find the line containing the findme string, below is the format which the findme value of 12345678 would appear in a line of the response page. I want to save ABCDE as a string.
<tr class="special"><td>12345678......
Hopefully I can acheive with
<?php
file_put_contents("response.html", file_get_contents("https://another.server.com/response.html"));
$content = file_get_contents('response.html');
preg_match('~^(.*'.$findme.'.'</a>'.*)$~',$content,$line);
echo $line[1];
$findme_url = substr("abcdef", -37, 5);
echo $findme_url
?>
Updated with cURL and preg_match possible solutions, however the file put contents needs to be reading the response page from cURL
Yes, this is a perfect time to use curl.
$request = curl_init( 'https://another.server.com' );
curl_setopt( $request, CURLOPT_POST, true ); // use POST
$response = curl_exec( $request );
// catch errors
if( $response === false ) {
throw new Exception( curl_error($response) );
}
curl_close( $request );
// parse response...

Sending File with cURL

I've sent some post data with cURL and am now trying to send a file, getting lost along the way. I'm using a form with a file input. Then would like cURL to send it off to my server. Here is my upload page.
<form action="curl_page.php" method="post" enctype="multipart/form-data">
Filename: <input type="file" name="file" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
Here is my curl page with some issues.
<?php
$tmpfile = $_FILES['file']['tmp_name'];
$filename = basename($_FILES['file']['name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://my_server/file_catch.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
?>
The file_catch.php on my server looks like this.
<?php
$folder = "audio/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Thanks for any help!
You are not sending the file that you got through the post request. Use the below code for posting the file through CURL request.
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
For more reference check the below link
Send file via cURL from form POST in PHP

PHP cURL setup to send to remote host

I have a few elementary questions about cURL that I can't find answered in the cURL docs (probably because they are obvious to everyone else...). I have a file type input in a form that needs to send that file to a remote server. Does the cURL code go on the page with the form, or is the cURL on the page that the form sends you to, then it gets sent to the remote server?
Here is the form html:
<form action="send.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
The cURL php I have so far which I don't even know if it's correct for what I'm trying to do, or if this goes on the same page or the send.php file the form goes to:
$ch = curl_init("http://remoteServer/upload_file.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CUROPT_POSTFIELDS, array('fileupload' => '#'.$_FILES['theFile'] ['tmp_name']));
echo curl_exec($ch);`
And on the remote server I have this file to receive it:
$folder = "files/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
Is this even remotely close?
you don't need curl to upload a file from a browser, you can submit the form directly to the remote server to upload - just make sure the form submits to whatever file has that third block of code
Try this
$curlPost = array('fileupload' => '#'.$_FILES['theFile'] ['tmp_name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://remoteServer/upload_file.php');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec();
curl_close($ch);
Another Example
How to upload image file to remote server with PHP cURL
http://www.maheshchari.com/upload-image-file-to-remote-server-with-php-curl/

New Bing API PHP example doesnt work

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

Categories