Jump to content

Resize code to work on most PHP hosts without error?


student101

Recommended Posts

Will this resize script work on most PHP hosts without error?What would the best server settings be - register_globals, max_execution_time ??

/* *** START resize image if needed START *** */ // move to "upload file without resizing"if($sExtension != 'jpg' && $sExtension != 'jpeg' && $sExtension != 'gif' && $sExtension != 'png'){move_uploaded_file( $oFile['tmp_name'], $sFilePath );}else{// set dimensions $maxWidth = 300;$maxHeight = 300;// Get / Set image size list($oldWidth, $oldHeight) = getimagesize($oFile['tmp_name']);if(($oldWidth > $maxWidth) || ($oldHeight > $maxHeight)){ //upload file with resizing$imgRatio=$oldWidth/$oldHeight; //calculate the image ratioif ($imgRatio>1){$newWidth = $maxWidth;$newHeight = $maxWidth/$imgRatio;}else{$newHeight = $maxWidth;$newWidth = $maxWidth*$imgRatio;}$newImage = imagecreatetruecolor($newWidth, $newHeight);switch ($oFile['type']){ case 'image/gif':$oldImage = imagecreatefromgif($oFile['tmp_name']); // create image object for resizingimagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);//resizingimagegif($newImage, $sFilePath); // copy resized image to destinationbreak;case 'image/jpeg':case 'image/pjpeg':$oldImage = imagecreatefromjpeg($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagejpeg($newImage, $sFilePath);break;case 'image/png':case 'image/x-png':$oldImage = imagecreatefrompng($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagepng($newImage, $sFilePath); break;}imagedestroy($oldImage); // destroy temporary image objectsimagedestroy($newImage);}else{ // "upload file without resizing"move_uploaded_file( $oFile['tmp_name'], $sFilePath );}}

Link to comment
Share on other sites

In order to answer that I suppose we would need to find out what "most" hosts use as PHP settings. Which functions or techniques do you think may not work? There are several undefined variables, but I assume you define them before this code.

Link to comment
Share on other sites

Versions being used:

