5

I'm currently using this code for PHP file upload (found directly on the wordpress page):

<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form> 

upload.php

    $allowedExts = array("jpg", "jpeg", "gif", "png");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if ((($_FILES["file"]["type"] == "image/gif")
         || ($_FILES["file"]["type"] == "image/jpeg")
         || ($_FILES["file"]["type"] == "image/png")
         || ($_FILES["file"]["type"] == "image/pjpeg"))
        && ($_FILES["file"]["size"] < 20000)
        && in_array($extension, $allowedExts))
    {
        if ($_FILES["file"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
        else
        {
            echo "Upload: " . $_FILES["file"]["name"] . "<br>";
            echo "Type: " . $_FILES["file"]["type"] . "<br>";
            echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
            echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

            if (file_exists("upload/" . $_FILES["file"]["name"]))
            {
                echo $_FILES["file"]["name"] . " already exists. ";
            }
            else
            {
                move_uploaded_file($_FILES["file"]["tmp_name"],
                                   "upload/" . $_FILES["file"]["name"]);
                echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
            }
        }
    }
    else
    {
        echo "Invalid file";
    }

It always returns "invalid file" even when I know 100% it should work.

I've been looking around online and I think that WP cannot do enctype="multipart/form-data" so that's why it doesn't work.

Does anyone have a work around or any idea why this won't work?

5 Answers 5

9

I know this post is kinda old, but hopefully will help others.

I was doing something very similar (custom uploads to display on a custom page) and also using practically the exact same code as objectiveccoder001. I kept getting "Invalid file." and write permission errors. I ended up going with this:

if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
    echo "File is valid, and was successfully uploaded.\n";
    //var_dump( $movefile);
} else {
    echo "Possible file upload attack!\n";
}

Works great if you're not looking to use Wordpress's media uploader and just need a simple file upload. It still uploads it using a dated file structure like the built in uploader. Then you can just use $movefile array to get the file's data.

Reference: http://codex.wordpress.org/Function_Reference/wp_handle_upload

Sign up to request clarification or add additional context in comments.

1 Comment

Help full for Custom file uploading
4

YOu can use wordpress default media file uploader by using this code and simply retrieve link of image in jquery

<label for="upload_image">
        <input id="upload_image" type="text" size="36" name="ad_image" value="http://" /> 
        <input id="upload_image_button" class="button" type="button" value="Upload Image" />
        <br />Enter a URL or upload an image
    </label>

<?php
add_action('admin_enqueue_scripts', 'my_admin_scripts');

function my_admin_scripts() {
    if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
        wp_enqueue_media();
        wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));
        wp_enqueue_script('my-admin-js');
    }
}

?>

<script>
    jQuery(document).ready(function($){


    var custom_uploader;


    $('#upload_image_button').click(function(e) {

        e.preventDefault();

        //If the uploader object has already been created, reopen the dialog
        if (custom_uploader) {
            custom_uploader.open();
            return;
        }

        //Extend the wp.media object
        custom_uploader = wp.media.frames.file_frame = wp.media({
            title: 'Choose Image',
            button: {
                text: 'Choose Image'
            },
            multiple: true
        });

        //When a file is selected, grab the URL and set it as the text field's value
        custom_uploader.on('select', function() {
            console.log(custom_uploader.state().get('selection').toJSON());
            attachment = custom_uploader.state().get('selection').first().toJSON();
            $('#upload_image').val(attachment.url);
        });

        //Open the uploader dialog
        custom_uploader.open();

    });


});
    </script>

Comments

4

Upload file is very easy in new version of WordPress. Just one line of code:

$uploaded_file = wp_upload_bits( $_FILES['file']['name'], null, @file_get_contents( $_FILES['file']['tmp_name'] ) ); 

$uploaded_file is an array which will return all the information including url, file type etc

Comments

3

HOW TO UPLOAD FILES TO A CUSTOM DIRECTORY IN WORDPRESS

This example uploads a PDF document in the wp-content/uploads/customDirectory folder

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submittheform">
</form>

global $wp_filesystem;
WP_Filesystem();

$content_directory = $wp_filesystem->wp_content_dir() . 'uploads/';
$wp_filesystem->mkdir( $content_directory . 'CustomDirectory' );

$target_dir_location = $content_directory . 'CustomDirectory/';
 
if(isset($_POST["submittheform"]) && isset($_FILES['fileToUpload'])) {
 
    $name_file = $_FILES['fileToUpload']['name'];
    $tmp_name = $_FILES['fileToUpload']['tmp_name'];
 
    if( move_uploaded_file( $tmp_name, $target_dir_location.$name_file ) ) {
        echo "File was successfully uploaded";
    } else {
        echo "The file was not uploaded";
    }
 
}

Comments

-5

why not use WordPress built-in uploader to upload your file?
Here is a quick tutorial about how to implement WordPress Uploader

WordPress Uploader

2 Comments

Because it's a custom file type. The uploader won't allow me to upload it.
@objectiveccoder001 take a look on this link wordpress.org/support/topic/… hope this help you..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.