How to move uploaded file from temporary directory to a newly created folder inside a permanent directory

StackOverflow https://stackoverflow.com/questions/20464984

Pregunta

The following script uploads successfully and moves the file to the permanent directory.

I'm creating a new folder with a name of a profile ID inside the parent permanent directory, so that all uploaded files can be inside a folder with a name of a profile, and the new folder is created inside the parent folder.

Problem: When the file is moved, it's moved into the parent folder, not the newly created folder.

PHP Upload script.

<?php
define("UPLOAD_DIR", "images/$Pid");
if (!file_exists(UPLOAD_DIR)){
    mkdir(UPLOAD_DIR, 0777, true);
    }
if (!empty($_FILES["imageUpload"])){
    $myFile = $_FILES["imageUpload"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    } else {
        $imageDir = UPLOAD_DIR .'/'. $_FILES["imageUpload"]["name"];
        echo $imageDir;
    }
    chmod(UPLOAD_DIR . $name, 0644);
}

?>

Thanks.

¿Fue útil?

Solución

Change

$success = move_uploaded_file($myFile["tmp_name"],
    UPLOAD_DIR . $name);

To

$success = move_uploaded_file($myFile["tmp_name"],
    UPLOAD_DIR . '/'.$name);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top