Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Image upload proble with php and mysql

Posted on 2008-11-13
15
Medium Priority
?
501 Views
Last Modified: 2013-12-13
I am having problems uploading large files in my app, small files upload but large files do not upload.  I have changed php.ini to accept large files but still experiencig problems.  Please have a look at my code and hope you can help solve my problem.

Thanks experts.
0
Comment
Question by:kasonde
  • 8
  • 7
15 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22957670
can you tell me what you had changed in php.in?


0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22957673
did you try?


upload_max_filesize = 15M
post_max_size = 20M
 
also try increasing memory_limit a bit, 
make sure no or not too low MAX_UPLOAD_LIMIT in html page

Open in new window

0
 

Author Comment

by:kasonde
ID: 22958470

Hi,

I got it to work locally, changed the size to 10M in php.ini, though now when I try and do it on the site live...i get the following error message:

FastCGI Error
The FastCGI Handler was unable to process the request.
--------------------------------------------------------------------------------

Error Details:

The FastCGI process exceeded configured request timeout
Error Number: 995 (0x800703e3).
Error Description: The I/O operation has been aborted because of either a thread exit or an application request.
HTTP Error 500 - Server Error.
Internet Information Services (IIS)



I guess its cause im on shared hosting and the server wont accept files larger than 2M which is default..how do I resize image before the file gets uploaded?  Could you please add the code to my snippet below if that ok? Thanks for responses
<?php
include("dbconnect.php");
session_start();
// define a constant for the maximum upload size of images that will be updated for students
define ('MAX_FILE_SIZE', 10102000);
 
if (array_key_exists('upload', $_POST)) {
  // This defines constants for the upload directory, simplifying and shortening the code
  define('UPLOAD_DIR', './images/');
  // This line replaces any spaces within the filename with underscores, this is essential when sending work to a server, as well as assign the string to a simple variable for use elsewhere in the page
  $file = str_replace(' ', '_', $_FILES['image']['name']);
  // This converts the MAX size of file to kilobytes, which will simplify the understanding of how big a file is
  $max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
  // This code creates an array of  MIME types that will be permitted on the Adult Education Site as images uploaded
  $allowed = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
  // We assume files are unacceptable
  $sizeOK = false;
  $imgtypeOK = false;
  
  // check that the file is within the range we specified at the top of the page
  if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
    $sizeOK = true;
	}
 
  // Checks if the image file is of the $allowed types we specified in the array above
  foreach ($allowed as $imgtype) {
    if ($imgtype == $_FILES['image']['type']) {
      $imgtypeOK = true;
	  break;
	  }
	
	}
  //This switch case is for the different error meassages we can get using $_FILES ARRAY for uploading images
  if ($sizeOK && $imgtypeOK) {
    switch($_FILES['image']['error']) {
	  case 0:
		
        // This code ensure that the same file is not uploaded
		if (!file_exists(UPLOAD_DIR.'/'.$file)) {
		  // move the file to the upload folder and rename it
		  $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.'/'.$file);
		  
		  }
		else {
		  // get the date and time
		  ini_set('date.timezone', 'Europe/London');
		  $now = date('Y-m-d-His');
		  $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.'/'.$now.$file);
		  
		  }
		if ($success) {
			$imgstore = "$file";
			$propid = $_SESSION['newpropid']; 
			$imgsql = "UPDATE propertydetails SET pimg='$imgstore' WHERE propertysectionid = 1 AND linkid = '".$_SESSION['newpropid']."'";
		  	$sql=mysql_query($imgsql);
		  if(!$sql) {
		  	echo "Failed query";
		  }
		  $result = "$file has been uploaded successfully!!";
		  echo "You have successfully uploaded image..click close button to go back";
		  header("Location: addpropertydetails2.php?id=$propid");
	      }
		else {
		  $result = "Error uploading $file, Try again";
		  include("addpropertydetails.php");
		  }
	  break;
	  case 3:
		$result = "Error uploading $file, Try again";
		include("addpropertydetails.php");
	  default:
        $result = 'SYSTEM ERROR performing upload of $file.';
		include("addpropertydetails.php");
	  	}
    }
  	elseif ($_FILES['image']['error'] == 4) {
    $result = 'You have not selected a file';
	include("addpropertydetails.php");
	}
  	else {
    $result = "$file cannot be uploaded, Maximum size: $max. Acceptable file types: gif, jpg, png";
	include("addpropertydetails.php");
	}
  }
?>
 
my html page
 
<?php
include("dbconnect.php");
//Start session and access
session_start();
if ($_SESSION['authoredUser'] != 1) {
	//If flag is absent then the user does not have view privileges and error message gets printed
	echo "You are not authorized to view this page!";
	exit();
	}
	else {
	// Now give the success message.
	// $_SESSION['username'] should print out your username.
		echo "Success! You are now logged in " . $_SESSION['username']; 
}
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
	<h1>ADD IMAGE FOR SECTION 1:</h1>
	<form action="addpropimg1.php" method="post" enctype="multipart/form-data" name="uploadimage1" id="uploadimage1">
                    <p>
                    <label for="image">Add image for Section 1:</label>
                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
                    <input type="file" name="image" id="image" />
                    </p>
                    <p>
                    <input type="submit" name="upload" id="upload" value="Upload" title="Click here to find an image to update onto your home page" />
                    </p>
                 </form>
</body>
</html>

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22958486
I guess its cause im on shared hosting and the server wont accept fileslarger than 2M which is default..

>> Yes, you may be correct, you can ask them to increase it

