SnareChops
SnareChops

Reputation: 13347

php file upload move_uploaded_file() Failed to open stream

I have a file upload script:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["picture"]["name"]));
if ((($_FILES["picture"]["type"] == "image/gif") || ($_FILES["picture"]["type"] == "image/jpeg") || ($_FILES["picture"]["type"] == "image/jpg") || ($_FILES["picture"]["type"] == "image/png")) && in_array($extension, $allowedExts)):
    if($_FILES["picture"]["error"] > 0):
        echo "Error: " . $_Files["picture"]["error"];
    else:
        move_uploaded_file($_FILES["picture"]["tmp_name"], "/TnA/ProfilePics/" . $_SESSION['ID'] . "." . $extension);
    endif;
endif;

But I am getting the errors:

Warning: move_uploaded_file(TnA/ProfilePics/1.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/91/9848191/html/TnA/webservice.php on line 1067

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php5nOdhI' to 'TnA/ProfilePics/1.jpg' in /home/content/91/9848191/html/TnA/webservice.php on line 1067

Here is my file structure:

Web Host Root (I have another site here)
    -TnA (Root of this site)
        -index.html
        -webservice.php
        -ProfilePics
            -(My target location)

What relative directory url should I be using? I have tried ProfilePics/1.jpg and /ProfilePics/1.jpg both result in the same error.

EDIT:

Using:

move_uploaded_file($_FILES["picture"]["tmp_name"], dirname(__FILE__) . "ProfilePics/" . $_SESSION['ID'] . "." . $extension);

I get:

Warning: move_uploaded_file(/home/content/91/9848191/html/TnA/ProfilePics/1.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/91/9848191/html/TnA/webservice.php on line 1067

Upvotes: 0

Views: 12993

Answers (1)

Denis O.
Denis O.

Reputation: 1850

Most likely that you have problem using relevant paths. If your upload script is webservice.php then you are actually trying to put file into / %webHostRoot% / TnA / TnA / ProfilePics / directory. Use full path in move_uploaded_file()'s target. Try to use something like:

move_uploaded_file($_FILES["picture"]["tmp_name"], dirname(__FILE__)."ProfilePics/" . $_SESSION['ID'] . "." . $extension);

UPD: Here's func to create dirs recursively:

function MkDirTree($path,$permissions = 0755, $compat_mode=true) {
    if (!$compat_mode) {
        $dirs = split("/",$path);
        $path = "";
        foreach ($dirs as $key=>$dir) {
            $path .= $dir."/";
            if ($dir!="" && !is_dir($path)) exec("mkdir -m ".$permissions." ".$path);
        }
    } else {
        $dirs = split("/",$path);
        $path = "";
        foreach ($dirs as $key=>$dir) {
            $path .= $dir."/";
            if ($dir!="" && !file_exists($path)) mkdir($path, $permissions);
        }
    }
    return file_exists($path);
}

Upvotes: 3

Related Questions