Solved

PHP getimagesize function

Posted on 2010-11-16
14
911 Views
Last Modified: 2012-05-10
Hi all,

I am trying to add the getimagesize function to my code but as it's an image upload and it creates a temp name, then the real one I don't know how to implement it in my code.

Can someone please help?

See code attached below

THanks
//Controller code

<?php
class UploadsController extends AppController {
	
	var $name = 'Uploads';
	var $useTable = 'competitions_entry';
	var $components = array('RequestHandler','FileUpload','Session');  
	var $helpers = array('Html', 'Form', 'Javascript','Session', 'Ajax');
	var $uses = array('User','Competition','Upload', 'Vote');
	
		
	
	
		
	
	
	function index($id = null) {
		

		
		//$this->set('uploads', $this->Upload->find('all')); 
		$temp_id = $this->sodium_user['User']['id'];
		
		
		
		$theuploads = $this->Upload->query("SELECT * FROM entries where user_id <> $temp_id");
										   
		$this->set('uploads', $theuploads);
		
			
		if($this->RequestHandler->isPost()) {
		
		   
		
		$this->Upload->create();
		
			$component = new FileUploadComponent();
			$component->upload(array('name'=>'blablabla', 'tmp_name'=>'tmp_blabla'));
			$FullUrl = $component->getFullpath();
			$currentUserId = $this->sodium_user['User']['id'];
			$test = $component->getFolder();
			$ddd = $component->getDestination();
			
		
				
		
		   
			//Get the path to save;
			$data = array('Upload' => array(
					'competition_id' => $this->data['Upload']['comp_id'],
					'user_id' => $currentUserId,// <- Need to get this via url
			 		'directory_name'=> 'img/uploads/',
					'name' => $test.'-'.$this->data['Upload'][0]['file']['name'],
					'size' => $this->data['Upload'][0]['file']['size'], 
					'type' => $this->data['Upload'][0]['file']['type']
				)
			);
		
		
		
		 
			
		
	
		
		//*****************************************************************
		// LETS START WITH THE VALIDATION
		//*****************************************************************
		
		
		
		
		
		//**********************************************************
		//	CHECK IF THE USER HAS ALREADY UPLOADED ANOTHER ENTRY
		//**********************************************************
		/*if ($theuploads = 'Array') { //temp
			echo 'You have already voted for the competition';
		
		} else {*/
		
		
		
		
		
		//*****************************************************************
		//  Check the File size
		//*****************************************************************
		$updat = $this->data['Upload'][0]['file']['size'];
		$file_max_size = 999999;
		if ($updat > $file_max_size) { //size in bytes
			echo '<br />';
			echo 'This file is too big';
			
		} else {
			
	
		
		
		
		//******************************************************
		//If filetype is now allowed or empty give an error
		//******************************************************
		$updat2 = $this->data['Upload'][0]['file']['size'];
		$file_empty_size = 0;
		if ($updat2 == $file_empty_size) { //size in bytes
			
			echo '<br />';
			echo 'Upload or file cannot be empty';
			
					
            
			
		} else {
			
	
		
		
		
		//**********************************************
		//	Check if filetype is allowed
		//**********************************************
		$accepted_file_types = array (
		
									  "application/pdf",
									  "application/msword",
									  "text/plain",
									  "text/rtf",
									  "image/gif",
									  "image/jpeg",
									  "application/x-zip-compressed", 
									  "image/jpg", 
									  "image/pjpeg",
									  "image/tiff",
									  "image/bmp",
									  "image/psd"
									  
									 );
		
		
		if (!in_array(strtolower($this->data['Upload'][0]['file']['type']), $accepted_file_types)) {
		
			echo '<br />';
			echo 'File type not allowed!';
			
		
		} 
			

		

		if($this->Upload->save($data, array('validate'=>false))) { // not validate now
		    echo 'Upload has been Saved!';	
			if(!$this->FileUpload->upload($this->data['Upload'][0]['file'])) {
			$this->Upload->delete($this->Upload->id); // remove the DB entry because there were upload errors
			$this->redirect('/'); //Redirect after saving
		}
		}
		
		}}
		
		
		
		
		}
		}
		}
		

