muttley91
muttley91

Reputation: 12674

PHP File Upload Issues

I'm looking for some help with PHP File Upload. I'm trying to upload an image, using the following code (provided in the w3schools tutorial):

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  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";
  }

Obviously I have some changes to make to their code, but it doesn't do what it says it's supposed to do as it is. So I'm asking:

  1. Why does this not make a new folder called 'upload' as it claims it will? I get the following error: Warning: move_uploaded_file(upload/donkeykong.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in ... etc.

  2. How should I write the URL where I want the image uploaded?

Upvotes: 0

Views: 1742

Answers (4)

Naveen Kumar
Naveen Kumar

Reputation: 4601

Hope this helps

<?php
if (isset($_FILES['photo']))
{
    $mimetype = mime_content_type($_FILES['photo']['tmp_name']);
    if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {

    move_uploaded_file($_FILES['photo']['tmp_name'],
 '/images/' . $_FILES['photo']['name']);
   echo 'OK';
     } else {
             echo 'Not an image file!';
     }
}

Upvotes: 1

Kurt
Kurt

Reputation: 7212

1.Usually means the file path is incorrect or the permissions are not set correctly. You should create the upload directory and set it so that the appropriate people can read and write from it manually. In apache I think it is something like this:

mkdir uploaded_files
chown -R nobody uploaded_files
chmod 755 -R uploaded_files

2.In regards to the path, you can use absolute or relative- best to do just use:

$_SERVER['DOCUMENT_ROOT] . '/uploaded_files'

Upvotes: 1

Dan Kanze
Dan Kanze

Reputation: 18595

I built this awial ago, works for JPEG, JPG, GIF, PNG

Saves to current directory "images".

<?
max_size = 300; //size in kbs

if($_POST['Submit'] == "Upload"){$image =$_FILES["file"]["name"];$uploadedfile = $_FILES['file']['tmp_name'];
    if ($image){$filename = stripslashes($_FILES['file']['name']);$extension = getExtension($filename); $extension = strtolower($extension);    
        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {$change='Invalid Picture';$errors=1;}
        else{$size=filesize($_FILES['file']['tmp_name']);
            if ($size > $max_size*1024){$change='File too big!';$errors=1;}
            else{
                if($extension=="jpg" || $extension=="jpeg" ){$uploadedfile = $_FILES['file']['tmp_name'];$src = imagecreatefromjpeg($uploadedfile);}
                else if($extension=="png"){$uploadedfile = $_FILES['file']['tmp_name'];$src = imagecreatefrompng($uploadedfile);}
                else {$src = imagecreatefromgif($uploadedfile);}
                echo $scr;
                list($width,$height)=getimagesize($uploadedfile);

                //MAIN IMAGE
                $newwidth=300;
                $newheight=($height/$width)*$newwidth;
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                $kek=imagecolorallocate($tmp, 255, 255, 255);
                imagefill($tmp,0,0,$kek);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

                //Does Directory Exhist?
                if(is_dir("images")==FALSE){mkdir("images");}

                //Build file path and SAVE
                $filepath = "images/".md5(genRandomString().$_FILES['file']['name']).".".$extension;
                imagejpeg($tmp,$filepath,100);
                imagejpeg($tmp,$filepath,100);
                imagedestroy($src);
                imagedestroy($tmp);

                //ERROR HANDLING
                if($_FILES["file"]["size"]<=0){$errors=1;$change='No file';}
                if($errors!=1){$change='Image Uploaded!';}
            }
        }
    }
}
?>

For your errors:

<div><? echo $change ?></div>

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270617

It doesn't create a folder because mkdir() is never called. The code assumes the upload/ directory already exists. Create the directory if it doesn't exist with:

if (!file_exists('upload')) {
  mkdir('./upload');
}

As an aside, the statement at the beginning can be cleaned up in a number of ways. One possibilty is to use in_array() rather than a bunch of || conditions:

if (in_array($_FILES['file']['type'], array("image/gif", "image/jpeg", "image/pjpeg")
  && ($_FILES["file"]["size"] < 20000)
)

To place the uploads in upload/ relative to the server document root, you can use $_SERVER['DOCUMENT_ROOT']. However, you should create the upload/ directory manually and make it writable by the web server. In order to create the directory through PHP, the whole document root would need to be writable by the web server, which is a massive security flaw.

$uploads_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
move_uploaded_file($_FILES["file"]["tmp_name"], $uploads_dir . $_FILES["file"]["name"]);

Upvotes: 4

Related Questions