MySQL Client API version 4.1.22PHP Version 5.2.14Server API CGI/FastCGI register_globals On register_long_arrays On PHP Version 4.3.4Client API version 3.23.49Server API CGI register_globals Offregister_long_arrays NA
Using the commands.php page in FCKeditor;Entire page below: the added parts are marked with [iCODE]/* *** added *** */[/iCODE]
<?php/* *** added START *** */ // string ini_set ( string varname, string newvalue)ini_set("memory_limit","64M");/* *** added END *** */ /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * *  - GNU General Public License Version 2 or later (the "GPL") *	http://www.gnu.org/licenses/gpl.html * *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL") *	http://www.gnu.org/licenses/lgpl.html * *  - Mozilla Public License Version 1.1 or later (the "MPL") *	http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is the File Manager Connector for PHP. */function GetFolders( $resourceType, $currentFolder ){ // Map the virtual path to the local server path. $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFolders' ); // Array that will hold the folders names. $aFolders = array(); $oCurrentFolder = opendir( $sServerDir ); while ( $sFile = readdir( $oCurrentFolder ) ) {  if ( $sFile != '.' && $sFile != '..' && is_dir( $sServerDir . $sFile ) )   $aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />'; } closedir( $oCurrentFolder ); // Open the "Folders" node. echo "<Folders>"; natcasesort( $aFolders ); foreach ( $aFolders as $sFolder )  echo $sFolder; // Close the "Folders" node. echo "</Folders>";}function GetFoldersAndFiles( $resourceType, $currentFolder ){ // Map the virtual path to the local server path. $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ); // Arrays that will hold the folders and files names. $aFolders = array(); $aFiles  = array(); $oCurrentFolder = opendir( $sServerDir ); while ( $sFile = readdir( $oCurrentFolder ) ) {  if ( $sFile != '.' && $sFile != '..' )  {   if ( is_dir( $sServerDir . $sFile ) )	$aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />';   else   {	$iFileSize = @filesize( $sServerDir . $sFile );	if ( !$iFileSize ) {	 $iFileSize = 0;	}	if ( $iFileSize > 0 )	{	 $iFileSize = round( $iFileSize / 1024 );	 if ( $iFileSize < 1 ) $iFileSize = 1;	}	$aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" />';   }  } } // Send the folders natcasesort( $aFolders ); echo '<Folders>'; foreach ( $aFolders as $sFolder )  echo $sFolder; echo '</Folders>'; // Send the files natcasesort( $aFiles ); echo '<Files>'; foreach ( $aFiles as $sFiles )  echo $sFiles; echo '</Files>';}function CreateFolder( $resourceType, $currentFolder ){ if (!isset($_GET)) {  global $_GET; } $sErrorNumber = '0'; $sErrorMsg  = ''; if ( isset( $_GET['NewFolderName'] ) ) {  $sNewFolderName = $_GET['NewFolderName'];  $sNewFolderName = SanitizeFolderName( $sNewFolderName );  if ( strpos( $sNewFolderName, '..' ) !== FALSE )   $sErrorNumber = '102';  // Invalid folder name.  else  {   // Map the virtual path to the local server path of the current folder.   $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'CreateFolder' );   if ( is_writable( $sServerDir ) )   {	$sServerDir .= $sNewFolderName;	$sErrorMsg = CreateServerFolder( $sServerDir );	switch ( $sErrorMsg )	{	 case '' :	  $sErrorNumber = '0';	  break;	 case 'Invalid argument' :	 case 'No such file or directory' :	  $sErrorNumber = '102';  // Path too long.	  break;	 default :	  $sErrorNumber = '110';	  break;	}   }   else	$sErrorNumber = '103';  } } else  $sErrorNumber = '102'; // Create the "Error" node. echo '<Error number="' . $sErrorNumber . '" originalDescription="' . ConvertToXmlAttribute( $sErrorMsg ) . '" />';}function FileUpload( $resourceType, $currentFolder, $sCommand ){ if (!isset($_FILES)) {  global $_FILES; } $sErrorNumber = '0'; $sFileName = ''; if ( isset( $_FILES['NewFile'] ) && !is_null( $_FILES['NewFile']['tmp_name'] ) ) {  global $Config;  $oFile = $_FILES['NewFile'];  // Map the virtual path to the local server path.  $sServerDir = ServerMapFolder( $resourceType, $currentFolder, $sCommand );  // Get the uploaded file name.  $sFileName = $oFile['name'];  $sFileName = SanitizeFileName( $sFileName );  /* *** added START *** */ // remove whitespaces$sFileName = preg_replace( "/\s/", "", $sFileName);// remove funny chars$sFileName = preg_replace("/\s+|;|\+|=|\[|\]|'|,|\\|\"|\*|<|>|\/|\?|\:|\\$|&|\|/i", "_", $sFileName);// generate random number$randigit=rand(0,99);$sFileName = $randigit.$sFileName; /* *** added END *** */   $sOriginalFileName = $sFileName;  // Get the extension.  $sExtension = substr( $sFileName, ( strrpos($sFileName, '.') + 1 ) );  $sExtension = strtolower( $sExtension );  if ( isset( $Config['SecureImageUploads'] ) )  {   if ( ( $isImageValid = IsImageValid( $oFile['tmp_name'], $sExtension ) ) === false )   {	$sErrorNumber = '202';   }  }  if ( isset( $Config['HtmlExtensions'] ) )  {   if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) &&	( $detectHtml = DetectHtml( $oFile['tmp_name'] ) ) === true )   {	$sErrorNumber = '202';   }  }  // Check if it is an allowed extension.  if ( !$sErrorNumber && IsAllowedExt( $sExtension, $resourceType ) )  {   $iCounter = 0;   while ( true )   {	$sFilePath = $sServerDir . $sFileName;	if ( is_file( $sFilePath ) )	{	 $iCounter++;	 $sFileName = RemoveExtension( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension;	 $sErrorNumber = '201';	}else{	 	 	 /* *** added START *** */	 // move_uploaded_file( $oFile['tmp_name'], $sFilePath );/* *** START resize image if needed START *** */ if($sExtension != 'jpg' && $sExtension != 'jpeg' && $sExtension != 'gif' && $sExtension != 'png'){move_uploaded_file( $oFile['tmp_name'], $sFilePath );}else{$maxWidth = 300;$maxHeight = 300;list($oldWidth, $oldHeight) = getimagesize($oFile['tmp_name']);if(($oldWidth > $maxWidth) || ($oldHeight > $maxHeight)){ //upload file with resizing$imgRatio=$oldWidth/$oldHeight; //calculate the image ratioif ($imgRatio>1){$newWidth = $maxWidth;$newHeight = $maxWidth/$imgRatio;}else{$newHeight = $maxWidth;$newWidth = $maxWidth*$imgRatio;}$newImage = imagecreatetruecolor($newWidth, $newHeight);switch ($oFile['type']){ case 'image/gif':$oldImage = imagecreatefromgif($oFile['tmp_name']); // create image object for resizingimagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);//resizingimagegif($newImage, $sFilePath); // copy resized image to destinationbreak;case 'image/jpeg':case 'image/pjpeg':$oldImage = imagecreatefromjpeg($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagejpeg($newImage, $sFilePath);break;case 'image/png':case 'image/x-png':$oldImage = imagecreatefrompng($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagepng($newImage, $sFilePath); break;}imagedestroy($oldImage); // destroy temporary image objectsimagedestroy($newImage);}else{ //upload file without resizing  move_uploaded_file( $oFile['tmp_name'], $sFilePath );}}/* *** added END *** */ if ( is_file( $sFilePath ) )	 {	  if ( isset( $Config['ChmodOnUpload'] ) && !$Config['ChmodOnUpload'] )	  {	   break;	  }	  $permissions = 0777;	  if ( isset( $Config['ChmodOnUpload'] ) && $Config['ChmodOnUpload'] )	  {	   $permissions = $Config['ChmodOnUpload'];	  }	  $oldumask = umask(0);	  chmod( $sFilePath, $permissions );	  umask( $oldumask );	 }	 break;	}   }   if ( file_exists( $sFilePath ) )   {	//previous checks failed, try once again	if ( isset( $isImageValid ) && $isImageValid === -1 && IsImageValid( $sFilePath, $sExtension ) === false )	{	 @unlink( $sFilePath );	 $sErrorNumber = '202';	}	else if ( isset( $detectHtml ) && $detectHtml === -1 && DetectHtml( $sFilePath ) === true )	{	 @unlink( $sFilePath );	 $sErrorNumber = '202';	}   }  }  else   $sErrorNumber = '202'; } else  $sErrorNumber = '202'; $sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ); $sFileUrl = CombinePaths( $sFileUrl, $sFileName ); SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ); exit;}?>

