PHP getimagesize function

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

error77Asked:
Who is Participating?
 
Vimal DMConnect With a Mentor Senior Software EngineerCommented:
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
 
Marco GasiFreelancerCommented:
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
 
error77Author Commented:
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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Marco GasiFreelancerCommented:
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
 
error77Author Commented:
Yeah, I've got it to report all errors but I'm still not getting any :o/

This is really strange
0
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
error77Author Commented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
error77Author Commented:
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
 
Ray PaseurCommented:
Please post the full URLs of some working images and some that do not work, thanks.  I'll take a look.
0
 
Ray PaseurCommented:
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
 
error77Author Commented:
Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.