Using PHP for file-upload in Wordpress

24,658

Solution 1

pathinfo() expects a path not a URL.

$target_dir should be a path, eg: /home3/dy/public_html/wp-content/uploads. Check $_SERVER['DOCUMENT_ROOT'] if you are not sure.

$target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"]);

Then, you've got a path where you want the files to be uploaded to. Now you need to run:

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

Solution 2

A recommended approach is to use wp_handle_upload() function. You can use it with wp_insert_attachment() if you wanted to add files to media library.

The first function wp_handle_upload() does:

Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type, and moving the file to the appropriate directory within the uploads directory.

An example from WordPress site with some changes

if ( ! function_exists( 'wp_handle_upload' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

$uploadedfile = $_FILES['file'];

/* You can use wp_check_filetype() function to check the
 file type and go on wit the upload or stop it.*/

$movefile = wp_handle_upload( $uploadedfile);

if ( $movefile && !isset( $movefile['error'] ) ) {
    echo "File is valid, and was successfully uploaded.\n";
    var_dump( $movefile);
} else {
    /**
     * Error generated by _wp_handle_upload()
     * @see _wp_handle_upload() in wp-admin/includes/file.php
     */
    echo $movefile['error'];
}

Alternatively you could just use wp_upload_dir() to get only the upload dir.

For more information on using native WordPress function for upload check this article: How to Upload a File With WordPress’ Secret Native Functions

Solution 3

If you want to upload a file to the library and attach it to a post you can use the Wordpress function media_handle_upload()

$attachment_id = media_handle_upload( 'your_file_field_name', $post_id);

See example

Share:
24,658
p.luck
Author by

p.luck

Updated on September 04, 2021

Comments

  • p.luck
    p.luck over 2 years

    I'm trying to upload files from the front end of a wordpress page to send to the back-end wordpress directory within wp-content. I can't figure out why files are not appearing in the back end folder 'uploads' which is what the $target_dir is set as. Here is my HTML form on one page.

    <form action="http://www.aeroex.co.uk/php-upload/" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
    </form>
    

    The form action page for the above form, www.aeroex.co.uk/php-upload/ , contains the following PHP code:

    <?php
    $target_dir = "http://www.aeroex.co.uk/home3/dy/public_html/wp-content/uploads";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
    }
    ?>
    
  • p.luck
    p.luck about 8 years
    Where do I run that line of code? Do I put it after $target_file ?
  • Tim Hysniu
    Tim Hysniu about 8 years
    move_uploaded_file() is something you run if $uploadOk == 1. But before that please make sure you know what the $target_dir actually is. If I understand correctly, this should be its path: $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads';
  • p.luck
    p.luck about 8 years
    Although this works fine and is uploading my file to the directory, I keep getting the following message: Warning: getimagesize(/tmp/phpD8fHDn): failed to open stream: No such file or directory in /home3/ddy/public_html/wp-content/themes/vantage/templates/t‌​emplate-upload.php on line 26 File is not an image.
  • Tim Hysniu
    Tim Hysniu about 8 years
    If you've already used move_uploaded_file() then the file will no longer be in this location: $_FILES["fileToUpload"]["tmp_name"]. You want to use getimagesize() before you move it. Lastly, I recommend consider Kalimah's answer too. It may not always be applicable but is the recommended Wordpress way of handling uploads.
  • p.luck
    p.luck about 8 years
    It was sorted by changing $check = getimagesize($target_file); . The message no longer comes up so its all working fine.
  • Fanky
    Fanky over 4 years
    Works to me only when I change the line to $movefile = wp_handle_upload( $uploadedfile, array( 'test_form' => false )); as recommended here
  • Fanky
    Fanky over 4 years
    Also i don't think how I would run wp_check_filetype() on $_FILES. An alternative I found working is if (in_array(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $uploadedfile['tmp_name']), array('image/jpeg', 'image/png','image/gif'))){ /*do the rest*/ }