Link to comment
Share on other sites

I don't see any PHP5-only function, so as long as you're not relying on register_globals it should be fine.
Now the obvious question? Does my resize and random code including my preg_replace rely on it?If the answer is NO, then why am I only allowed to upload a 900K imageSorry PHP-5 Only function? what do you mean, sorry If I'm being a bit slow here...
Link to comment
Share on other sites

Sorry PHP-5 Only function? what do you mean, sorry If I'm being a bit slow here...
Functions defined in PHP5 but not in PHP4. This is an example:http://www.php.net/manual/en/mysqli.query.phpLook under the function name for the required version. Compare that with this one:http://www.php.net/manual/en/function.mysql-query.php
Does my resize and random code including my preg_replace rely on it?
Well, what does register_globals do? Does the code rely on its effects?
Link to comment
Share on other sites

I have attempted a PHP.INI in the cgi-bin folder but the host has disabled overrides!

display_errors = Onerror_reporting = E_ALLlog_errors = Onlog_errors_max_len = 1024display_startup_errors = Offignore_repeated_source = Offreport_memleaks = Ontrack_errors = Off; Log errors to specified file, no clue how the log file should be set? error_log = php_error.logpost_max_size = 16Mupload_max_filesize = 16Mmax_execution_time = 1024max_input_time = 1024memory_limit = -1;Not sure if output_buffering is even needed?output_buffering = 4096
Link to comment
Share on other sites

The host Finally enabled error logs:

