PHP Uploader (Functions)

Soldato
Joined
1 Dec 2004
Posts
23,082
Location
S.Wales
I want to expand my basic file uploader. Here is the code:


Code:
	<?php

//Variables
$_FILES["uploaded_file"]["name"];
$_FILES["uploaded_file"]["type"];
$_FILES["uploaded_file"]["size"];
$_FILES["uploaded_file"]["tmp_name"];
$_FILES["uploaded_file"]["error"];


//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  
  //Check if the file is JPEG image and it's size is less than 300Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_file"]["size"] < 1200000)) {
    
	//Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/phpupload/uploaddir/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 300Kb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

and i have a basic form which consists of a text field, a browse button, and an upload button which points to the above PHP.

At the moment i can only upload 1 file at a time of the one type (jpg).

I have some requirements below:

  1. The ability to upload multiple files in one session (maybe 5 at a time)
  2. If a filetype of the same name is uploaded, i want it to amend the name instead of refusing to upload it
  3. The ability to upload files of multiple types (jpg, wmv, avi, pdf, doc)
  4. A seperate page that will display a gallery (small thumbnails of the images only that have been uploaded.

How easy would it be to do the above?
 
The ability to upload multiple files in one session (maybe 5 at a time)
Look into ajax technology, it may be worth dynamically adding a new path textbox / browse button after each one is used.

If a filetype of the same name is uploaded, i want it to amend the name instead of refusing to upload it
Generate a random string and insert it before/after each image name

The ability to upload files of multiple types (jpg, wmv, avi, pdf, doc)
Simply check this upon post and only allow those types

A seperate page that will display a gallery (small thumbnails of the images only that have been uploaded.
Query the DB for images which meet your criteria (SELECT imagename from table where userid='blah') and then loop through the results and create a line for each image "<a href='http://blah.com/images/". $imagename ."'>"
To create thumbnails you'll need to use imagemagik and script that process in (ideally when the images are uploaded)
 
[Sniper][Wolf] said:
How easy would it be to do the above?
A bit of an odd question... a precursory hint asking for us to do the legwork? IIRC you were given quite a few pointers in your previous thread; rather than being spoonfed, try some independent learning using the PHP manual, tutorials, basic logic and trial and error.

Nonetheless, here are some pointers:
  1. Give each input a name attribute, then the $_FILES array will reflect said naming convention
  2. You can perform a check with file_exists(), then delete the original file with unlink()
  3. Put allowed filetypes in an array, then use in_array() on the file extensions to perform the matching... I swear I gave you some code in your previous topic
  4. opendir(), readdir()
 
Last edited:
i is noob but i made myself a little image uploader recently. a couple of tips....

a)
what's this?

Code:
$_FILES["uploaded_file"]["name"];
$_FILES["uploaded_file"]["type"];
$_FILES["uploaded_file"]["size"];
$_FILES["uploaded_file"]["tmp_name"];
$_FILES["uploaded_file"]["error"];

remove it, it serves no purpose.

b)
use the error checking built into the form

Code:
$error = $_FILES['userfile']['error'];
switch($error) {
    case 0:
        //no error. process data
    case 1:
        //file larger than limit set in php.ini
    case 2:
        //file larger than limit set in form
    case 3:
        //only part of the file was uploaded
    case 4: 
        //no file selected
    default:
       //unknown error
}

c)
i use this to prefix a random number if the file exists...

Code:
$path = 'files/';
$name = @mysql_real_escape_string($_FILES['userfile']['name']);
$tmp_name  = $_FILES['userfile']['tmp_name'];
while(file_exists($path.$rand.$name)) {
	$rand = rand(1, 9999);
}
$name = $rand.$name;
if(move_uploaded_file($tmp_name, $path.$name)) {
    //add file details to database
}

d)
here's my code for generating thumbnails 200x200 (leave files as is if they are smaller. requires the GD library. most reputable hosts should have this enabled.)

Code:
$path = 'files/';
$prefix = 'thumb_';

$im = imagecreatefromjpeg($tmp_name);
$width = imagesx($im);
$height = imagesy($im);
$thumb = $path.$prefix.$name;
if(($width <= 200) && ($height <= 200)) {
        imagejpeg($im, $thumb);
        imagedestroy($im);
} else {
        $ratio = $width/$height;
	if ($ratio>1){
		$newwidth = 200;
		$newheight = 200/$ratio;
	} else {
		$newwidth = 200*$ratio;
		$newheight = 200;
	}
	$new = imagecreatetruecolor($newwidth,$newheight);
	imagecopyresampled($new, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
	imagejpeg($new, $thumb);
	imagedestroy($new);
}

that'll do for now. no doubt the php guru's will be cringing but it works for me... :p
 
Most of what you lot have suggested i just cant get my head around, not unless i start this script from scratch, i cant encorporate it into my existing code.

I have worked out on my own how do upload different extensions, even if it is abit long winded!


Code:
$filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg")  || ($ext == "txt") && ($_FILES["uploaded_file"]["type"] == "text/plain") || ($ext == "gif") && ($_FILES["uploaded_file"]["type"] == "image/gif") && ($_FILES["uploaded_file"]["size"] < 307200)) {
 
Created a new script from scratch, which is below:

Code:
<?php

//Variable Declarations
$_FILES["uploaded_file"]["name"];
$_FILES["uploaded_file"]["type"];
$_FILES["uploaded_file"]["size"];
$_FILES["uploaded_file"]["tmp_name"];
$_FILES["uploaded_file"]["error"];

$target = "phpupload/uploaddir/"; //Upload Directory
$target = $target . basename( $_FILES['uploaded_file']['name']) ;  //Target file details



$ok=1; //Error Generator (1=No Error, 0= Error)



//This is our size condition, Files must be under 300kb
if ($uploaded_size > 307200)
{
echo "Files need to be under 300kb <br>";
$ok=0;
}


//This is our limit file type condition, supported types include 
if ($uploaded_type !="image/jpeg")
{
echo "No supported files<br>";
$ok=0;
} 


//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}

//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded_file']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
} 