?>

//component code

<?php

class FileUploadComponent extends Object {
      var $components = array('RequestHandler');
	  

  
      protected $folder;
      protected $destination;
	  protected $fullpath;
      
      function upload($data) {            
            
            if(!is_dir($this->fullpath)) 
        { 
			
			$this->folder = date('Y-m-d_H-i-s');
            $tempdest  = 'img/uploads/';
          
            $this->fullpath = $tempdest;
			
			$this->destination = $this->fullpath.'/'.$this->folder.'-'.$data['name'];
			
            if(move_uploaded_file($data['tmp_name'], $this->destination)) {
                  
                  return true;
            }  
            return false;
      }
  }

           

  public function getDestination() {
    return $this->destination;
  }

  public function getFolder() {
    return $this->folder;
  }
  
    public function getFullpath() {
    return $this->fullpath;
  }
}



?>

Open in new window

0
Comment
Question by:error77
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 34154414
Sorry, but your question is not clear enogh to be answered.  To use getimage size, one has simply to do this:

list($width,$height)=getimagesize($imageName);

In your case you could do this

list($width,$height)=getimagesize($this->data['Upload'][0]['file']['name']);

But about integration with your code, this depends on what you want to do once you have getted image size...

Cheers
0
 

Author Comment

by:error77
ID: 34154557
Ok trying the following:

        $thePath = 'http://'.$_SERVER['SERVER_NAME'].''.$this->webroot.'img/uploads/';
            $theFilname = $test.'-'.$this->data['Upload'][0]['file']['name'];
            $full_path = $thePath.''.$theFilname;
            echo $full_path; //Returns the full path to the image  ... tested on the image IS there.
            
            
            //Then finally
            
            list($width, $height, $type, $attr) = getimagesize($full_path);
            echo "Image width " .$width;
            echo "<BR>";
            echo "Image height " .$height;
            echo "<BR>";
            echo "Image type " .$type;
            echo "<BR>";
            echo "Attribute " .$attr;
            
            I'm getting No Values on $width or $height or $type or $attr ...
            
            Any ideas why please? The image path is right and the image IS actually there :o/
            
            thankstrying the following:

        $thePath = 'http://'.$_SERVER['SERVER_NAME'].''.$this->webroot.'img/uploads/';
            $theFilname = $test.'-'.$this->data['Upload'][0]['file']['name'];
            $full_path = $thePath.''.$theFilname;
            echo $full_path; //Returns the full path to the image  ... tested on the image IS there.
            
            
            //Then finally
            
            list($width, $height, $type, $attr) = getimagesize($full_path);
            echo "Image width " .$width;
            echo "<BR>";
            echo "Image height " .$height;
            echo "<BR>";
            echo "Image type " .$type;
            echo "<BR>";
            echo "Attribute " .$attr;
            
            I'm getting No Values on $width or $height or $type or $attr ...
            
            Any ideas why please? The image path is right and the image IS actually there :o/
            
            thanks
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 34154618
It seems there are no errors in your code. Please, put at the top of your script this line:

error_reporting(E_ALL);

As said in php.net "If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE." So, if in your php.ini error_messages is set to none, you don't receive any message.

Let me know results.

Cheers
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

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

 

Author Comment

by:error77
ID: 34154773
Yeah, I've got it to report all errors but I'm still not getting any :o/

This is really strange
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34154855
From my teaching library.  As you can see, the $original_image_url string is the file name relative to the current working directory.  In this case, the cwd is the web root.
<?php // RAY_resize_and_crop.php
error_reporting(E_ALL);

// RESIZE AN IMAGE PROPORTIONALLY AND CROP CENTERED

