Search code examples
phphtmlwordpressformsfile-upload

Using PHP for file-upload in Wordpress


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;
}
}
?>

Solution

  • 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);