Im trying to upload an image to Smugmug using the Upload API v2.
I've been trying for quite a time but it wont work.
This is what i've came up with so far.
When i run the script the response is as follows:
HTTP/1.1 100 Continue HTTP/1.1 200 OK Cache-Control: private, no-store, no-cache, max-age=1, must-revalidate Content-Type: text/xml; charset=utf-8 Date: Tue, 07 Jul 2015 14:18:50 GMT Edge-Control: no-store Expires: Tue, 07 Jul 2015 14:18:50 GMT Server: nginx X-Powered-By: SmugMug/1.0 X-SmugMug-Hiring: How to love what you do: http://www.smugmug.com/jobs/ X-SmugMug-Values: 1/4 - Thrill your customers Content-Length: 38 Connection: keep-alive
But the file isn't uploaded..
Do you see anything wrong with the code?
include_once("oauth/OAuth.php");
include_once("constants.php");
$access_token = '***';
$access_token_secret = '***';
$consumer = new OAuthConsumer(API_KEY, API_KEY_SECRET);
$signature_method = new OAuthSignatureMethod_PLAINTEXT;
$token = new OAuthToken($access_token, $access_token_secret);
$req_token = OAuthRequest::from_consumer_and_token($consumer, $token, "POST", 'http://upload.smugmug.com');
$req_token->sign_request($signature_method, $consumer, $token);
$parameters = $req_token->get_parameters();
$path = 'image.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
finfo_close($finfo);
$header[] = 'Authorization: OAuth realm="http://upload.smugmug.com/",
oauth_consumer_key='.$parameters['oauth_consumer_key'].',
oauth_token='.$parameters['oauth_token'].',
oauth_signature_method='.$parameters['oauth_signature_method'].',
oauth_signature='.$parameters['oauth_signature'].',
oauth_timestamp='.time().',
oauth_nonce='.md5(time() . mt_rand()).',
oauth_version=1.0';
$body[] = 'Accept: application/json';
$body[] = 'X-Smug-Version: v2';
$body[] = 'X-Smug-ResponseType: JSON';
$body[] = 'X-Smug-AlbumUri: /api/v2/album/******';
$body[] = 'X-Smug-Filename: image.png';
$body[] = 'Content-MD5: '.$base64.'';
$body[] = 'Content-Length: '.filesize($path).'';
$body[] = 'Content-Type: '.$mime.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://upload.smugmug.com/');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_error ($ch);
$result = curl_exec($ch);
print_r($result);
Using OAuth can be tricky, and the upload API for SmugMug is a little unique. It might be helpful to use one of the PHP wrappers out there rather than write your own code. Here are two, both of which have examples of how to upload images:
1.) phpSmug
2.) DFM Smug Wrapper
For example with the DFM Smug Wrapper, you can do the following (copied from the README file included with the wrapper):
<?php
require_once("dfm-smug-wrapper/dfm-smug-wrapper.php");
$f = new DFM_Smug(
"oauth_consumer_key=12345678",
"oauth_secret=some_secret",
"token_id=12345",
"token_secret=some_other_secret",
"app_name=My Cool App/1.0 (http://app.com)",
"api_ver=2.0"
);
$f->images_upload("AlbumID=123456", "File=/path/to/image.jpg");
?>
Related
I've tried to send a CSV File to eBay FileExchange Service.
I'm writing an application to update a lot of products on eBay at the same time.
When I upload the test.csv by using the eBay CSV-Manager the update will be success, but with the script nothing will happens after post the data.
I've treid the following steps:
Create a separate token for FileExchange.
https://signin.ebay.de/ws/eBayISAPI.dll?SignIn&runame=F-FILEEXL51P1EHH6L899Q9B969GE134DK-FileUpload
Then I use the following script:
$token = 'AgAAAA**AQAAAA**aAAAAA************';
$ebay_url = 'https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeUpload';
$sendheaders = array(
'User-Agent: My Client App v1.0'
);
$fields = array(
'token' => $token,
'file' => '#test.csv'
);
$ch = curl_init($ebay_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_NOBODY, 0); // set to 1 to eliminate body info from response
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
curl_setopt($ch, CURLOPT_HTTPHEADER, $sendheaders);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // use HTTP POST to send form data
$resp = curl_exec($ch); //execute post and get results
if(!curl_exec($ch)) {
die('Error: ' . curl_error($ch) . ' - Code: ' . curl_errno($ch));
}
curl_close ($ch);
I've used this csv File-format (test.csv)
Action;ItemID;DispatchTimeMax
Revise;28*********916;30
The results after post:
print_r($resp);
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: dp1=bu1p/QEBfX0BAX19AQA**617d3da3^bl/DE617d3da3^; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Set-Cookie: s=CgAD4ACBdvCgjMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWFY39RE; Domain=.ebay.com; Path=/
Set-Cookie: nonsession=CgADKACBhfT2jMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWIAywABXbrdqzHTwXKU; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Cache-Control: private
Pragma: no-cache
Content-Type: text/html;charset=UTF-8
Content-Length: 731
Date: Thu, 31 Oct 2019 12:42:11 GMT
Connection: keep-alive
File upload successful. Your ref # is .
Close
Thanks for helping me.
I have found a solution:
Obviously at php 7.1 the # has no effect, and the file post ist empty to ebay.
I use the curl_file_create function and it's work.
if (!function_exists('curl_file_create'))
{
function curl_file_create($filename, $mimetype = '')
{
return "#$filename;filename="
. ($mimetype ? ";type=$mimetype" : '');
}
}
$fields = array(
"token" => $token,
"file" => curl_file_create ($_GET['filename'], 'text/csv')
);
Hope that help's anybody.
I want to integrate Superfeedr API using PubSubHubbub in PHP. I am following this and my code is:
<?php
require_once('Superfeedr.class.php')
$superfeedr = new Superfeedr('http://push-pub.appspot.com/feed',
'http://mycallback.tld/push?feed=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed',
'http://wallabee.superfeedr.com');
$superfeedr->verbose = true;
$superfeedr->subscribe();
?>
And my subscribe() function is
public function subscribe()
{
$this->request('subscribe');
}
private function request($mode)
{
$data = array();
$data['topic'] = $this->topic;
$data['callback'] = $this->callback;
$post_data = array (
"hub.mode" => 'subscribe',
"hub.verify" => "sync",
"hub.callback" => urlencode($this->callback),
"hub.topic" => urlencode($this->topic),
"hub.verify_token" => "26550615cbbed86df28847cec06d3769",
);
//echo "<pre>"; print_r($post_data); exit;
// url-ify the data for the POST
foreach ($post_data as $key=>$value) {
$post_data_string .= $key.'='. $value.'&';
}
rtrim($fields_string,'&');
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->hub);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
$output = curl_exec($ch);
if ($this->verbose) {
print('<pre>');
print_r($output);
print('</pre>');
}
}
But after execution I am getting this error
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: The force, Luke
Vary: X-HTTP-Method-Override, Accept-Encoding
Content-Type: text/plain; charset=utf-8
X-Superfeedr-Host: supernoder16.superfeedr.com
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Content-Length: 97
ETag: W/"61-db6269b5"
Date: Wed, 24 Aug 2016 14:01:47 GMT
Connection: close
Please provide a valid hub.topic (feed) URL that is accepted on this hub. The hub does not match.
Same data (topic and callback etc..) requesting from https://superfeedr.com/users/testdata/push_console
is working fine. But I don't know why I am getting this error on my local. If anyone has any experienced with same problom then please help me. Thanks.
You are using a strange hub URL. You should use HTTPS://push.superfeedr.com in the last param of your class constructor.
I have a piece of code that trying to call Cloudstack REST API :
function file_get_header($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
$datas = curl_exec($ch);
curl_close($ch);
return $datas;
}
$url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;
echo $test = file_get_header($url);
And the output is like this :
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT
What I am trying to do is how to print JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 only and assign it into variable? Thankss,
Here's a method that will parse all your headers into a nice associative array, so you can get any header value by requesting $dictionary['header-name']
$url = 'http://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$datas = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($datas, 0, $header_size);
curl_close($ch);
echo ($header);
$arr = explode("\r\n", $header);
$dictionary = array();
foreach ($arr as $a) {
echo "$a\n\n";
$key_value = explode(":", $a, 2);
if (count($key_value) == 2) {
list($key, $value) = $key_value;
$dictionary[$key] = $value;
}
}
//uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
//var_dump($dictionary);
Simple, just match the part of the string you want with preg_match:
<?php
$text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";
preg_match("/JSESSIONID=\\w{32}/u", $text, $match);
echo $result = implode($match);
?>
So i managed to built oauth 2.0 youtube video upload, but everytime i upload a video i get an HTTP 400 ERROR with a invalid request.
But the weirdest thing is that the video is uploading to youtube while having : Failed (upload aborted).
im not using any framework, cause google doesnt have yet any to oauth 2.0, so i built all of my code on my own.
And also i did managed to send comments, and stuff.... the only problem is the video upload itself.
My code:
public function uploadVideo($video, $title, $description, $category, $keywords) {
$url = 'http://uploads.gdata.youtube.com/feeds/api/users/FacebookDevelopersIL/uploads';
$boundary = uniqid();
$accessToken = $this->refreshAccessToken("13", "11313", 'REFRESHTOKEN');
$xmlString = "<?xml version='1.0'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007'><media:group><media:title type='plain'>".$title."</media:title><media:description type='plain'>".$description."</media:description> <media:category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>".$category."</media:category><media:keywords>".$keywords."</media:keywords></media:group></entry>";
$videoData = file_get_contents($video);
$headers = array(
'POST /feeds/api/users/FacebookDevelopersIL/uploads HTTP/1.1',
'Host: uploads.gdata.youtube.com',
'Authorization: Bearer '.$accessToken,
'GData-Version: 2',
'X-GData-Key: key='.YOUTUBE_SRM_DEVELOPER_KEY,
'Slug: IMG_0047.mp4',
'Content-Type: multipart/related; boundary='.$boundary,
'Content-Length:'.strlen($videoData),
'Connection: close'
);
$postData = "--".$boundary . "\r\n"
."Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n"
.$xmlString . "\r\n"
."--".$boundary . "\r\n"
."Content-Type: video/mp4\r\n"
."Content-Transfer-Encoding: binary\r\n\r\n"
.$videoData . "\r\n"
."--".$boundary . "--";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
$response = curl_exec($ch);
curl_close($ch);
Trace::dump($response); }
The error im getting: HTTP/1.1 400 Bad Request Server: HTTP Upload Server Built on May 7 2012 18:16:42 (1336439802) Content-Type: text/html; charset=UTF-8 X-GUploader-UploadID: AEnB2Uq7cHcf6rS4bcamu18ChAF3gnKJqsF6U_dk2qB4WR9GhAoTL_-iUejitgead-Gh-1fpJcke1z68TAxoopS2vYiGmCW69A Date: Thu, 10 May 2012 11:55:24 GMT Pragma: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Cache-Control: no-cache, no-store, must-revalidate Content-Length: 15 Connection: close
Invalid Request
thanx everyone!
Couple of things I notice: hard coding the POST and Host headers is poor form, because curl will take care of them automatically for you. I suspect part of the problem is the insertion of the carriage return/line feed between the $videoData and the last boundary marker. That will be interpreted as part of the video file. All you need are line feeds as line separators. Maybe the carriage return renders the video file invalid?
Maybe curl_setopt($ch, CURLOPT_VERBOSE, true) will provide some illumination.
This works for me (on a Linux host):
/*
** https://developers.google.com/youtube/2.0/developers_guide_protocol_direct_uploading
*/
private function send_to_youtube($video_file, $video_info) {
// Refresh access token
log_msg("Obtaining access token");
$response = http_post($this->config['token_url'], array(
'client_id' => $this->config['client_id'],
'client_secret' => $this->config['client_secret'],
'refresh_token' => $video_info->refresh_key,
'grant_type' => $this->config['grant_type']
));
if ($response['http_code'] != 200)
throw new Exception("Unable to obtain access token. ".print_r($response, true));
$authorization = json_decode($response['contents'], true);
// Build multi-part upload request
// api xml and then video file contents
$boundary = uniqid();
$location = '';
if ($video_info->latitude && $video_info->longitude)
$location = '
<georss:where>
<gml:Point>
<gml:pos>'. $video_info->latitude .' '. $video_info->longitude .'</gml:pos>
</gml:Point>
</georss:where>';
$content = '--'.$boundary.'
Content-Type: application/atom+xml; charset=UTF-8
<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:georss="http://www.georss.org/georss"
xmlns:gml="http://www.opengis.net/gml">
<media:group>
<media:title type="plain">'. $video_info->title .'</media:title>
<media:description type="plain">
'. $video_info->description .'
</media:description>
<media:category
scheme="http://gdata.youtube.com/schemas/2007/categories.cat">
'. $video_info->category .'
</media:category>
<media:keywords>'. implode(', ', $video_info->tags) .'</media:keywords>
</media:group>
'. $location .'
</entry>
--'.$boundary.'
Content-Type: '. $video_info->type .'
Content-Transfer-Encoding: binary
'.file_get_contents($video_file).'
--'.$boundary.'--';
$headers = array(
'Authorization: '.$authorization['token_type'].' '.$authorization['access_token'],
'GData-Version: 2',
'X-GData-Key: key='.$this->config['dev_key'],
'Slug: '.$video_info->filename,
'Content-Type: multipart/related; boundary="'.$boundary.'"',
'Content-Length: '.strlen($content),
'Connection: close'
);
// Upload video
log_msg("Sending video '{$video_info->title}', {$video_info->url}");
$ch = curl_init($this->config['upload_url']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!$http_code == 201) { // Something other than 'New Entry'
log_msg("Upload Failed: ".print_r($response, true));
return new SimpleXMLElement();
}
$entry = new SimpleXMLElement($response);
$yt_link = $entry->link[0]->attributes()->href;
log_msg("Upload Complete: ".$yt_link);
return $entry;
}
<?php
/* gets the data from a URL */
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$paste_data=""; if(isset($_POST["paste_code"])) { $paste_data = $_POST["paste_code"]; }
echo $paste_data;
$returned_content = get_data('http://pastebin.com/api_public.php/paste_code(paste_data)');
echo $returned_content;
?>
This is my php code . where $paste_data contains the data to be pasted in a new page . How do I paste it using the function paste_code(String) ?
The documentation says that you need to submit a POST request to
http://pastebin.com/api_public.php
and the only mandatory parameter is paste_code, of type string is the paste that you want to make.
On success a new pastebin URL will be returned.
Bare bone example:
$ch = curl_init("http://pastebin.com/api_public.php");
curl_setopt ($ch, CURLOPT_POST, true);
// A new paste with the string "hello there SO"
curl_setopt ($ch, CURLOPT_POSTFIELDS, "paste_code=hello there SO");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
$response = curl_exec($ch);
echo $response;
and on running I get:
> POST http://pastebin.com/api_public.php HTTP/1.1
Host: pastebin.com
Accept: */*
Proxy-Connection: Keep-Alive
Content-Length: 25
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Date: Mon, 13 Dec 2010 07:51:12 GMT
< Content-Type: text/plain
< Server: nginx/0.8.52
< Vary: Accept-Encoding
< X-Powered-By: PHP/5.3.4-dev
< Via: 1.1 apac-nc06 (NetCache NetApp/6.0.6)
<
http://pastebin.com/Lc7kAw8Z* Closing connection #0
Clearly the response has the URL http://pastebin.com/Lc7kAw8Z
Visit it and you'll see a new paste containing hello there SO
FYI for others looking at this "post 2013", the api_public.php POST has been discontinued.
For those who stumple upon this thread via seach, here is a code that works in 2013:
<?php
$data = 'Hello World!';
$apiKey = 'xxxxxxx'; // get it from pastebin.com
$postData = array(
'api_dev_key' => $apiKey, // your dev key
'api_option' => 'paste', // action to perform
'api_paste_code' => utf8_decode($data), // the paste text
'api_paste_private' => '1', // 0=public 1=unlisted 2=private
'api_paste_expire_date' => '1D', // paste expires in 1 day
);
$ch = curl_init('http://pastebin.com/api/api_post.php');
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($postData),
CURLOPT_RETURNTRANSFER => 1,
));
$re = curl_exec($ch);
curl_close($ch);
$pasteId = end(explode('/', $re));
echo "Created new paste.\r\n Link:\t{$re}\r\n Raw:\t" . sprintf('http://pastebin.com/raw.php?i=%s', $pasteId) . "\r\n";