how do I resize image before the file gets uploaded?  

>> resize means, want to reduce the width + height of image... OR file size to be reduced?

0
 

Author Comment

by:kasonde
ID: 22958628
Reduce the file size..I ll try ask m host, but can I reduce the file size on upload? then after im guessing it would also make sense to reduce the width and height. Thanks for quick response.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22958657
>> but can I reduce the file size on upload?

i don't think you can reduce the file size on the fly... it may not be possible also... find a mechanism to upload larger file
0
 

Author Comment

by:kasonde
ID: 22958752
ok..sothe only soluton is with the hosting provider? is they any solution that exists to handle large files that get uploaded, pictures from digi camera are large, e.g. 3.5mb, I need to reduce the size somehow on upload, cause i keeps timing out..If you have any ideas let me know.  Thanks
0
 

Author Comment

by:kasonde
ID: 22959260
Hi,

How do I increase memory limit in php..i think it could be that?
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22961095
you may also try with this,

<?php
ini_set ( 'upload_max_filesize', '20M');
ini_set('max_input_time', -1);
 
 
?>

Open in new window

0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22961101
you check that,


check the size in script
$data = ini_get( 'upload_max_filesize' );
echo $data;

Open in new window

0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 22961115
it can be done using .htaccess file method also,
0
 

Author Comment

by:kasonde
ID: 22966661
Hi,

Tried above solution n got the following error..

FastCGI Error
The FastCGI Handler was unable to process the request.
--------------------------------------------------------------------------------

Error Details:

The FastCGI process exceeded configured request timeout
Error Number: 995 (0x800703e3).
Error Description: The I/O operation has been aborted because of either a thread exit or an application request.
HTTP Error 500 - Server Error.
Internet Information Services (IIS)

same error message seems to be timing out...
please look at my code snippet, contacted host but where not much help..


<?php
include("dbconnect.php");
session_start();
ini_set ( 'upload_max_filesize', '20M');
ini_set('max_input_time', -1);
// define a constant for the maximum upload size of images that will be updated for students
define ('MAX_FILE_SIZE', 10102000);
 
if (array_key_exists('upload', $_POST)) {
  // This defines constants for the upload directory, simplifying and shortening the code
  define('UPLOAD_DIR', './images/');
  // This line replaces any spaces within the filename with underscores, this is essential when sending work to a server, as well as assign the string to a simple variable for use elsewhere in the page
  $file = str_replace(' ', '_', $_FILES['image']['name']);
  // This converts the MAX size of file to kilobytes, which will simplify the understanding of how big a file is
  $max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
  // This code creates an array of  MIME types that will be permitted on the Adult Education Site as images uploaded
  $allowed = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
  // We assume files are unacceptable
  $sizeOK = false;
  $imgtypeOK = false;
  
  // check that the file is within the range we specified at the top of the page
  if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
    $sizeOK = true;
	}
 
  // Checks if the image file is of the $allowed types we specified in the array above
  foreach ($allowed as $imgtype) {
    if ($imgtype == $_FILES['image']['type']) {
      $imgtypeOK = true;
	  break;
	  }
	
	}
  //This switch case is for the different error meassages we can get using $_FILES ARRAY for uploading images
  if ($sizeOK && $imgtypeOK) {
    switch($_FILES['image']['error']) {
	  case 0:
		
        // This code ensure that the same file is not uploaded
		if (!file_exists(UPLOAD_DIR.'/'.$file)) {
		  // move the file to the upload folder and rename it
		  $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.'/'.$file);
		  
		  }
		else {
		  // get the date and time
		  ini_set('date.timezone', 'Europe/London');
		  $now = date('Y-m-d-His');
		  $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.'/'.$now.$file);
		  
		  }
		if ($success) {
			$imgstore = "$file";
			$propid = $_SESSION['newpropid']; 
			$imgsql = "UPDATE propertydetails SET pimg='$imgstore' WHERE propertysectionid = 1 AND linkid = '".$_SESSION['newpropid']."'";
		  	$sql=mysql_query($imgsql);
		  if(!$sql) {
		  	echo "Failed query";
		  }
		  $result = "$file has been uploaded successfully!!";
		  echo "You have successfully uploaded image..click close button to go back";
		  header("Location: addpropertydetails2.php?id=$propid");
	      }
		else {
		  $result = "Error uploading $file, Try again";
		  include("addpropertydetails.php");
		  }
	  break;
	  case 3:
		$result = "Error uploading $file, Try again";
		include("addpropertydetails.php");
	  default:
        $result = 'SYSTEM ERROR performing upload of $file.';
		include("addpropertydetails.php");
	  	}
    }
  	elseif ($_FILES['image']['error'] == 4) {
    $result = 'You have not selected a file';
	include("addpropertydetails.php");
	}
  	else {
    $result = "$file cannot be uploaded, Maximum size: $max. Acceptable file types: gif, jpg, png";
	include("addpropertydetails.php");
	}
  }
?>

Open in new window

0
 

Author Comment

by:kasonde
ID: 22966670
how do I do it using htaccess method? it keeps timing out when i upload, dont know why...thanks for your help, really appreciated.
0
 
LVL 36

Accepted Solution

by:
Loganathan Natarajan earned 1000 total points
ID: 22973493
you  have to put these values in .htaccess file and try to execute on it.
ref. http://roshanbh.com.np/2008/01/uploading-larger-files-in-php.html
0
 

Author Comment

by:kasonde
ID: 22998219
THANK YOU!!! Much appreciated..problem solved as usual on expert exchange..thank you for your time..!
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question