dotsandcoms
asked on
Upload and Resize Large image using PHP
Hello experts,
I am new to PHP and I am developing Image Gallery component. Everything is working fine.
I can upload image upto 2MB and get resize it but cannot upload and resize larger image.
I tried to update settings in php.ini file and its working fine but on client's end php.ini is not accessible. Also, I tried to update via .htaccess but it gives me "Internal Error" on client's end.
My server is IIS and Client's Server is Linux based Apache.
Thanks in Advance.
Below is My Code:
Upload and Record Insertion Code:
<?php
error_reporting(-1);
ini_set('upload_max_filesi ze', '8388608');
ini_set('post_max_size', '8388608');
ini_set('max_input_time', 1200);
ini_set('max_execution_tim e', 1200);
ini_set('memory_limit', -1);
require_once('_connection/ Database-q uery.php') ;
require_once('SimpleImage. php');
function SaveImages($txtTitle,$fluF ile,$visib le){
if ($fluFile["error"] > 0)
{
echo "File Error: " . $fluFile["error"] . "<br />";
return false;
}
$fileName = $fluFile["name"];
$fileName = str_replace("#", "-", $fileName);
$fileName = str_replace("$", "-", $fileName);
$fileName = str_replace("%", "-", $fileName);
$fileName = str_replace("^", "", $fileName);
$fileName = str_replace("&", "-", $fileName);
$fileName = str_replace("*", "", $fileName);
$fileName = str_replace("?", "", $fileName);
$fileName = str_replace("/", "", $fileName);
$fileName = str_replace("\\", "", $fileName);
$fileName = str_replace("'", "", $fileName);
if(strlen($fluFile["name"] ) <= 0)
{
return false;
}
else
{
$imgType = $fluFile["type"] ;
if($imgType == "image/gif" || $imgType == "image/png" || $imgType == "image/jpg" || $imgType == "image/jpeg" || $imgType == "image/pjpeg")
{
$newFileName = date('dmYGHs').'-'.$fileNa me;
$uploadPath = realpath("../gallery/orig/ ")."/".$ne wFileName;
move_uploaded_file($fluFil e["tmp_nam e"],$uploa dPath);
$image = new SimpleImage();
$image->load($uploadPath);
$disImagePath = realpath("../gallery/displ ay/")."/". $newFileNa me;
$thumbImagePath = realpath("../gallery/thumb /")."/".$n ewFileName ;
/// Create Zoom Image ///
if($image->getWidth() > 810)
{
$image->resizeToWidth(810) ;
$image->save($disImagePath );
}
else if($image->getHeight() > 405)
{
$image->resizeToHeight(405 );
$image->save($disImagePath );
}
else
$image->save($disImagePath );
/// End Zoom Image ///
/// Create Thumb Image ///
if($image->getHeight() > 60)
{
$image->resizeToHeight(60) ;
$image->save($thumbImagePa th);
}
else if($image->getWidth() > 120)
{
$image->resizeToWidth(120) ;
$image->save($thumbImagePa th);
}
else
$image->save($thumbImagePa th);
/// End Thumb Image ///
$disOrder = 1;
$set_select_sql = "Select displayorder from photogallery order by id desc limit 1";
$sqlDisStr = mysql_query($set_select_sq l);
if (mysql_numrows($sqlDisStr) != 0) {
$row = mysql_fetch_array($sqlDisS tr);
$disOrder = $row[0] + 1;
}
else
$disOrder = 1;
$photoTitle = str_replace('\'',''',$ txtTitle);
$strIns = "Insert into photogallery (title,imageFileName,uploa dDate,disp layOrder,v isible)";
$strIns .= " values('". $photoTitle ."','". $newFileName ."','". date('Y-m-d') ."' ,". $disOrder .",". $visible .")";
if (!mysql_query($strIns))
{
die('Error 2: ' . mysql_error());
}
return true;
}
else
{
return false;
}
}
}
?>
Image Resize Code:
<?php
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filen ame);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filena me);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filena me);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG , $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$fi lename,$co mpression) ;
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$fil ename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$fil ename);
}
if( $permissions != null) {
chmod($filename,$permissio ns);
}
}
function output($image_type=IMAGETY PE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$heig ht);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$heig ht);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$heig ht);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($widt h, $height);
imagecopyresampled($new_im age, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
I am new to PHP and I am developing Image Gallery component. Everything is working fine.
I can upload image upto 2MB and get resize it but cannot upload and resize larger image.
I tried to update settings in php.ini file and its working fine but on client's end php.ini is not accessible. Also, I tried to update via .htaccess but it gives me "Internal Error" on client's end.
My server is IIS and Client's Server is Linux based Apache.
Thanks in Advance.
Below is My Code:
Upload and Record Insertion Code:
<?php
error_reporting(-1);
ini_set('upload_max_filesi
ini_set('post_max_size', '8388608');
ini_set('max_input_time', 1200);
ini_set('max_execution_tim
ini_set('memory_limit', -1);
require_once('_connection/
require_once('SimpleImage.
function SaveImages($txtTitle,$fluF
if ($fluFile["error"] > 0)
{
echo "File Error: " . $fluFile["error"] . "<br />";
return false;
}
$fileName = $fluFile["name"];
$fileName = str_replace("#", "-", $fileName);
$fileName = str_replace("$", "-", $fileName);
$fileName = str_replace("%", "-", $fileName);
$fileName = str_replace("^", "", $fileName);
$fileName = str_replace("&", "-", $fileName);
$fileName = str_replace("*", "", $fileName);
$fileName = str_replace("?", "", $fileName);
$fileName = str_replace("/", "", $fileName);
$fileName = str_replace("\\", "", $fileName);
$fileName = str_replace("'", "", $fileName);
if(strlen($fluFile["name"]
{
return false;
}
else
{
$imgType = $fluFile["type"] ;
if($imgType == "image/gif" || $imgType == "image/png" || $imgType == "image/jpg" || $imgType == "image/jpeg" || $imgType == "image/pjpeg")
{
$newFileName = date('dmYGHs').'-'.$fileNa
$uploadPath = realpath("../gallery/orig/
move_uploaded_file($fluFil
$image = new SimpleImage();
$image->load($uploadPath);
$disImagePath = realpath("../gallery/displ
$thumbImagePath = realpath("../gallery/thumb
/// Create Zoom Image ///
if($image->getWidth() > 810)
{
$image->resizeToWidth(810)
$image->save($disImagePath
}
else if($image->getHeight() > 405)
{
$image->resizeToHeight(405
$image->save($disImagePath
}
else
$image->save($disImagePath
/// End Zoom Image ///
/// Create Thumb Image ///
if($image->getHeight() > 60)
{
$image->resizeToHeight(60)
$image->save($thumbImagePa
}
else if($image->getWidth() > 120)
{
$image->resizeToWidth(120)
$image->save($thumbImagePa
}
else
$image->save($thumbImagePa
/// End Thumb Image ///
$disOrder = 1;
$set_select_sql = "Select displayorder from photogallery order by id desc limit 1";
$sqlDisStr = mysql_query($set_select_sq
if (mysql_numrows($sqlDisStr)
$row = mysql_fetch_array($sqlDisS
$disOrder = $row[0] + 1;
}
else
$disOrder = 1;
$photoTitle = str_replace('\'',''',$
$strIns = "Insert into photogallery (title,imageFileName,uploa
$strIns .= " values('". $photoTitle ."','". $newFileName ."','". date('Y-m-d') ."' ,". $disOrder .",". $visible .")";
if (!mysql_query($strIns))
{
die('Error 2: ' . mysql_error());
}
return true;
}
else
{
return false;
}
}
}
?>
Image Resize Code:
<?php
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filen
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filena
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filena
}
}
function save($filename, $image_type=IMAGETYPE_JPEG
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$fi
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$fil
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$fil
}
if( $permissions != null) {
chmod($filename,$permissio
}
}
function output($image_type=IMAGETY
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$heig
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$heig
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$heig
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($widt
imagecopyresampled($new_im
$this->image = $new_image;
}
}
?>
ini_set('upload_max_filesize', '8388608');
ini_set('post_max_size', '8388608');
That will not work. As stated here:
http://www.php.net/manual/en/ini.core.php
upload_max_filesize and post_max_size are only PHP_INI_PERDIR changeable. So you have to make these settings in a .htaccess file.
Is PHP running in "CGI mode" or as Apache module? If PHP is running in "CGI mode" you can't make these settings via .htaccess. You have to adjust them in php.ini.
The 2MB limit sounds familiar. PHP has a number of limits built in to it and one of these is file upload size. It is usually set to 2MB but you can change it by editing PHP.INI and finding
upload_max_filesize = 2M
and change 2M to 4M or whatever you like. Also read this http://php.net/manual/en/ini.core.php and scan for "File Uploads"
upload_max_filesize = 2M
and change 2M to 4M or whatever you like. Also read this http://php.net/manual/en/ini.core.php and scan for "File Uploads"
I just want to add a simple notet to what has been posted above.
If your client has php installed as a CGI instead of an apache module. For example he has suPHP installed then you cannot put the above changes in a .htaccess file. You should put them directly under php.ini of it you dont have access to it then you create a php.ini file in your clients /home and put those values in it.
The syntax is different between .htaccess file and php.ini
For php.ini follow the syntax posted by bportlock
If your client has php installed as a CGI instead of an apache module. For example he has suPHP installed then you cannot put the above changes in a .htaccess file. You should put them directly under php.ini of it you dont have access to it then you create a php.ini file in your clients /home and put those values in it.
The syntax is different between .htaccess file and php.ini
For php.ini follow the syntax posted by bportlock
ASKER
Hi small_student,
I think php is installed as CGI. But can you please verify ?
On runnint phpinfo(); I get "Server API -> CGI/FastCGI ". Does it means CGI ? if you want phpinfo() url i am ready to give.
I think php is installed as CGI. But can you please verify ?
On runnint phpinfo(); I get "Server API -> CGI/FastCGI ". Does it means CGI ? if you want phpinfo() url i am ready to give.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi,
Will it be ok as php.ini ? And, will it effect other php.ini settings ?
[PHP]
post_max_size = 12M
upload_max_filesize = 12M
max_execution_time = 1200
max_input_time = 1200
memory_limit = -1
Will it be ok as php.ini ? And, will it effect other php.ini settings ?
[PHP]
post_max_size = 12M
upload_max_filesize = 12M
max_execution_time = 1200
max_input_time = 1200
memory_limit = -1
Now I would not advise of putting memory limit to unlimited, this would make you open for memory leaks and memory DOS attacks. At least put some limit for memory
ASKER
ok..sure...i'll put 128M there as php.ini default...
but my question is do i have to put only this in php.ini or need to make whole php.ini ?
but my question is do i have to put only this in php.ini or need to make whole php.ini ?
You can either use a directory vbased php.ini or the global one. I would stick it in the global one as it keeps it away from sticky fingers that might want to fiddle or people deleting what they think is "duff" files when tidying up. If you pout it in the global version then it is out of the way and safe and none of your limits are outrageous or silly as long as you set the memory limit to 128M
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
sure...i'll try and will update you.
When you have code to post here at EE, please use the code snippet.
Here is a teaching example of how to upload and resize an image. You can install it and run it to see the moving parts. Please read it over, code, comments and especially the man page references and post back with any specific questions. Regards, ~Ray
Here is a teaching example of how to upload and resize an image. You can install it and run it to see the moving parts. Please read it over, code, comments and especially the man page references and post back with any specific questions. Regards, ~Ray
<?php // RAY_upload_resize_example.php
error_reporting(E_ALL);
// UPLOAD AN IMAGE AND RESIZE IT TO FIT SOME PREDEFINED SIZES
// http://php.net/manual/en/ref.image.php
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/function.getimagesize.php
// http://php.net/manual/en/function.imagejpeg.php
// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{
// IS GD INSTALLED AT ALL?
if (!function_exists("gd_info"))
{
if ($display) echo "<br/>GD NOT INSTALLED\n";
return FALSE;
}
// IF GD IS INSTALLED GET DETAILS
$gd = gd_info();
// IF DISPLAY IS REQUESTED, PRINT DETAILS
if ($display)
{
echo "<br/>GD DETAILS:\n";
foreach ($gd as $key => $value)
{
if ($value === TRUE) $value = 'YES';
if ($value === FALSE) $value = 'NO';
echo "<br/>$key = $value \n";
}
}
// RETURN THE VERSION NUMBER
$gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
return $gd_version;
}
// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
// IS GD HERE?
$gdv = get_gd_info();
if (!$gdv) return FALSE;
// GET AN IMAGE THING
$source = imagecreatefromjpeg("$image");
// GET THE X AND Y DIMENSIONS
$imageX = imagesx($source);
$imageY = imagesy($source);
// IF NO RESIZING IS NEEDED
if ($imageX <= $width)
{
return FALSE;
}
// THE WIDTH IS TOO GREAT - MUST RESIZE
$tnailX = $width;
$tnailY = (int) (($tnailX * $imageY) / $imageX );
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
if ($gdv >= 2)
{
// IF GD IS AT LEVEL 2 OR ABOVE
$target = imagecreatetruecolor($tnailX, $tnailY);
imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
}
else
{
// IF GD IS AT A LOWER REVISION LEVEL
$target = imagecreate($tnailX, $tnailY);
imagecopyresized ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
}
return $target ;
}
/* ********************************************************************************************* */
// ESTABLISH THE NAMES OF THE DIRECTORIES
$s = 'RAY/storage/';
$p = 'RAY/pics/';
$t = 'RAY/thumbs/';
// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;
// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
// IF THERE ARE ERRORS
$error_code = $_FILES["userfile"]["error"];
if ($error_code)
{
die($errors[$error_code]);
}
// SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
$f = basename($_FILES['userfile']['name']);
$my_new = getcwd() . '/' . $s . $f;
$my_temp = $s . $f;
// MOVE THE FILE INTO THE STORAGE DIRECTORY
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
{
die("MOVE TO $my_new FAILED");
}
// SAVE THE PIC
if ($image_resource = create_right_size_image($my_temp, 450))
{
imagejpeg($image_resource, $p . $f);
imagedestroy($image_resource);
}
// SAVE THE THUMB
if ($image_resource = create_right_size_image($my_temp, 100))
{
imagejpeg($image_resource, $t . $f);
imagedestroy($image_resource);
}
// DISPOSE OF THE UNWANTED ORIGINAL
unlink($my_new);
// SHOW THE LINKS TO THE NEW FILES
echo '<br/><a href="' . $p . $f . '">PIC</a>';
echo '<br/><a href="' . $t . $f . '">THUMB</a>';
}
// CREATE THE FORM FOR INPUT USING HEREDOC SYNTAX
$form = <<<ENDFORM
<form enctype="multipart/form-data" method="post">
<!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a Photo to Upload: <input name="userfile" type="file" />
<input type="submit" value="Upload" />
</form>
ENDFORM;
echo $form;
ASKER
Hi small_student,
I put php.ini in root directory of site but doesn't solve the problem. Do i have to tell server techsupport to allow.
I put php.ini in root directory of site but doesn't solve the problem. Do i have to tell server techsupport to allow.
I am not really sure, You can ask them of how to achieve this.
Wonder why you did not award any points to the first correct answer, here: ID:34904702
?
?
http://www.thewebhelp.com/php/scripts/image-upload-with-resize/