I am using this code to try to upload images located in my server to Media Library of my wordpress installation.
<?php
include("../../../wp-blog-header.php");
include("../../../wp-admin/includes/file.php");
include("../../../wp-admin/includes/media.php");
$id = 0;
$image = $_SERVER['DOCUMENT_ROOT'] . "/image01.jpg";
$array = array( //array to mimic $_FILES
'name' => basename($image), //isolates and outputs the file name from its absolute path
'type' => 'image/jpeg', //yes, thats sloppy, see my text further down on this topic
'tmp_name' => $image, //this field passes the actual path to the image
'error' => 0, //normally, this is used to store an error, should the upload fail. but since this isnt actually an instance of $_FILES we can default it to zero here
'size' => filesize($image) //returns image filesize in bytes
);
media_handle_sideload($array, $id); //the actual image processing, that is, move to upload directory, generate thumbnails and image sizes and writing into the database happens here
?>
I can see that this code takes my image called "image01.jpg" located in that path and then it put the image to /wp-contents/uploads/. However when I go to the admin panel in wordpress to see the image in the Media Library I cannot see the image. Also there is not any row in the wp_posts of this image.
UPDATE:
I used this time this code:
$result = media_handle_sideload($array, $id);
echo "Finish media handle sideload<br>";
if ( ! is_wp_error( $result ) ) {
echo "Result<br>";
print_r($result);
} else {
echo "Error<br>";
print_r($results);
}
echo "Finish script<br>";
Nothing is shown is the execution. I can't see the msg "Finish media handle sideload". However the file is moved from path specified in "$image" to "wp-content/uploads". Note that the files is moved, not copied, so if I execute the script without copy again the image to the source (path of $image), I can see some warnings about filesize function likes this:
Warning: filesize(): stat failed for C:/Users/dlopez/Documents/Development/web-folders/image01.jpg in C:\Users\dlopez\Documents\Development\web-folders\wp_test\wp-content\plugins\pods-csv-importer\upload.php on line 16
wp_insert_attachment