FATAL: emalloc(): Unable to allocate 8560 bytes[Date and Time] [error] [client *.*.*.*] Premature end of script headers: /www/cgi-bin/php
[edit] Without my resize code it uploads images of 1.6MB, there must be something wrong with it?I need to enable resizing images on upload.[/edit]
Long story short, all my hosts need to match what I have![quote]Apache Version :2.2.3 PHP Version :5.2.11 MySQL Version :5.1.36register_globals = Off[/quote]

Link to comment
Share on other sites

The upload isn't the problem. This isn't disk space type of memory, it's RAM memory that you're using on image resources when applying GD functions to them.If you were working with more than one image, image_destroy() would be able to help free some memory after you're finished with each image, but since this single image already takes up all the memory than you can't free anything while working with it.

Link to comment
Share on other sites

The upload isn't the problem. This isn't disk space type of memory, it's RAM memory that you're using on image resources when applying GD functions to them.
I am fully aware of that's it RAM related, that's why I'm interested to know what the best memory limit would be?A 2200 x 3100 Pixel JPG file can be about 1MB to 3MB, which could require 2200 x 3100 x 3 (One byte each for Red, Green, and Blue) = at least 20MB to 30MBThis will resize a 2MB image to 66KB, read on...
if($sExtension == 'jpg' || $sExtension == 'jpeg' || $sExtension == 'gif' ){$uploadedfile = $_FILES['NewFile']['tmp_name'];// Create an Image from it so we can do the resize$src = imagecreatefromjpeg($uploadedfile);// Capture the original size of the uploaded imagelist($width,$height)=getimagesize($uploadedfile);// For my purposes, I have resized the image to be 300 pixels wide, and maintain the original aspect ratio. // This prevents the image from being "stretched" or "squashed". If you prefer some max width other than 300, simply change the $newwidth variable$newwidth=300;$newheight=($height/$width)*$newwidth;$tmp=imagecreatetruecolor($newwidth,$newheight);// this line actually does the image resizing, copying from the original// image into the $tmp imageimagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);// now write the resized image to disk. I have assumed that you want the// resized, uploaded image file to reside in the ./images subdirectory.$filename = $_FILES['NewFile']['tmp_name'];imagejpeg($tmp,$filename,100);move_uploaded_file( $filename, $sFilePath );imagedestroy($src);imagedestroy($tmp);}else{move_uploaded_file( $oFile['tmp_name'], $sFilePath );}

This will resize the same 2MB image to 16KB, freakin COOL!!!

if($sExtension != 'jpg' && $sExtension != 'jpeg' && $sExtension != 'gif' && $sExtension != 'png'){move_uploaded_file( $oFile['tmp_name'], $sFilePath );}else{$maxWidth = 300;$maxHeight = 300;list($oldWidth, $oldHeight) = getimagesize($oFile['tmp_name']);if(($oldWidth > $maxWidth) || ($oldHeight > $maxHeight)){ //upload file with resizing$imgRatio=$oldWidth/$oldHeight; //calculate the image ratioif ($imgRatio>1){$newWidth = $maxWidth;$newHeight = $maxWidth/$imgRatio;}else{$newHeight = $maxWidth;$newWidth = $maxWidth*$imgRatio;}$newImage = imagecreatetruecolor($newWidth, $newHeight);switch ($oFile['type']){ case 'image/gif':$oldImage = imagecreatefromgif($oFile['tmp_name']); // create image object for resizingimagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);//resizingimagegif($newImage, $sFilePath); // copy resized image to destinationbreak;case 'image/jpeg':case 'image/pjpeg':$oldImage = imagecreatefromjpeg($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagejpeg($newImage, $sFilePath);break;case 'image/png':case 'image/x-png':$oldImage = imagecreatefrompng($oFile['tmp_name']);imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);imagepng($newImage, $sFilePath); break;}imagedestroy($oldImage); // destroy temporary image objectsimagedestroy($newImage);}else{ //upload file without resizing  move_uploaded_file( $oFile['tmp_name'], $sFilePath );}}

Link to comment
Share on other sites

You can build a test uploader and use memory_get_usage and memory_get_peak_usage to monitor how much memory it's using. If you test it with a few different file sizes and graph the results you should get an idea about the memory requirements based on the image size.http://www.php.net/manual/en/function.memo...-peak-usage.php

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...