Jump to content

upload form validation


saunders1989

Recommended Posts

im trying to do some simple validation on my upload form. first of all i want to only allow a max size of 5mb to be uploaded. i have done that i think! but if the file is larger than 5mb i dont know how to echo an error in my code. could someone please advise. the second bit of validation i would like to do is check before it is moved to the folder if the file name already exists. could someone also advise me on this please. my code is below:

 

Thanks

 

<?php

$max_size=5*1024*1024;

// Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)
{
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
	 $target_path = "images/";
	$target_path = $target_path . basename( $_FILES['uploaded_file']['name']); 

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']). 
    " has been uploaded";

$dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         							}			 

         // Gather all required data
         $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
         $size = intval($_FILES['uploaded_file']['size']);
         $image_path = $dbLink->real_escape_string($target_path);
	 $gallery_type = $dbLink->real_escape_string($_POST['gallery_type']); 

//query to insert the data i had gathered into the database
$query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`)
             VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}')";

		 //executes the query
		 	$dbLink->query($query);
	} 
}
  else {
     		echo 'Error! A file was not sent!';
		   }
}
  
// Echo a link back to the main page
echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
?>

Link to comment
Share on other sites

1. size of uploads is limite through the setting in your php.ini file

i.e. "upload_max_filesize = 2M" to limit the size to 2M

when a file is uploaded which is larger, this aplies:

http://nl3.php.net/manual/en/features.file-upload.php#73762

 

2. to check if a file exists read this:

http://nl3.php.net/manual/en/function.file-exists.php

 

 

Link to comment
Share on other sites

so the else statement should look like this:

 

<?php

$max_size=5*1024*1024;
$filename =.  basename($_FILES['uploaded_file']['name']);

// Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)
{
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
	 $target_path = "images/";
	$target_path = $target_path . basename( $_FILES['uploaded_file']['name']); 

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']). 
    " has been uploaded";

$dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         							}			 

         // Gather all required data
         $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
         $size = intval($_FILES['uploaded_file']['size']);
         $image_path = $dbLink->real_escape_string($target_path);
	 $gallery_type = $dbLink->real_escape_string($_POST['gallery_type']); 

//query to insert the data i had gathered into the database
$query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`)
             VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}')";

		 //executes the query
		 	$dbLink->query($query);
	} 
}
  else {
     		echo 'Error! A file was not sent!';
		   }
}
     else {
                 echo "The file is too large";
}
  
// Echo a link back to the main page
echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
?>

Link to comment
Share on other sites

Just so you know if a user attempts to upload a file to your server that is LARGER than the php.ini allowed size the file will NOT be uploaded.

But your if statement

if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)

will still return true because a) uploaded_file is still set and b) the $_FILES array will report the file size as 0 ..

 

You need to handle the $_FILES[...]['error'] first..

 

example. (this is a print_r of $_FILES with a file that is too large)

[pre]

Array

(

    [file1] => Array

        (

            [name] => SomeExampleFile.jpg

            [type] =>

            [tmp_name] =>

            [error] => 1

            => 0

        )

)

[/pre]

Link to comment
Share on other sites

thanks for that little bit of info about the php.ini

 

im really sorry but i dont understand clearly what i would have to do i am very new to php (1 week in). i understand i would have to do something like

 

if($_FILES['uploaded_file']['error'] == 1) {

 

echo 'error';

}

 

but not sure how i would go about placing that into my code if that is even correct

Link to comment
Share on other sites

Off the top of my head (its 4:30am here) I would do something like this..

if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == 0) {
// First check completed successfully proceed with your code
} else {
// Grab the error from $_FILES['uploaded_file']['error'] and display an appropriate message or if the error was due to $_FILES not being set show then that error 
}

Link to comment
Share on other sites

so the code would be (coloured line):

 

sorry to keep you up

 

<?php

$max_size=5*1024*1024;

// Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)
{
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
	 $target_path = "images/";
	$target_path = $target_path . basename( $_FILES['uploaded_file']['name']); 

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']). 
    " has been uploaded";

$dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         							}			 

         // Gather all required data
         $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
         $size = intval($_FILES['uploaded_file']['size']);
         $image_path = $dbLink->real_escape_string($target_path);
	 $gallery_type = $dbLink->real_escape_string($_POST['gallery_type']); 

//query to insert the data i had gathered into the database
$query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`)
             VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}')";

		 //executes the query
		 	$dbLink->query($query);
	} 
}
  else {
     		echo 'Error! A file was not sent!';
		   }
}
  
  else {
[color=red]  echo '$_files['error'];[/color]
  }
  
// Echo a link back to the main page
echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
?>

Link to comment
Share on other sites

okay cool. ill give that code a try.

 

yer that is the main problem im having with my code i need to tidy it up. once ive done the validation on what needs to get validated is it possible to post all the code onto this forum and ask someone to have a look and ask what they would change and how to make it more coder friendly? or is that not a done thing?

 

thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.