Jump to content

Image Upload Validation Not Working


happypete

Recommended Posts

Hi,

 

I have the following code for making sure an image upload is valid. The script should technically stop non image file uploads, produce an error if a file size is '0' or more than 2mb etc.

 

I can't work out why it does the following:

  1. If I upload a really big image (5mb) it give an error of invalid filetype
     
  2. If I upload a .jpg file of size 0 bytes it does nothing and returns the user to the index.php page

<?php
// check user logged in
include("assets/member.inc.php");
$member->LoggedIn();

// Check if coming from a POST command and Cancel
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Cancel / Return to site')
{
// cancel & return to admin page
header('Location: index.php?success=5');
exit;
}
// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload')
{
// File Size Check
@session_start();

$file_size = filesize($_FILES['image']['name']);

$blacklist = array(".php", ".phtml", ".php3", ".php4", ".js", ".shtml", ".pl" ,".py", ".php5", ".htm", ".html", ".zip", ".exe", ".htaccess");

//Remove blacklisted files
foreach ($blacklist as $file)
{
if(preg_match("/$file\$/i", $_FILES['image']['name'])) {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats1';
header('Location: index-image.php');
exit;
}}

//Check for valid image type
$allowedexts = array('gif','jpeg','jpg','png');
$extension = end(explode('.', strtolower($_FILES['image']['name'])));
if($_FILES['image']['type']=='image/jpeg'||$_FILES['image']['type']=='image/gif'||$_FILES['image']['type']=='image/png'
&& in_array($extension,$allowedexts)){ }
else {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats2';
header('Location: index-image.php');
exit;
}

// Check image size not 0
if($file_size === 0) {
$_SESSION['msg'] = 'That was an empty file!';
header('Location: index-image.php');
exit;
}

// Check image size not too big
else if($file_size >= (2480000)) {
$_SESSION['msg'] = 'Image size is to big. Max upload 2MB';
header('Location: index-image.php');
exit;
}

// Check not double extension like bad.php.jpg
else if(substr_count($_FILES['image']['name'], '.')>1){ //check double file type
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats3';
header('Location: index-image.php');
exit;
}

$newPath = '' . basename($_FILES['image']['name']);
(move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

// *** Include the class
include("inc/resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize($newPath);
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(475, 600, 'landscape');
// *** 3) Save image + define quality
$resizeObj -> saveImage('/home/user/public_html/'.$siteid.'/images/vacation_rentals.jpg', 85);

// Remove file from temp Directory
unlink($newPath) ;

// once updated return to admin page
header('Location: index.php?success=3');
exit;
}
else
{
// If nothing happend send back to admin page
header('Location: index.php?success=5');
exit;
}
?>

Edited by happypete
Link to comment
Share on other sites

OK added

($_FILES['image']['error'] == UPLOAD_ERR_OK)

 

here:

// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK))
{

 

 

and made if show an error if no file uploaded:

else
{
$_SESSION['msg'] = 'NO IMAGE UPLOADED';
header('Location: index-image.php');
exit;
}

 

Thanks, I'm sure it make the form better, but still have the same problems as before...

Edited by happypete
Link to comment
Share on other sites

OK new code. Error reporting added:

 

when I click the 'Cancel / Return to site' button I get the following errors (before it returned me to the index page):

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 12

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 21

 

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/accounts/index-imageupdate.php:12) in /home/user/public_html/accounts/index-imageupdate.php on line 100

 

when I upload an image with a size of '0' I get the following errors:

 

Warning: filesize() [function.filesize]: stat failed for empty.jpg in /home/user/public_html/accounts/index-imageupdate.php on line 27

 

Warning: imagesx() expects parameter 1 to be resource, boolean given in /home/user/public_html/accounts/inc/resize-class.php on line 29

 

Warning: imagesy() expects parameter 1 to be resource, boolean given in /home/user/public_html/accounts/inc/resize-class.php on line 30

 

Warning: Division by zero in /home/user/public_html/accounts/inc/resize-class.php on line 110

 

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/user/public_html/accounts/inc/resize-class.php on line 63

 

Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in /home/user/public_html/accounts/inc/resize-class.php on line 64

 

Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /home/user/public_html/accounts/inc/resize-class.php on line 182

 

Warning: imagedestroy() expects parameter 1 to be resource, boolean given in /home/user/public_html/accounts/inc/resize-class.php on line 204

 

Warning: Cannot modify header information - headers already sent by (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:27) in /home/user/public_html/accounts/index-imageupdate.php on line 94

 

When I upload a valid image, I get the following errors (before it just uploaded the image):

 

Warning: filesize() [function.filesize]: stat failed for apartment-living2b.jpg in /home/user/public_html/accounts/index-imageupdate.php on line 27

 

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/accounts/index-imageupdate.php:27) in /home/user/public_html/accounts/index-imageupdate.php on line 94

 

index-image.php (the form)

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
// check user logged in
include("assets/member.inc.php");
$member->LoggedIn();
$pagetitle = 'Upload Image';
$random = microtime();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include('inc/head.php'); ?>
</head>
<body>
<div class="content">
<h1>Upload a new image to the homepage</h1>
	 <?php if(!empty($_SESSION['msg'])) { echo '<font color="red">'.$_SESSION['msg'].'</font>'; unset($_SESSION['msg']); } ?>
 <form method="post" action="index-imageupdate.php" enctype="multipart/form-data">
	 <label>
	 Select Image <br />
	 <input type="file" name="image" />
	 <p>Files must be less than 2 MB in size (if you need to resize an image: <a href="www.picresize.com/" target="_blank">PicResize</a>).<br />
	 Allowed file types: png gif jpg jpeg.</p>
	 <p>The image will be resized to 475 pixels wide (it won't be cropped or distorted).
	 <br />
	 </label>
	 </p>
	 <div class="clear"></div>
	 <input id="button" class="button" type="submit" name="submit" value="Upload" />
	 <input id="button" class="buttoncancel" type="submit" name="cancel" value="Cancel / Return to site" />
	 <div id="spinner" class="spinner"><img id="img-spinner" src="../media/spinner.gif" alt="Loading"/></div>
 </form>
 <p> </p>
 <p>Current Image</p>
	 <img src="http://<?php echo $siteid; ?>.sitename.com/images/vacation_rentals.jpg?<?php echo $random; ?>">

</div><!--content-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
 <script>window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')</script>
<script type="text/javascript">
$(document).ready(function(){$('#button').click(function(){$('#spinner').show()})});
</script>
</body>
</html>

 

 

 

index-imageupdate.php (upload script)

<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

// check user logged in
include("assets/member.inc.php");
$member->LoggedIn();

// Check if coming from a POST command and Cancel
if($_SERVER['REQUEST_METHOD']=='POST')
&& $_POST['submit']=='Cancel / Return to site')
{
// cancel & return to admin page
header('Location: index.php?success=5');
exit;
}
// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK))
{
// File Size Check
@session_start();

$file_size = filesize($_FILES['image']['name']);
if ($file_size === 0) {
$_SESSION['msg'] = 'No file uploaded';
header('Location: index-image.php');
exit;
}

$blacklist = array(".php", ".phtml", ".php3", ".php4", ".js", ".shtml", ".pl" ,".py", ".php5", ".htm", ".html", ".zip", ".exe", ".htaccess");

//Remove blacklisted files
foreach ($blacklist as $file)
{
if(preg_match("/$file\$/i", $_FILES['image']['name'])) {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats1';
header('Location: index-image.php');
exit;
}}

//Check for valid image type
$allowedexts = array('gif','jpeg','jpg','png');
$extension = end(explode('.', strtolower($_FILES['image']['name'])));
if($_FILES['image']['type']=='image/jpeg'||$_FILES['image']['type']=='image/gif'||$_FILES['image']['type']=='image/png'
&& in_array($extension,$allowedexts)){ }
else {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats2';
header('Location: index-image.php');
exit;
}

// Check image size not 0
if($file_size === 0) {
$_SESSION['msg'] = 'That was an empty file!';
header('Location: index-image.php');
exit;
}

// Check image size not too big
else if($file_size >= (2480000)) {
$_SESSION['msg'] = 'Image size is to big. Max upload 2MB';
header('Location: index-image.php');
exit;
}

// Check not double extension like bad.php.jpg
else if(substr_count($_FILES['image']['name'], '.')>1){ //check double file type
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats3';
header('Location: index-image.php');
exit;
}

$newPath = '' . basename($_FILES['image']['name']);
(move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

// *** Include the class
include("inc/resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize($newPath);
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(475, 600, 'landscape');
// *** 3) Save image + define quality
$resizeObj -> saveImage('/home/user/public_html/'.$siteid.'/images/vacation_rentals.jpg', 85);

// Remove file from temp Directory
unlink($newPath) ;

// once updated return to admin page
header('Location: index.php?success=3');
exit;
}
else
{
$_SESSION['msg'] = 'NO IMAGE UPLOADED';
header('Location: index-image.php');
exit;
}
?>

 

resize-class.php

<?php
# ========================================================================#
#
# Author: Jarrod Oberto
# Version: 1.0
# Date:	 17-Jan-10
# Purpose: Resizes and saves image
# Requires : Requires PHP5, GD library.
# Usage Example:
#					 include("file:///C|/xampplite/htdocs/inc/classes/resize_class.php");
#					 $resizeObj = new resize('images/cars/large/input.jpg');
#					 $resizeObj -> resizeImage(150, 100, 0);
#					 $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
#
#
# ========================================================================#
Class resize
{
// *** Class variables
private $image;
 private $width;
 private $height;
private $imageResized;
function __construct($fileName)
{
// *** Open up the file
$this->image = $this->openImage($fileName);
 // *** Get width and height
 $this->width = imagesx($this->image);
 $this->height = imagesy($this->image);
}
## --------------------------------------------------------
private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));
switch($extension)
{
 case '.jpg':
 case '.jpeg':
 $img = @imagecreatefromjpeg($file);
 break;
 case '.gif':
 $img = @imagecreatefromgif($file);
 break;
 case '.png':
 $img = @imagecreatefrompng($file);
 break;
 default:
 $img = false;
 break;
}
return $img;
}
## --------------------------------------------------------
public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $option);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($option == 'crop') {
 $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}