function resize_and_crop($original_image_url, $thumb_image_url, $thumb_w, $thumb_h, $quality=75)
{
    // ACQUIRE THE ORIGINAL IMAGE: http://us3.php.net/manual/en/function.imagecreatefromjpeg.php
    $original = imagecreatefromjpeg($original_image_url);
    if (!$original) return FALSE;

    // GET ORIGINAL IMAGE DIMENSIONS
    list($original_w, $original_h) = getimagesize($original_image_url);

    // RESIZE IMAGE AND PRESERVE PROPORTIONS KEEPING AS MUCH OF THE IMAGE AS POSSIBLE
    $thumb_w_resize = $thumb_w;
    $thumb_h_resize = $thumb_h;
    if ($original_w > $original_h)
    {
        $thumb_h_ratio  = $thumb_h / $original_h;
        $thumb_w_resize = (int)round($original_w * $thumb_h_ratio);
    }
    else
    {
        $thumb_w_ratio  = $thumb_w / $original_w;
        $thumb_h_resize = (int)round($original_h * $thumb_w_ratio);
    }
    if ($thumb_w_resize < $thumb_w)
    {
        $thumb_h_ratio  = $thumb_w / $thumb_w_resize;
        $thumb_h_resize = (int)round($thumb_h * $thumb_h_ratio);
        $thumb_w_resize = $thumb_w;
    }

    // CREATE THE PROPORTIONAL IMAGE RESOURCE
    $thumb = imagecreatetruecolor($thumb_w_resize, $thumb_h_resize);
    if (!imagecopyresampled($thumb, $original, 0,0,0,0, $thumb_w_resize, $thumb_h_resize, $original_w, $original_h)) return FALSE;

    // ACTIVATE THIS TO STORE THE INTERMEDIATE IMAGE
    // imagejpeg($thumb, 'RAY_temp_' . $thumb_w_resize . 'x' . $thumb_h_resize . '.jpg', 100);

    // CREATE THE CENTERED CROPPED IMAGE TO THE SPECIFIED DIMENSIONS
    $final = imagecreatetruecolor($thumb_w, $thumb_h);

    $thumb_w_offset = 0;
    $thumb_h_offset = 0;
    if ($thumb_w < $thumb_w_resize)
    {
        $thumb_w_offset = (int)round(($thumb_w_resize - $thumb_w) / 2);
    }
    else
    {
        $thumb_h_offset = (int)round(($thumb_h_resize - $thumb_h) / 2);
    }

    if (!imagecopy($final, $thumb, 0,0, $thumb_w_offset, $thumb_h_offset, $thumb_w_resize, $thumb_h_resize)) return FALSE;

    // STORE THE FINAL IMAGE - WILL OVERWRITE $thumb_image_url
    if (!imagejpeg($final, $thumb_image_url, $quality)) return FALSE;
    return TRUE;
}

// USE CASE
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_100x100.jpg', 100, 100);
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_200x100.jpg', 200, 100);
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_200x300.jpg', 200, 300);

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34154889
So I think the strategy you want to use is to store the image on your file system first, then use getImageSize() with a relative URL after you have moved the file.

HTH, ~Ray
0
 

Author Comment

by:error77
ID: 34154891
I'm using the full path just to be on the sure side and I am actually testing that the image is there too.

All is ok except that the function is not returning anything :o/
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34154910
If you completed the upload process without errors and move_uploaded_file() succeeded, the image is there and no further tests are needed.  Then you can use the relative URL.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34154939
This comment might help explain part of the issue.
http://us3.php.net/manual/en/function.getimagesize.php#87188

Also, are you CERTAIN you are reporting all the errors, warnings and notices?  Some frameworks have their own assumptions about error reporting, and it's not what you need.  To be sure, you probably want to add these lines to the code IMMEDIATELY before the function call.

ini_set('display_errors', TRUE);
error_reporting(E_ALL);
0
 

Author Comment

by:error77
ID: 34155007
I'm started testing other images and the code is actually working but only on some images (some gifs, some jpgs, some png's etc )  ... any ideas why?

thanks

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34155108
Please post the full URLs of some working images and some that do not work, thanks.  I'll take a look.
0
 
LVL 7

Accepted Solution

by:
Vimal DM earned 500 total points
ID: 34155996
Hai,

Just get the below code it is working fine  - there are three functions

