I have about 300 images I want to upload to my new Tumblr account, becuase my old wordpress site got hacked and I no longer wish to use wordpress.
I uploaded one image a day for 300 days, and I'd like to be able to take these images and upload them to my tumblr site using the api.
The images are currently local, stored in /images/. They all have the date they were uploaded as the first ten characters of the filename, (01-01-2009-filename.png) and I went to send this date parameter along as well. I want to be able to see the progress of the script by outputting the responses from the API to my error_log. Here is what I have so far, based on the tumblr api page.
// Authorization info
$tumblr_email = '[email protected]';
$tumblr_password = 'password';
// Tumblr script parameters
$source_directory = "images/";
// For each file, assign the file to a pointer
here's the first stumbling block. How do I get all of the images in the directory and loop through them? Once I have a for or while loop set up I assume this is the next step
$post_data = fopen(dir(__FILE__) . $source_directory . $current_image, 'r');
$post_date = substr($current_image, 0, 10);
// Data for new record
$post_type = 'photo';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'data' => $post_data,
'date' => $post_date,
'generator' => 'Multi-file uploader'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Output response to error_log
error_log($result);
So, I'm stuck on how to use PHP to read a file directory, loop through each of the files, and do things to the name / with the file itself. I also need to know how to set the data parameter, as in choosing multi-part / formdata. I also don't know anything about cURL.
You can use the glob
function to quickly get an array of files matching a pattern. That is:
foreach (glob('images/*.png') as $current_image) {
...
}
To make curl upload the file, you can simply pass it the file name prefixed with an @
(see the CURLOPT_POSTFIELDS
description at http://www.php.net/curl_setopt). At the minute you're passing it a PHP file handle, which doesn't make too much sense. Change $post_data
to:
$post_data = '@' . dirname(__FILE__) . '/' . $current_image;
And you should be good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With