## --------------------------------------------------------

private function getDimensions($newWidth, $newHeight, $option)
{
 switch ($option)
{
 case 'exact':
 $optimalWidth = $newWidth;
 $optimalHeight= $newHeight;
 break;
 case 'portrait':
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
 break;
 case 'landscape':
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
 break;
 case 'auto':
 $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
 $optimalWidth = $optionArray['optimalWidth'];
 $optimalHeight = $optionArray['optimalHeight'];
 break;
 case 'crop':
 $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
 $optimalWidth = $optionArray['optimalWidth'];
 $optimalHeight = $optionArray['optimalHeight'];
 break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function getSizeByFixedHeight($newHeight)
{
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}
private function getSizeByFixedWidth($newWidth)
{
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}
private function getSizeByAuto($newWidth, $newHeight)
{
if ($this->height < $this->width)
// *** Image to be resized is wider (landscape)
{
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
}
elseif ($this->height > $this->width)
// *** Image to be resized is taller (portrait)
{
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
}
else
// *** Image to be resizerd is a square
{
 if ($newHeight < $newWidth) {
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
 } else if ($newHeight > $newWidth) {
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
 } else {
 // *** Sqaure being resized to a square
 $optimalWidth = $newWidth;
 $optimalHeight= $newHeight;
 }
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function getOptimalCrop($newWidth, $newHeight)
{
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
if ($heightRatio < $widthRatio) {
 $optimalRatio = $heightRatio;
} else {
 $optimalRatio = $widthRatio;
}
$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
// *** Find center - this will be used for the crop
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
$crop = $this->imageResized;
//imagedestroy($this->imageResized);
// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
}
## --------------------------------------------------------
public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
	 $extension = strrchr($savePath, '.');
	 $extension = strtolower($extension);
switch($extension)
{
 case '.jpg':
 case '.jpeg':
 if (imagetypes() & IMG_JPG) {
 imagejpeg($this->imageResized, $savePath, $imageQuality);
 }
 break;
 case '.gif':
 if (imagetypes() & IMG_GIF) {
 imagegif($this->imageResized, $savePath);
 }
 break;
 case '.png':
 // *** Scale quality from 0-100 to 0-9
 $scaleQuality = round(($imageQuality/100) * 9);
 // *** Invert quality setting as 0 is best, not 9
 $invertScaleQuality = 9 - $scaleQuality;
 if (imagetypes() & IMG_PNG) {
 imagepng($this->imageResized, $savePath, $invertScaleQuality);
 }
 break;
 // ... etc
 default:
 // *** No extension - No save.
 break;
}
imagedestroy($this->imageResized);
}
## --------------------------------------------------------
}
?>

Edited by happypete
Link to comment
Share on other sites

// File Size Check
@session_start();

Take out the error suppression ("@") here, and anywhere else that you have it. It does not fix errors, it just hides them.

 

Add error reporting at the top of all scripts. For development:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Then fix any errors that you get --- IMO, WARNINGS and NOTICES are errors.

 

$file_size = filesize($_FILES['image']['name']);

$_FILES['image']['name'] returns "The original name of the file on the client machine." not a path on the server that you can reference. You can get the filesize from $_FILES['image']['size']. (see http://php.net/manual/en/features.file-upload.post-method.php)

 

Try that, and report back any problems. If you have trouble with new error messages, post the entire error message.

Link to comment
Share on other sites

instead of doing

 

$this->$image = imagesy($this->$image);

 

can you put it in a function like so??? (taken from simon jarvis simple image class)

 

public function getWidth(){
return imagesx ($this->$image);
}
public function getHeight(){
return imagesy ($this->$image);
}
[color=#000000][b]function[/b][/color] resizeToHeight[color=#009900]([/color][color=#000088]$height[/color][color=#009900])[/color] [color=#009900]{[/color]

     [color=#000088]$ratio[/color] [color=#339933]=[/color] [color=#000088]$height[/color] [color=#339933]/[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getHeight[/color][color=#009900]([/color][color=#009900])[/color][color=#339933];[/color]
     [color=#000088]$width[/color] [color=#339933]=[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getWidth[/color][color=#009900]([/color][color=#009900])[/color] [color=#339933]*[/color] [color=#000088]$ratio[/color][color=#339933];[/color]
     [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]resize[/color][color=#009900]([/color][color=#000088]$width[/color][color=#339933],[/color][color=#000088]$height[/color][color=#009900])[/color][color=#339933];[/color]
  [color=#009900]}[/color]

  [color=#000000][b]function[/b][/color] resizeToWidth[color=#009900]([/color][color=#000088]$width[/color][color=#009900])[/color] [color=#009900]{[/color]
     [color=#000088]$ratio[/color] [color=#339933]=[/color] [color=#000088]$width[/color] [color=#339933]/[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getWidth[/color][color=#009900]([/color][color=#009900])[/color][color=#339933];[/color]
     [color=#000088]$height[/color] [color=#339933]=[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getheight[/color][color=#009900]([/color][color=#009900])[/color] [color=#339933]*[/color] [color=#000088]$ratio[/color][color=#339933];[/color]
     [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]resize[/color][color=#009900]([/color][color=#000088]$width[/color][color=#339933],[/color][color=#000088]$height[/color][color=#009900])[/color][color=#339933];[/color]
  [color=#009900]}[/color]

  [color=#000000][b]function[/b][/color] scale[color=#009900]([/color][color=#000088]$scale[/color][color=#009900])[/color] [color=#009900]{[/color]
     [color=#000088]$width[/color] [color=#339933]=[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getWidth[/color][color=#009900]([/color][color=#009900])[/color] [color=#339933]*[/color] [color=#000088]$scale[/color][color=#339933]/[/color][color=#cc66cc]100[/color][color=#339933];[/color]
     [color=#000088]$height[/color] [color=#339933]=[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getheight[/color][color=#009900]([/color][color=#009900])[/color] [color=#339933]*[/color] [color=#000088]$scale[/color][color=#339933]/[/color][color=#cc66cc]100[/color][color=#339933];[/color]
     [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]resize[/color][color=#009900]([/color][color=#000088]$width[/color][color=#339933],[/color][color=#000088]$height[/color][color=#009900])[/color][color=#339933];[/color]
  [color=#009900]}[/color]

  [color=#000000][b]function[/b][/color] resize[color=#009900]([/color][color=#000088]$width[/color][color=#339933],[/color][color=#000088]$height[/color][color=#009900])[/color] [color=#009900]{[/color]
     [color=#000088]$new_image[/color] [color=#339933]=[/color] [color=#990000]imagecreatetruecolor[/color][color=#009900]([/color][color=#000088]$width[/color][color=#339933],[/color] [color=#000088]$height[/color][color=#009900])[/color][color=#339933];[/color]
     [color=#990000]imagecopyresampled[/color][color=#009900]([/color][color=#000088]$new_image[/color][color=#339933],[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]image[/color][color=#339933],[/color] [color=#cc66cc]0[/color][color=#339933],[/color] [color=#cc66cc]0[/color][color=#339933],[/color] [color=#cc66cc]0[/color][color=#339933],[/color] [color=#cc66cc]0[/color][color=#339933],[/color] [color=#000088]$width[/color][color=#339933],[/color] [color=#000088]$height[/color][color=#339933],[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getWidth[/color][color=#009900]([/color][color=#009900])[/color][color=#339933],[/color] [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]getHeight[/color][color=#009900]([/color][color=#009900])[/color][color=#009900])[/color][color=#339933];[/color]
     [color=#000088]$this[/color][color=#339933]->[/color][color=#004000]image[/color] [color=#339933]=[/color] [color=#000088]$new_image[/color][color=#339933];[/color]
  [color=#009900]}[/color]      

Edited by darkfreaks
Link to comment
Share on other sites

Thanks.

 

Sorted some bits, but still have trouble with:

 

===============

 

If I upload a 4mb image I get: 'NO IMAGE UPLOADED'

 

Which come from: index-imageupdate.php it would appear it didn't get picked up by the max file size validation, nor did it get uploaded to the upload directory.

else

{

$_SESSION['msg'] = 'NO IMAGE UPLOADED';

header('Location: index-image.php');

exit;

}

 

=============

 

If I click the form button 'Cancel / Return to site':

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 12

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 21

 

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/accounts/index-imageupdate.php:12)

in /home/user/public_html/accounts/index-imageupdate.php on line 91

 

==========================

 

If I upload a 1.5mb image it redirects to: index-imageupload.php and I get a blank page, and image is not uploaded

Link to comment
Share on other sites

Thanks.

 

Sorted some bits, but still have trouble with:

You seem to have posted your code (#7) while I was typing my response [#8]. Have you reviewed my comments and made those changes?

 

If I upload a 4mb image I get: 'NO IMAGE UPLOADED'

 

Which come from: index-imageupdate.php it would appear it didn't get picked up by the max file size validation, nor did it get uploaded to the upload directory.

else

{

$_SESSION['msg'] = 'NO IMAGE UPLOADED';

header('Location: index-image.php');

exit;

}

The else is from this if($_SERVER['REQUEST_METHOD']=='POST'

&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) which means the file did not upload successfully. The php.ini file sets the maximum upload file size. The default is apparently 2MB. If a file is uploaded that is larger than this setting allows, the upload fails, the file is not stored and you get UPLOAD_ERR_INI_SIZE for the error value.

 

If I click the form button 'Cancel / Return to site':

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 12

 

Notice: Undefined index: submit in /home/user/public_html/accounts/index-imageupdate.php on line 21

 

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/accounts/index-imageupdate.php:12)

in /home/user/public_html/accounts/index-imageupdate.php on line 91

The name of your cancel button is "cancel" (in your form). If you click that button, the "submit" index does not exist. You should try using isset() before checking the value:

if($_SERVER['REQUEST_METHOD']=='POST')
&& isset($_POST['cancel'])
&& $_POST['cancel']=='Cancel / Return to site') {

The header error is because you tried to use a header() call, but there had already been output (the error messages). Once you fix the errors, the header problem should go away.

Link to comment
Share on other sites

You seem to have posted your code (#7) while I was typing my response [#8]. Have you reviewed my comments and made those changes?

 

Yes. I took out the @ from ' @session_start();'

I have error_reporting(E_ALL); ini_set('display_errors', 1); at the top of each page

and change to 'size' to get filesize: $_FILES['image']['size']

 

The else is from this if($_SERVER['REQUEST_METHOD']=='POST'

&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) which means the file did not upload successfully. The php.ini file sets the maximum upload file size. The default is apparently 2MB. If a file is uploaded that is larger than this setting allows, the upload fails, the file is not stored and you get UPLOAD_ERR_INI_SIZE for the error value.

 

Just contacted my host and they said the max file upload size was 2GB....

 

 

The name of your cancel button is "cancel" (in your form). If you click that button, the "submit" index does not exist. You should try using isset() before checking the value:

if($_SERVER['REQUEST_METHOD']=='POST')
&& isset($_POST['cancel'])
&& $_POST['cancel']=='Cancel / Return to site') {

The header error is because you tried to use a header() call, but there had already been output (the error messages). Once you fix the errors, the header problem should go away.

I change the script from (I was calling it submit not cancel)

if($_SERVER['REQUEST_METHOD']=='POST'
   && $_POST['submit']=='Cancel / Return to site')

 

to this:

if($_SERVER['REQUEST_METHOD']=='POST')
&& isset($_POST['cancel'])
&& $_POST['cancel']=='Cancel / Return to site') {

 

on pressing 'cancel' it redirects me to index-imageupdate.php and shows a blank screen..

Link to comment
Share on other sites

// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK))
{
   // File Size Check
   session_start();

I just noticed your session_start() is inside the IF test. If the test fails and the ELSE is executed, there is no session for the message you are applying there (in the ELSE). I would move the session_start() out of the IF (just before it).

 

If I am following the thread correctly, all of your outstanding issues leave you with a blank screen.

 

First, check the "View Source" feature of the browser to see if there is any output at all; it may be broken HTML that the browser cannot render.

 

Second, add some debugging statements. I would put the following two lines right at the top (after turning on the errors):

printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_POST, true)));
printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_FILES, true)));

This will show you exactly what is being sent with the form, so you can see the data.

 

Also, use phpinfo() to check the upload_max_filesize and post_max_size values. Both of these have an impact on uploading files.

Link to comment
Share on other sites

// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK))
{
// File Size Check
session_start();

I just noticed your session_start() is inside the IF test. If the test fails and the ELSE is executed, there is no session for the message you are applying there (in the ELSE). I would move the session_start() out of the IF (just before it).

 

I actually took the session_start() out altogether as there was already a session because I was logged in to the admin panel of the script, and got an error that said a session had already started.

 

If I am following the thread correctly, all of your outstanding issues leave you with a blank screen.

 

yes

 

First, check the "View Source" feature of the browser to see if there is any output at all; it may be broken HTML that the browser cannot render.

 

If I view the source code I see nothing.

 

Second, add some debugging statements. I would put the following two lines right at the top (after turning on the errors):

printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_POST, true)));
printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_FILES, true)));

This will show you exactly what is being sent with the form, so you can see the data.

 

I changed the script back to as without it didn't give an output:

if($_SERVER['REQUEST_METHOD']=='POST'
 && $_POST['submit']=='Cancel / Return to site') /// before it was: && $_POST['cancel']=='Cancel / Return to site')

 

pressing the cancel button:

 

Array
(
[cancel] => Cancel / Return to site
)
Array
(
[image] => Array
 (
	 [name] =>
	 [type] =>
	 [tmp_name] =>
	 [error] => 4
	 [size] => 0
 )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17
Notice: Undefined index: submit in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 15
Notice: Undefined index: submit in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 27
Warning: Cannot modify header information - headers already sent by (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 97

 

if I try and upload a large image, then refresh the index-image.php and the image hasn't uploaded to the upload directory - IT ACTUALLY UPLOADED IT TO THE DIRECTORY THAT THE UPLOAD SCRIPT IS IN AND NOT THE UPLOAD DIRECTORY SPECIFIED BY THE SCRIPT..

 

Array
(
[submit] => Upload
)
Array
(
[image] => Array
 (
	 [name] => yey.jpg
	 [type] => image/jpeg
	 [tmp_name] => /tmp/phpk8hooD
	 [error] => 0
	 [size] => 1576292
 )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17

 

 

 

if I try and upload a valid image, the image uploads to the upload directory

Array
(
[submit] => Upload
)
Array
(
[image] => Array
 (
	 [name] => apartment-living2b.jpg
	 [type] => image/jpeg
	 [tmp_name] => /tmp/phpbiy9BS
	 [error] => 0
	 [size] => 77772
 )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17
Warning: Cannot modify header information - headers already sent by (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 91

 

 

 

Also, use phpinfo() to check the upload_max_filesize and post_max_size values. Both of these have an impact on uploading files.

 

upload_max_filesize 2M

post_max_size 64M

 

the updated script:

 

<?php
printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_POST, true)));
printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_FILES, true)));

error_reporting(E_ALL);
ini_set('display_errors', 1);
// check user logged in
include("assets/member.inc.php");
$member->LoggedIn();

// Check if coming from a POST command and Cancel
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Cancel / Return to site') {

//if($_SERVER['REQUEST_METHOD']=='POST')
//&& isset($_POST['cancel'])
//&& $_POST['cancel']=='Cancel / Return to site') {
// cancel & return to admin page
header('Location: index.php?success=5');
exit;
}
// Check if coming from a POST command and
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Upload' && ($_FILES['image']['error'] == UPLOAD_ERR_OK))
{

$file_size = $_FILES['image']['size'];
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".js", ".shtml", ".pl" ,".py", ".php5", ".htm", ".html", ".zip", ".exe", ".htaccess");

//Remove blacklisted files
foreach ($blacklist as $file)
{
if(preg_match("/$file\$/i", $_FILES['image']['name'])) {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats1';
header('Location: index-image.php');
exit;
}}

//Check for valid image type
$allowedexts = array('gif','jpeg','jpg','png');
$extension = end(explode('.', strtolower($_FILES['image']['name'])));
if($_FILES['image']['type']=='image/jpeg'||$_FILES['image']['type']=='image/gif'||$_FILES['image']['type']=='image/png'
&& in_array($extension,$allowedexts)){ }
else {
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats2';
header('Location: index-image.php');
exit;
}

// Check image size not 0
if($file_size === 0) {
$_SESSION['msg'] = 'That was an empty file!';
header('Location: index-image.php');
exit;
}

// Check image size not too big
if($file_size >= (2097152)) { // 2MB
$_SESSION['msg'] = 'Image size is to big. Max upload 2MB';
header('Location: index-image.php');
exit;
}

// Check not double extension like bad.php.jpg
else if(substr_count($_FILES['image']['name'], '.')>1){ //check double file type
$_SESSION['msg'] = 'Invalid image format only JPG, PNG & GIF formats3';
header('Location: index-image.php');
exit;
}

$newPath = '' . basename($_FILES['image']['name']);
(move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

// *** Include the class
include("inc/resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize($newPath);
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(475, 600, 'landscape');
// *** 3) Save image + define quality
$resizeObj -> saveImage('/home/jeremyiv/public_html/'.$siteid.'/images/vacation_rentals.jpg', 85);

// Remove file from temp Directory
unlink($newPath) ;

// once updated return to admin page
header('Location: index.php?success=3');
exit;
}
else
{
$_SESSION['msg'] = 'NO IMAGE UPLOADED';
header('Location: index-image.php');
exit;
}
?>

Link to comment
Share on other sites

I actually took the session_start() out altogether as there was already a session because I was logged in to the admin panel of the script, and got an error that said a session had already started.

Well, you only need one per page request. I suspect the "@" was put on it to "make that error go away" when it said there was already a session.

 

yes

Wow, I really thought I was getting lost

 

If I view the source code I see nothing.

OK. Sometimes you get some output like "<junk", but since it is not a complete or valid HTML tag, the browser doesn't show anything. Whenever you get a blank page, it is worth it to check the source.

 

I changed the script back to as without it didn't give an output:

if($_SERVER['REQUEST_METHOD']=='POST'
    && $_POST['submit']=='Cancel / Return to site') /// before it was: && $_POST['cancel']=='Cancel / Return to site')

 

pressing the cancel button:

 

Array
(
[cancel] => Cancel / Return to site
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17
Notice: Undefined index: submit in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 15
Notice: Undefined index: submit in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 27
Warning: Cannot modify header information - headers already sent by (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 97

Well, again, the header errors are because of the debugging output we printed, so ignore it for now.

But now your "Undefined Index" errors are back. The "cancel" code was correct, we just need to figure out what else is happening.

 

if I try and upload a large image, then refresh the index-image.php and the image hasn't uploaded to the upload directory - IT ACTUALLY UPLOADED IT TO THE DIRECTORY THAT THE UPLOAD SCRIPT IS IN AND NOT THE UPLOAD DIRECTORY SPECIFIED BY THE SCRIPT..

 

Array
(
[submit] => Upload
)
Array
(
[image] => Array
    (
        [name] => yey.jpg
        [type] => image/jpeg
        [tmp_name] => /tmp/phpk8hooD
        [error] => 0
        [size] => 1576292
    )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17

Here

    $newPath = '' . basename($_FILES['image']['name']);
   (move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

You have not specified a path to move the file to. So it is moved to the current directory (where the script is). Something must be going wrong in the resize object that prevents you from getting a valid image so the save does not work? Maybe there is some error suppression ("@" operator) in there that is preventing us from seeing the error message. The image in the script directory is your original sized image, right? Not the resized one?

 

 

if I try and upload a valid image, the image uploads to the upload directory

Array
(
[submit] => Upload
)
Array
(
[image] => Array
    (
        [name] => apartment-living2b.jpg
        [type] => image/jpeg
        [tmp_name] => /tmp/phpbiy9BS
        [error] => 0
        [size] => 77772
    )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/assets/member.class.php on line 17
Warning: Cannot modify header information - headers already sent by (output started at /home/jeremyiv/public_html/accounts/index-imageupdate.php:3) in /home/jeremyiv/public_html/accounts/index-imageupdate.php on line 91

So this one worked, eh? Well that's good news. These two error messages are because we dumped the two arrays to the output. They will go away when we take those printf's out of there.

 

upload_max_filesize 2M

post_max_size 64M

That's 2 megabytes for the file, not 2 GB as you said earlier. The post_max_size is fine, basically it just has to be a little more than the maximum filesize you want to upload.

Link to comment
Share on other sites

The "cancel" code was correct, we just need to figure out what else is happening.

 

added it back in!

 

Here

 $newPath = '' . basename($_FILES['image']['name']);
(move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

You have not specified a path to move the file to. So it is moved to the current directory (where the script is). Something must be going wrong in the resize object that prevents you from getting a valid image so the save does not work? Maybe there is some error suppression ("@" operator) in there that is preventing us from seeing the error message. The image in the script directory is your original sized image, right? Not the resized one?

 

The image is being upload at the original size into the wrong directory.

 

The path to the upload is the same as per the other images that uploaded properly:

$newPath = '' . basename($_FILES['image']['name']);
(move_uploaded_file($_FILES['image']['tmp_name'], $newPath));

// *** Include the class
include("inc/resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize($newPath);
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(475, 600, 'landscape');
// *** 3) Save image + define quality
$resizeObj -> saveImage('/home/user/public_html/'.$siteid.'/images/vacation_rentals.jpg', 85);

// Remove file from temp Directory
unlink($newPath) ;

 

the only '@' are in the resize class:

## --------------------------------------------------------
private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));
switch($extension)
{
 case '.jpg':
 case '.jpeg':
 $img = @imagecreatefromjpeg($file);
 break;
 case '.gif':
 $img = @imagecreatefromgif($file);
 break;
 case '.png':
 $img = @imagecreatefrompng($file);
 break;
 default:
 $img = false;
 break;
}
return $img;
}
## --------------------------------------------------------

 

Where do I go from here?

Edited by happypete
Link to comment
Share on other sites

took out all the '@'s on the resize class and get a new error:

 

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 10944 bytes) in /home/user/public_html/accounts/inc/resize-class.php on line 45

 

Array
(
[submit] => Upload
)
Array
(
[image] => Array
 (
	 [name] => yey.jpg
	 [type] => image/jpeg
	 [tmp_name] => /tmp/phpVUsEsR
	 [error] => 0
	 [size] => 1576292
 )
)

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/user/public_html/accounts/index-imageupdate.php:3) in /home/user/public_html/accounts/assets/member.class.php on line 17
Notice: Undefined index: cancel in /home/user/public_html/accounts/index-imageupdate.php on line 15
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 10944 bytes) in /home/user/public_html/accounts/inc/resize-class.php on line 45

 

do i need to increase the limit on the resize_class.php, if so, any suggestions on how?

 

line 45: $img = imagecreatefromjpeg($file);

 

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

# ========================================================================#
#
# Author: Jarrod Oberto
# Version: 1.0
# Date:	 17-Jan-10
# Purpose: Resizes and saves image
# Requires : Requires PHP5, GD library.
# Usage Example:
#					 include("file:///C|/xampplite/htdocs/inc/classes/resize_class.php");
#					 $resizeObj = new resize('images/cars/large/input.jpg');
#					 $resizeObj -> resizeImage(150, 100, 0);
#					 $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
#
#
# ========================================================================#
Class resize
{
// *** Class variables
private $image;
 private $width;
 private $height;
private $imageResized;
function __construct($fileName)
{
// *** Open up the file
$this->image = $this->openImage($fileName);
 // *** Get width and height
 $this->width = imagesx($this->image);
 $this->height = imagesy($this->image);
}
## --------------------------------------------------------
private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));
switch($extension)
{
 case '.jpg':
 case '.jpeg':
 $img = imagecreatefromjpeg($file); // @ REMOVED
 break;
 case '.gif':
 $img = imagecreatefromgif($file); // @ REMOVED
 break;
 case '.png':
 $img = imagecreatefrompng($file); // @ REMOVED
 break;
 default:
 $img = false;
 break;
}
return $img;
}
## --------------------------------------------------------
public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $option);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($option == 'crop') {
 $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}
## --------------------------------------------------------

private function getDimensions($newWidth, $newHeight, $option)
{
 switch ($option)
{
 case 'exact':
 $optimalWidth = $newWidth;
 $optimalHeight= $newHeight;
 break;
 case 'portrait':
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
 break;
 case 'landscape':
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
 break;
 case 'auto':
 $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
 $optimalWidth = $optionArray['optimalWidth'];
 $optimalHeight = $optionArray['optimalHeight'];
 break;
 case 'crop':
 $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
 $optimalWidth = $optionArray['optimalWidth'];
 $optimalHeight = $optionArray['optimalHeight'];
 break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function getSizeByFixedHeight($newHeight)
{
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}
private function getSizeByFixedWidth($newWidth)
{
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}
private function getSizeByAuto($newWidth, $newHeight)
{
if ($this->height < $this->width)
// *** Image to be resized is wider (landscape)
{
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
}
elseif ($this->height > $this->width)
// *** Image to be resized is taller (portrait)
{
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
}
else
// *** Image to be resizerd is a square
{
 if ($newHeight < $newWidth) {
 $optimalWidth = $newWidth;
 $optimalHeight= $this->getSizeByFixedWidth($newWidth);
 } else if ($newHeight > $newWidth) {
 $optimalWidth = $this->getSizeByFixedHeight($newHeight);
 $optimalHeight= $newHeight;
 } else {
 // *** Sqaure being resized to a square
 $optimalWidth = $newWidth;
 $optimalHeight= $newHeight;
 }
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function getOptimalCrop($newWidth, $newHeight)
{
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
if ($heightRatio < $widthRatio) {
 $optimalRatio = $heightRatio;
} else {
 $optimalRatio = $widthRatio;
}
$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
## --------------------------------------------------------
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
// *** Find center - this will be used for the crop
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
$crop = $this->imageResized;
//imagedestroy($this->imageResized);
// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
}
## --------------------------------------------------------
public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
	 $extension = strrchr($savePath, '.');
	 $extension = strtolower($extension);
switch($extension)
{
 case '.jpg':
 case '.jpeg':
 if (imagetypes() & IMG_JPG) {
 imagejpeg($this->imageResized, $savePath, $imageQuality);
 }
 break;
 case '.gif':
 if (imagetypes() & IMG_GIF) {
 imagegif($this->imageResized, $savePath);
 }
 break;
 case '.png':
 // *** Scale quality from 0-100 to 0-9
 $scaleQuality = round(($imageQuality/100) * 9);
 // *** Invert quality setting as 0 is best, not 9
 $invertScaleQuality = 9 - $scaleQuality;
 if (imagetypes() & IMG_PNG) {
 imagepng($this->imageResized, $savePath, $invertScaleQuality);
 }
 break;
 // ... etc
 default:
 // *** No extension - No save.
 break;
}
imagedestroy($this->imageResized);
}
## --------------------------------------------------------
}
?>

Edited by happypete
Link to comment
Share on other sites

Sorry, I have not been available today. I suspected the problem was with one of those imagecreate*() statements. The setting for maxium memory allowed is in the php.ini file. You should be able to see it with the phpinfo() output. That error message indicates about 32M. The manual currently says the default is 128M, so you need to check what value you are set at. You might check with your host and see if it can be increased.

 

There may be a memory leak somewhere in your script. I might have time tonight to read through that class file and see if there is a problem in it. You're trying to process a 1.5 M image file, and to tell you the truth, I don't know if 32M is a reasonable amount of memory use for that or not.

 

You can put echo memory_get_usage() . "<BR>\n"; statements in various places and see where the memory is jumping.

Link to comment
Share on other sites

I don't see anything in either of those scripts that should be chewing up that much memory. I can't see assets/member.inc.php so we don't know what that is doing.

 

Line 45 is in the openImage() method, which is called by the constructor, so the error was thrown when you instantiated the object: $resizeObj = new resize($newPath);

 

I would echo the memory_get_usage() value at the very beginning of the script, then again after the call to $member->LoggedIn(), and again just before instantiating the resize object. I would be looking for where it jumped up. The first one will give you a "baseline" since it is the start of the script. The second one will tell us if the $member object or that include file is grabbing a bunch of memory (my favorite suspect right now), and the third one will tell us if all of the checks you are doing are using lots of memory (I don't think they are). Then we can proceed from there.

Link to comment
Share on other sites

 

There may be a memory leak somewhere in your script. I might have time tonight to read through that class file and see if there is a problem in it. You're trying to process a 1.5 M image file, and to tell you the truth, I don't know if 32M is a reasonable amount of memory use for that or not.

 

 

Thanks very much. Any help to improve the script is very much appreciated

 

I added ' echo memory_get_usage() . "<BR>\n";' in 2 places

 

  echo memory_get_usage() . "<BR>\n";

// *** Include the class
include("inc/resize-class.php");

echo memory_get_usage() . "<BR>\n";

 

the results:

 

1885080

1943120

 

I just chatted with my webhost and have some increases:

memory_limit 128M

upload_max_filesize10M

 

The large file now uploads :)

 

Will remove the php error reporting and see if everything works ok..

Link to comment
Share on other sites

echo memory_get_usage() . "<BR>\n"; added

 

at start of script : 664240

after $member->LoggedIn(), : 1882288

before resize-class.php include: 1886432

after resize-class.php include: 1944440

 

these values are when I upload a 1.5m image

Edited by happypete
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.