This is the code I am using to upload the file to WordPress
define(âWP_DEBUGâ, true);
$filename = "test.png";
$tmpFile = download_url("http://url.com/testing/crop/".$filename);
chmod($tmpFile, 0755);
$mimeType = wp_check_filetype($_SERVER['DOCUMENT_ROOT'] . '/testing/crop/'.$filename);
$file_array = array(
'file' => $_SERVER['DOCUMENT_ROOT'] . '/testing/crop/'.$filename,
'url' => $_SERVER['DOCUMENT_ROOT'] . '/testing/crop/'.$filename,
'type' => $mimeType['type'],
'size' => filesize($_SERVER['DOCUMENT_ROOT'] . '/testing/crop/'.$filename),
'name' => $filename,
'tmp_name' => $tmpFile
);
$image = wp_handle_upload($file_array, array('test_form' => FALSE, 'test_upload' => FALSE, 'test_type' => FALSE));
print_r($file_array);
print_r($image);
unlink($tmpFile);
?>
This is the error I am getting “The uploaded file could not be moved to /home/xxxx/public_html/wp-content/uploads/2012/09.”
What I am trying to do is have a small PHP script outside of WordPress upload images to its Media Library and then post it however at this point I am getting stuck at the uploading stage.
All the permissions are correct as I am able to upload fine through the WordPress admin area.
Any help is much appreciated.
The
move_uploaded_file
function is a PHP function:http://php.net/manual/en/function.move-uploaded-file.php
One important thing to note about it from that page:
You’re not uploading a file here, you’re downloading it from a URL, saving it locally, and then attempting to use
wp_handle_upload
(which usesmove_uploaded_file
) to handle it. This fails because it’s not actually an uploaded file.What you’re actually trying to do is called a “sideload”, where you get a file from URL and load it in directly. WordPress has a function for this specific case, called
wp_handle_sideload
. For the specific case of images, WordPress has another function calledmedia_sideload_image
that does much the same thing but also handles all the image processing.If you really are wanting to upload files and not sideload them from a URL (this could be test code you’re trying to do), then you need to code up a file upload form, get the contents of the
$_FILES[0]
parameter, and pass that towp_handle_upload
. If you’re trying specifically to handle uploaded images or other items for the media library, usemedia_handle_upload
instead. Uploads through these function have to be real, not faked.