?>

problem is this part

Code:
/This is our limit file type condition, supported types include 
if ($uploaded_type !="image/jpeg")
{
echo "No supported files<br>";
$ok=0;
}

From that snippet, what you would expect it to upload all files with the "image/jpeg" mime type, if the uploaded type is not equal to "image/jpeg" it will echo the error "No supported files" and set the error count to 0 (0 means that there are errors)

but that doest work, iv tried lots of combos which dont seem to work, i can only get all files to upload, or none.
 
Why have you still got those "variable declarations" as marc2003 suggested removing? They're not declarations, they do nothing.
 
In this bit:
Code:
//This is our limit file type condition, supported types include 
if ($uploaded_type !="image/jpeg")
{
echo "No supported files<br>";
$ok=0;
}
just underneath it, outside if the if(){} statement, put:

echo "The Upload Type was $uploaded_type <br>";

Then you'll see what's actually in your $uploaded_type variable.

Also, your variable declerations aren't doing anything :p

This is doing something:
$myVariable = "Something";

So is this:
$myArray = array();

But this:
$variable;

Is just like saying... I dunno, nothing. lol. It's like, stating something random. This is kinda like saying "the car is called a clio":
$myCar = "Clio";

and this is like saying "the car" for no apparent reason:
$myCar;

(your code is saying the car for no apparent reason);)

[ PHP ] [ /PHP ] MODS: PHP tags need a white background!
 
here's a very basic working one....

Code:
<?php
if($_POST['upload']) {
	$target = "files/";
	$name = ($_FILES['userfile']['name']);
	$tmp_name  = $_FILES['userfile']['tmp_name'];
	$type = $_FILES['userfile']['type'];
	$error = $_FILES['userfile']['error'];
	switch($error) {
		case 0:
			$types = array('image/jpeg', 'image/pjpeg');
			if(in_array($type, $types)) {
                                while(file_exists($target.$rand.$name)) {
				        $rand = rand(1, 9999);
			        }
				$name = $rand.$name;
				if(move_uploaded_file($tmp_name, $target.$name)) {
					$message = 'file uploaded ok';
				} else {
					$message = 'unable to process file';
				}
			} else {
				$message = 'sorry, that wasn\'t a valid file type';
			}
			break;
                case 1:
		case 2:
			$message = 'the maxium file size allowed is 300kb';
			break;
		case 3:
			$message = 'only part of the file was uploaded';
			break;
		case 4:
			$message = 'you didn\'t select a file!';
	}
}
?>
<html>
<head></head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="uploadform">
<p><input name="MAX_FILE_SIZE" type="hidden" value="307200">
<input name="userfile" type="file" size="40">
<input type="submit" name="upload" value="upload"></p>
</form>
<br>
<?php echo $message."<br>"; ?>
</body>
</html>

:)

edited: to add random number to start of filename if it already exists.

edit2: because i bodged the random number code. uploading files with different filenames still would have worked....
 
Last edited:
just underneath it, outside if the if(){} statement, put:

echo "The Upload Type was $uploaded_type <br>";

Then you'll see what's actually in your $uploaded_type variable.


It doesnt output nothing, nothing is being stored in the variable, hence it aint working.

Ill have ago at that switch array one, its far too complicated for my level of coding, think i might just give it a miss :(
 
[Sniper][Wolf] said:
Ill have ago at that switch array one, its far too complicated for my level of coding, think i might just give it a miss :(

what? you don't actually have to do anything. that's the whole page i've posted there. just try it and see if it works. i did test before posting....
 
Last edited:
It doesnt do anything, when i click submit i just get a blank page and nothing its uploaded/outputted
 
psyr33n said:
Jesus, ask for help then dismiss it... seriously, just ****ing try it and experiment.
im not being funny mate but chill out.its alrite for some people who can read this stuff and get it.i appriciate everyones help on here and as i said im going to have ago when i get the chance. If the web was full of decent tutorials i wouldnt be spending most of my day on google wasting my time.but for programming its close to useless to me.
 
find me a tutorial of a working,decent,secure upload script and i will appoligise.every one i have tried isnt fit for use on a live website.
 
[Sniper][Wolf] said:
find me a tutorial of a working,decent,secure upload script and i will appoligise.every one i have tried isnt fit for use on a live website.

what's the point? you won't take any notice of it anyway. in my first reply i posted this...

marc2003 said:
a)
what's this?

Code:
$_FILES["uploaded_file"]["name"];
$_FILES["uploaded_file"]["type"];
$_FILES["uploaded_file"]["size"];
$_FILES["uploaded_file"]["tmp_name"];
$_FILES["uploaded_file"]["error"];

remove it, it serves no purpose.

yet you posted it again so furnace had to explain what a waste of space it was.... :p
 
Last edited:
Back
Top Bottom