Jump to content

Image uploader


Lyleyboy

Recommended Posts

Hi all,

 

I have this code that uploads a photo to the site. The issue seems to be that it wont upload an image that is more than about a megabyte.

There is a bit in there to say how big and I have set it to 1000000KB which (Unless I'm going daft) is 100MB or 1GB so that should be ok.

 

Can some one take a look please and help me out before I quit php and go off and be a road sweeper.

 

Code that does the upload

//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","1000000"); 

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
//and it will be changed to 1 if an errro occures.  
//If the error occures the file will not be uploaded.
//checks if the form has been submitted
if(isset($_POST['Submit'])) 
{
	//reads the name of the file the user submitted for uploading
	$image=$_FILES['image']['name'];
	//if it is not empty
	if ($image) 
	{
	//get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['image']['name']);
	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
		$extension = strtolower($extension);
	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
		{
	//print error message
			echo 'Unknown extension!';
			$errors="1";
		}
		else
		{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*5024)
{
echo 'You have exceeded the size limit!';
$errors="1";
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="upload/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) 
{
echo 'Copy unsuccessfull!';
$errors="1";
}}}}

 

Full code

<?php

// Site area setup
session_start();
$_SESSION['sitearea'] = "Galleries";

//Setup errors to be 0
$errors = "0";

//Setup instructions path
  $inst_path = "../includes/instructions/inst_galleries_upload.php";
    
    //Turn off warnings
    error_reporting(E_ALL ^ E_NOTICE); 
    
    //Include the header bar
    include('../includes/main_head.php');
  
    //Now include the nav bar
    include('../includes/main_nav.php');
  
    //Include the conn
    include('../includes/inc.conn.php');
    
    //Check my users details
    $username = $_SESSION['username'];
    
    $query = "SELECT * FROM users WHERE username = '$username'"; 
	$result = mysql_query($query) or die(mysql_error());
	    while($row = mysql_fetch_array($result)){
		//Set up my vars
		$userover18 = $row['over18'];
	    }
      $gallery_id = $_POST['gallery'];
      $query = "SELECT * FROM galls_galleries WHERE gall_gall_id = '$gallery_id'"; 
	$result = mysql_query($query) or die(mysql_error());
	    while($row = mysql_fetch_array($result)){
		//Set up my vars
		$over18 = $row['over18'];
		$gallery_name = $row['gallery'];
	    }
  

//*****************Page content*********************
if ($inst_path > ""){
  ?>
    <div class="instructions">
      <?php
        include($inst_path);
      ?>
    </div>
      
    <div class="log_nav" onmouseover="this.className='log_nav_on'" onmouseout="this.className='log_nav'" style="float:right;" id="inst">
      Help
    </div>
  <?php
}
?>
  <h1><img src="../images/nav_gallery.png" alt="Galleries Icon" width="50px"/> Upload to our photo galleries</h1>




<p>
Fill out all the details below to upload the picture. Don't forget to tag the images with keywords.
</p>

<p>
    
<?php
//Do some nice little validation of the form entries
$sub_gallery = $_POST['gallery'];
$sub_title = $_POST['title'];
$sub_tags = $_POST['tags'];
$sub_image = $_POST['image'];

if (isset($_POST['Submit'])){
    if ($sub_gallery < "1" || $sub_title < "1" || $sub_tags < "1" || isset($sub_image)){
echo "<span class='errors'>Whoops, the form wasn't quite filled out properly<br/><br/>";
$errors="1";//Sets the errors to 1 in any case
    if($sub_gallery < "1"){
	echo " - You didn't enter a gallery! Where we goona put the piccy if you don't tell us?<br/>";
	$errors="1";
    }
    if($sub_title < "1"){
	echo " - You didn't enter a title. What are we gonna call it then?<br/>";
	$errors="1";
    }
    if($sub_tags < "1"){
	echo " - You didn't enter any tags. Please enter some so we can find it later.<br/>";
	$errors="1";
    }
    if(isset($sub_image)){
	echo " - You didn't select a file. Give me something to work with here.<br/><br/></span>";
	$errors="1";
    }
    }
}


//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","1000000"); 

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
//and it will be changed to 1 if an errro occures.  
//If the error occures the file will not be uploaded.
//checks if the form has been submitted
if(isset($_POST['Submit'])) 
{
	//reads the name of the file the user submitted for uploading
	$image=$_FILES['image']['name'];
	//if it is not empty
	if ($image) 
	{
	//get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['image']['name']);
	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
		$extension = strtolower($extension);
	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
		{
	//print error message
			echo 'Unknown extension!';
			$errors="1";
		}
		else
		{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*5024)
{
echo 'You have exceeded the size limit!';
$errors="1";
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="upload/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) 
{
echo 'Copy unsuccessfull!';
$errors="1";
}}}}



//If no errors registred, print the success message
if(isset($_POST['Submit']) && $errors=="0") 
{
	echo "<br/><b>File Uploaded Successfully! Have another go!!<br/><br/></b>";


//Lets resize the image (Fingers crossed)
//Validate it
if($sub_image > ""){
include('SimpleImage.php');
  $image = new SimpleImage();
  $image->load($newname);
  $image->resizeToWidth(500);
  $image->save($newname);
}
        
        //Update the table
        //Verify vars
        $title = $_POST['title'];
$tags = $_POST['tags'];
$path = $image_name;

//Check if the night has been changed
if (isset($new_night)){
	$night = $_POST['new_night'];
}
        
        //Kill injections
        // night title tags path active network
$gallery_id = mysql_real_escape_string($gallery_id);
$gallery_name = mysql_real_escape_string($gallery_name);
        $title = mysql_real_escape_string($title);
$tags = mysql_real_escape_string($tags);
$path = mysql_real_escape_string($path);

//Over18 galleries do not need to be moderated neither do Administrators
if ($over18 == 'on' || $_Session['admin'] == 'on' || $_session['s_admin'] == 'on'){
  $active = "on";
  $over18 = "on";
} else {
  $active = "off";
  $over18 = "off";
}
        
//Check for swearings
include('../includes/functions/swear_filter.php');
$title = swear_filter($title);
$tags = swear_filter($tags);


        //tags year
$year = date('Y');
$tags = $year . " " . $tags;
        mysql_query("INSERT INTO galls (gallery_id, gallery, title, tags, path, uploaded_by, gall_over18, active) VALUES('$gallery_id', '$gallery_name', '$title', '$tags', '$path' , '$username', '$over18', '$active') ") or die(mysql_error());  
        
} else {
    echo "<span class='errors'>Nothing was uploaded, please fix the errors to continue. Please reselect the gallery!</span>";
}

?>
      <form name="newad" method="post" enctype="multipart/form-data" action="">
Which gallery would you like to upload the photo to?

<select name="gallery" class="nav_form">
	<option value="">-- Choose --</option> 
<?php
//am I over 18?
if ($userover18 == 'on'){
    $qry = "SELECT * FROM galls_galleries"; 
} else {
    $qry = "SELECT * FROM galls_galleries WHERE over18<>'on'"; 
}

$query = $qry; 
	$result = mysql_query($query) or die(mysql_error());
	    while($row = mysql_fetch_array($result)){
		echo "<option value='" . $row['gall_gall_id'] .  "'>" . $row['gallery'] . "</option>";
	    }
?>
</select><br/><a href="requestgallery.php">Or click here to request a new gallery</a><br/>



    
    Choose the image to upload<br/>
    <input type="file" name="image" class="buttons" onmouseover="this.className='buttons_on'" onmouseout="this.className='buttons'"/><br/><br/><br/>
    What is the title of the image<br/>
    <input type="text" name="title" size="60" class="nav_form" value="<?php echo $sub_title; ?>"/><br/><br/>
    Enter some tags so that folks can search for this photo later like "Rafting bbq dave camp tent" (Doesn't need the " marks.)<br/>
    <input type="text" name="tags" size="60" class="nav_form" value="<?php echo $sub_tags; ?>"/><br/><br/>
    <input name="Submit" type="submit" value="Upload image" class="buttons" onmouseover="this.className='buttons_on'" onmouseout="this.className='buttons'"/>
    </form>
    
<?php
//*****************Page content*********************

  //Inlcude the footer bar
  include('../includes/main_footer.php');

Link to comment
Share on other sites

Sometimes this can also be done by placeing a local php.ini file

But this depends on the host as Nutty said.

 

you can increase the upload file size with htaccess here's a tutorial on that: http://www.phphelptutorials.com/ht-access/override-file-upload-sizes-an-htaccess-file

 

your server may be setup to restrict upload sizes, if thats the case you'll need to contact your host.

Link to comment
Share on other sites

oh yeah

you might want to use

http://us2.php.net/manual/en/function.move-uploaded-file.php

rather than copy()

It is more secure since it checks that the file was uploaded via POST before doing anything

 

and check for the $_FILE error code

 

I just used this function below a couple days ago..

 

http://us2.php.net/manual/en/features.file-upload.errors.php

<?php 

function file_upload_error_message($error_code) {
    switch ($error_code) { 
        case UPLOAD_ERR_INI_SIZE: 
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; 
        case UPLOAD_ERR_FORM_SIZE: 
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; 
        case UPLOAD_ERR_PARTIAL: 
            return 'The uploaded file was only partially uploaded'; 
        case UPLOAD_ERR_NO_FILE: 
            return 'No file was uploaded'; 
        case UPLOAD_ERR_NO_TMP_DIR: 
            return 'Missing a temporary folder'; 
        case UPLOAD_ERR_CANT_WRITE: 
            return 'Failed to write file to disk'; 
        case UPLOAD_ERR_EXTENSION: 
            return 'File upload stopped by extension'; 
        default: 
            return 'Unknown upload error'; 
    } 
} 

// Example
if ($_FILES['file']['error'] === UPLOAD_ERR_OK)
    // upload ok
else
    $error_message = file_upload_error_message($_FILES['file']['error']); 

?>

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.