1) Is to upload the file
2) Is to resize the image or file
3) Is to create the quality image according to the old once

      
      function upload_image($name, $uploaddir) {
            $filevalue = $_FILES[$name]['name'];

            $tempfile = $_FILES[$name]["tmp_name"];
      
            $type=$_FILES[$name]['type'];
      if($type == "image/jpeg" || $type == "image/gif" || $type == "image/pjpeg" || $type == "image/png" || $type == "image/x-png" || $type =="image/jpg"|| $type =="video/x-ms-wmv" ||$type =="video/x-ms-avi") {
            $location       = strrpos($filevalue, ".");
            $startfile       = substr($filevalue, "0", $location);
            $ext             = substr($filevalue, $location);
            $filevalue       = $startfile.$ext;
            $id = 0;

            while(file_exists($uploaddir."".$filevalue)) {
                  $id++;
                  $filevalue = $startfile.$id.$ext;
            }
            
            $src_file = $uploaddir."".$filevalue;

            if (move_uploaded_file($tempfile, $uploaddir."/".$filevalue)) {
                   resize_image($uploaddir,$filevalue);
                  @chmod($uploaddir."/".$filevalue, 0775);
            }
            return $filevalue;
      } else {
            return false;
      }
      }// end funciton

      function resize_image($src_path, $src_filename)
      {
            $src_file = $src_path."/".$src_filename;
            //create thumnail image
            if(PIC_THUMB_SIZE <1)
                  $pic_width = 178;
            else
                  $pic_width = PIC_THUMB_SIZE;
                  
            $thumb_file = $src_path."/".PIC_THUMB_NAME.$src_filename;
            $result1 = create_image($src_file, $thumb_file, $pic_width);
            return $result;      
      }//end function


      //function to resize and create photo on specified width
      //file name should be with path name
      function create_image($src_file, $dest_file, $picture_width)
      {
            define("GIS_GIF", 1);
            define("GIS_JPG", 2);
            define("GIS_PNG", 3);
            //$picture_width = 400;

            if (!function_exists('imagecreatefromjpeg')) {
                  echo '<br>'.'PHP running on your server does not support the GD image library, check with your webhost if GD Library or ImageMagick is installed';
                  echo "<br><br><br><br><br><br>";
                  return false;
            }

            // 1. check file type is allowed
        $imginfo = getimagesize($src_file);
        if (max($imginfo[0], $imginfo[1]) > $CONFIG['picture_width'] && !file_exists($src_file)) {
            }
      
            if ($imginfo == null)
                  return false;
                  // GD can only handle JPG & PNG images
            if ($imginfo[2] != GIS_JPG && $imginfo[2] != GIS_PNG ) {
                  copy($src_file,$dest_file);
                  chmod($dest_file, octdec('0775'));
                  echo "GD file type error - not supported";
                  return false;
            }
            // height/width
            $srcWidth = $imginfo[0];
            $srcHeight = $imginfo[1];
      
            $ratio = max($srcWidth, $srcHeight) / $picture_width;
            
            $ratio = max($ratio, 1.0);
            $destWidth = (int)($srcWidth / $ratio);
            $destHeight = (int)($srcHeight / $ratio);

            if ($imginfo[2] == GIS_JPG)
                  $src_img = imagecreatefromjpeg($src_file);
            else
                  $src_img = imagecreatefrompng($src_file);
            if (!$src_img) {
                  echo 'invalid_image';
                  return false;
            }

         $dst_img = imagecreatetruecolor($destWidth, $destHeight);
         imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);

            //$dst_img = imagecreate($destWidth, $destHeight);
            //imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
            
            imagejpeg($dst_img, $dest_file, 100);
            imagedestroy($src_img);
            imagedestroy($dst_img);
            
            // Set mode of uploaded picture
            chmod($dest_file, octdec('0775'));
            // We check that the image is valid
            $imginfo1 = getimagesize($dest_file);
            if ($imginfo1 == null) {
                  echo 'resize_failed';
                  @unlink($dest_file);
                  return false;
            } else {
                  //echo "<img src='$dest_file'>";
                  //echo "<img src='$src_file' width='$destWidth' height='$destHeight' ><br>";
                  return true;
            }

      }//end function

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34156235
Not sure that it matters to this question, but you can get the file extension like this:

            $fileext = end(explode('.', $filename);

Would love to see the full URLs of some working images and some that do not work.
0
 

Author Closing Comment

by:error77
ID: 34186100
Thanks
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Suggested Solutions

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

733 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