Using “media_handle_sideload” to upload images programmatically does not upload image to Media Library

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.

Read More

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:UsersdlopezDocumentsDevelopmentweb-folderswp_testwp-contentpluginspods-csv-importerupload.php
on line 16

Related posts

4 comments

  1. Your failing and getting a WP_Error object returned before the function runs wp_insert_attachment().

    You should always include a check for is_wp_error( $thing ) when calling a function that returns WP_Errors.

    $result = media_handle_sideload($array, $id);
    
    if ( ! is_wp_error( $result ) ) {
       return $result;
    } else {
       var_dump( $result->get_error_messages );
     }
    

    Your problem will be listed in the output of error messages

  2. <?php 
        // Need to require these files
        if ( !function_exists('media_handle_upload') ) {
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            require_once(ABSPATH . "wp-admin" . '/includes/file.php');
            require_once(ABSPATH . "wp-admin" . '/includes/media.php');
        }
    
        $url = "https://www.w3schools.com/css/img_fjords.jpg";
        $tmp = download_url( $url );
        if( is_wp_error( $tmp ) ){
            // download failed, handle error
        }
        $post_id = 0; // set 0 for no parent post id or simple attachment otherwise pass post id for include in post 
        $desc = "The WordPress Logo";
        $file_array = array();
    
        // Set variables for storage
        // fix file filename for query strings
        preg_match('/[^?]+.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
        $file_array['name'] = basename($matches[0]);
        $file_array['tmp_name'] = $tmp;
    
        // If error storing temporarily, unlink
        if ( is_wp_error( $tmp ) ) {
            @unlink($file_array['tmp_name']);
            $file_array['tmp_name'] = '';
        }
    
        // do the validation and storage stuff
        $id = media_handle_sideload( $file_array, $post_id, $desc );
    
        // If error storing permanently, unlink
        if ( is_wp_error($id) ) {
            @unlink($file_array['tmp_name']);
            return $id;
        }
    
        $src = wp_get_attachment_url( $id );
    ?>
    

    apply this code and pass your file URL. That is works for me.

    for more details please check WordPress function reference for media_handle_sideload.

  3. You shouldn’t assign a string valus to image. According to the example in this page, at first you must download files to temporary directory using download_url() and assign object returned by this function to $image:

    $image = download_url("http://yoursite.com/image01.jpg");
    

    Don’t forget to unlink() the $image at the end of function.

  4. Does the form that the file is coming from use:

    enctype="multipart/form-data"
    

    e.g.,

    <form method="post" enctype="multipart/form-data">
    

Comments are closed.