Solved

Upload and Resize Large image using PHP

Posted on 2011-02-16
17
836 Views
Last Modified: 2012-08-13
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_filesize', '8388608');
      ini_set('post_max_size', '8388608');  
      ini_set('max_input_time', 1200);  
      ini_set('max_execution_time', 1200);
      ini_set('memory_limit', -1);
      require_once('_connection/Database-query.php');
      require_once('SimpleImage.php');
      function SaveImages($txtTitle,$fluFile,$visible){
            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').'-'.$fileName;
                        $uploadPath = realpath("../gallery/orig/")."/".$newFileName;
                        move_uploaded_file($fluFile["tmp_name"],$uploadPath);                        
                        
                        $image = new SimpleImage();
                        $image->load($uploadPath);
                                                
                        $disImagePath = realpath("../gallery/display/")."/".$newFileName;
                        $thumbImagePath = realpath("../gallery/thumb/")."/".$newFileName;                        
                        
                        ///            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($thumbImagePath);
                        }                        
                        else if($image->getWidth() > 120)
                        {
                              $image->resizeToWidth(120);
                              $image->save($thumbImagePath);
                        }
                        else
                              $image->save($thumbImagePath);
                        ///            End Thumb Image ///                              
                        
                        $disOrder = 1;                        
                        $set_select_sql = "Select displayorder from photogallery order by id desc limit 1";                        
                        $sqlDisStr = mysql_query($set_select_sql);
                        if (mysql_numrows($sqlDisStr) != 0) {
                              $row = mysql_fetch_array($sqlDisStr);
                              $disOrder = $row[0] + 1;
                        }
                        else
                              $disOrder = 1;
                        
                        $photoTitle = str_replace('\'','&#39;',$txtTitle);
                        
                        
                        $strIns = "Insert into photogallery (title,imageFileName,uploadDate,displayOrder,visible)";
                        $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($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image,$filename);        
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image,$filename);
      }  
      if( $permissions != null) {
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_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,$height);
   }
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;  
   }      
}
?>
0
Comment
Question by:dotsandcoms
  • 5
  • 5
  • 2
  • +4
17 Comments
 
LVL 11

Expert Comment

by:SAMIR BHOGAYTA
ID: 34904601
0
 
LVL 4

Expert Comment

by:d4011
ID: 34904702
      ini_set('upload_max_filesize', '8388608');
      ini_set('post_max_size', '8388608');  

Open in new window


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.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 34904746
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"
0
 
LVL 14

Expert Comment

by:small_student
ID: 34905039
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
0
 

Author Comment

by:dotsandcoms
ID: 34905115
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.
0
 
LVL 14

Accepted Solution

by:
small_student earned 334 total points
ID: 34905175
Yes FastCgi runs php in a different proccess therfore you need to put your settings in a php.ini file and not in a .htaccess
0
 
LVL 11

Assisted Solution

by:mattibutt
mattibutt earned 166 total points
ID: 34905199
You need to overrise the upload by putting file.ini inside your web directory not in .htaccess you need to run phpinfo and see what is the max upload size appearin there
0
 

Author Comment

by:dotsandcoms
ID: 34905213
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
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 14

Expert Comment

by:small_student
ID: 34905305
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
0
 

Author Comment

by:dotsandcoms
ID: 34905450
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 ?
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 34905515
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
0
 
LVL 14

Assisted Solution

by:small_student
small_student earned 334 total points
ID: 34905957
If you have access to the global php.ini file then make the changes there as suggested by bportlock. Otherwise you can stick to the local version with the lines you posted. No need to make a new full copy of php.ini directives.

The idea is that the lines you put will override the default lines in php.ini global file. However both files will be read.
0
 

Author Comment

by:dotsandcoms
ID: 34906039
sure...i'll try and will update you.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34907314
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
<?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;

Open in new window

0
 

Author Comment

by:dotsandcoms
ID: 34913319
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.
0
 
LVL 14

Expert Comment

by:small_student
ID: 34914196
I am not really sure, You can ask them of how to achieve this.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34933075
Wonder why you did not award any points to the first correct answer, here: ID:34904702

?
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now