Jump to content

upload image file using php


sssrr

Recommended Posts

I have a flash application that calls php script to do the image file upload and save the image in jpg format in thumbnail size. I swear it worked at one time, and then as I tried to figure out how to covert other image formats that are not currently built-in in php library (createimagefrom... functions), I played around with it a little bit, then it doesn't upload file any more!!! What I got, is that NONE of the image files is saved in my designated image folders, subsequently the flash application comes up with a broken image link.  :confused: PLEASE HELP! MANY THANKS!

 

Here's the relevant flash code:

		private function uploadFiles():void
		{
			var curTime:Date = new Date();
			timeStamp = curTime.valueOf().toString();
			var variables:URLVariables = new URLVariables("timeStamp=" + timeStamp);

				var request:URLRequest = new URLRequest(ModelLocator.getInstance().serverPath+"uploadArtImages.php");
			request.method = URLRequestMethod.POST;
			request.data = variables;
			file.upload(request);
				Application.application.showLoading();
		}

Here's my php script: (it's really a simple script, a big chunk of it is just some functions that does error checking and image conversions)

 

<?php

$timeStamp = $_POST['timeStamp'];
$file = $_FILES['Filedata'];
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$fileSize = $file['size'];

$errorCode = 0; //0: success
$allowedExtensions = array("jpg", "bmp", "png", "gif", "tif", "ps", "eps", "pdf");
$mime = array('image/gif' => 'gif',
                  'image/jpeg' => 'jpg',
                  'image/png' => 'png',
                  'application/x-shockwave-flash' => 'swf',
                  'image/psd' => 'psd',
                  'image/bmp' => 'bmp',
                  'image/tiff' => 'tif',
                  'image/jp2' => 'jp2',
                  'image/iff' => 'iff',
                  'image/vnd.wap.wbmp' => 'bmp',
                  'image/xbm' => 'xbm',
                  'image/vnd.microsoft.icon' => 'ico');

public function imagecreatefrombmp($p_sFile)
{
        //    Load the image into a string
        $file    =    fopen($p_sFile,"rb");
        $read    =    fread($file,10);
        while(!feof($file)&&($read<>""))
            $read    .=    fread($file,1024);
       
        $temp    =    unpack("H*",$read);
        $hex    =    $temp[1];
        $header    =    substr($hex,0,108);
       
        //    Process the header
        //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
        if (substr($header,0,4)=="424d")
        {
            //    Cut it in parts of 2 bytes
            $header_parts    =    str_split($header,2);
           
            //    Get the width        4 bytes
            $width            =    hexdec($header_parts[19].$header_parts[18]);
           
            //    Get the height        4 bytes
            $height            =    hexdec($header_parts[23].$header_parts[22]);
           
            //    Unset the header params
            unset($header_parts);
        }
       
        //    Define starting X and Y
        $x                =    0;
        $y                =    1;
       
        //    Create newimage
        $image            =    imagecreatetruecolor($width,$height);
       
        //    Grab the body from the image
        $body            =    substr($hex,108);

        //    Calculate if padding at the end-line is needed
        //    Divided by two to keep overview.
        //    1 byte = 2 HEX-chars
        $body_size        =    (strlen($body)/2);
        $header_size    =    ($width*$height);

        //    Use end-line padding? Only when needed
        $usePadding        =    ($body_size>($header_size*3)+4);
       
        //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
        //    Calculate the next DWORD-position in the body
        for ($i=0;$i<$body_size;$i+=3)
        {
            //    Calculate line-ending and padding
            if ($x>=$width)
            {
                //    If padding needed, ignore image-padding
                //    Shift i to the ending of the current 32-bit-block
                if ($usePadding)
                    $i    +=    $width%4;
               
                //    Reset horizontal position
                $x    =    0;
               
                //    Raise the height-position (bottom-up)
                $y++;
               
                //    Reached the image-height? Break the for-loop
                if ($y>$height)
                    break;
            }
           
            //    Calculation of the RGB-pixel (defined as BGR in image-data)
            //    Define $i_pos as absolute position in the body
            $i_pos    =    $i*2;
            $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
            $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
            $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);
           
            //    Calculate and draw the pixel
            $color    =    imagecolorallocate($image,$r,$g,$b);
            imagesetpixel($image,$x,$height-$y,$color);
           
            //    Raise the horizontal position
            $x++;
        }
       
        //    Unset the body / free the memory
        unset($body);
       
        //    Return image-object
        return $image;
}

function ValidateImageFile($input_file, &$width, &$height, &$type) {
  global $allowedExtensions;
  global $mime;
  global $errorCode;
  
  $errorCode = 0; //reset
  $width = 0;
  $height = 0;
  $type = 0;
  $file_info = getimagesize($input_file['tmp_name']);
  if(!$file_info || empty($file_info)) { // No Image?
    //$error = "The uploaded file doesn't seem to be an image.";
    $errorCode = 1;
    return FALSE;
  } else { // An Image? check extension
    // Get File Extension (if any)
    $file_name = $input_file['name'];
    $dotExt = strrchr($file_name, ".");
    if (!$dotExt) { //no extension found
    	$errorCode = 2;
    	return FALSE;
    } else {
  	  $ext = strtolower(substr($dotExt, 1));
  	  $ext = ($ext == 'jpeg') ? 'jpg' : $ext; //convert jpeg to jpg
  	  $ext = ($ext == 'tiff') ? 'tif' : $ext;
      if(!in_array($ext, $allowedExtensions)) { //has extension, but invalid
        //$error .= "You must upload a file with one of the following extensions: ".$exts;
        $errorCode = 2;
        return FALSE;
      } else {
        $file_mime = $file_info['mime'];        
        //if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2') {
        //  $extension = $ext;
        //} else {
        //  $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
        //}
        //if(!$extension) {
        //  $extension = '';
        //  $file_name = str_replace('.', '', $file_name);
        //}
        if (strcmp($mime[$file_mime], $ext)) {
        	$errorCode = 3;
        	return FALSE; //strcmp non zero, mime type doesn't match ext, error!
        }
    }
  }
}
  $width = $file_info[0];
  $height = $file_info[1];
  $type = $file_info[2];
  return TRUE;
}

//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
function ConvertPic($w_dst, $h_dst, $new_img, $file_src, $w_src, $h_src, $type_src)
{
ini_set('memory_limit', '100M');   //  handle large images
   unlink($new_img);         //  remove old images if present
  
   if ($w_src > $w_dst || $h_src > $h_dst) {
   $ratio = $w_src/$h_src;
   if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}
  } else {
  	$w_dst = $w_src;
  	$h_dst = $h_src;
  }

   switch ($type_src)
     {case 1: //IMAGETYPE_GIF:   // 1:  gif -> jpg
        $img_src = imagecreatefromgif($file_src);
        break;
      case 2: //IMAGETYPE_JPEG:   // 2:  jpeg -> jpg
        $img_src = imagecreatefromjpeg($file_src);
        break;
      //case IMAGETYPE_JPEG2000:
      //  $img_src = imagecreatefromjpeg($file_src);
      //  break;
      case 3: //IMAGETYPE_PNG:  // 3:  png -> jpg
        $img_src = imagecreatefrompng($file_src);
        break;
      case IMAGETYPE_WBMP: // wbmp -> jpg
        $img_src = imagecreatefromwbmp($file_src);
        break;
      case IMAGETYPE_XBM:
        $img_src = imagecreatefromxbm($file_src);
        break;
      case IMAGETYPE_BMP:
        $img_src = imagecreatefrombmp($file_src);
        break;
     }
   $img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample
  
   imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
   imagejpeg($img_dst, $new_img);    //  save new image, always jpg

   imagedestroy($img_src);       
   imagedestroy($img_dst);
}

$uploadFileName = '';
if($file['error'] == UPLOAD_ERR_OK) {
$width = 0;
$height = 0;
$type = 0;
$dir = "./art_images/";
$dirThumb = "./art_images_thumb/";	
  if(ValidateImageFile($file, $width, $height, $type)) {
    # Do uploading here
    // make a unique filename for the uploaded file and check it is not already
    // taken... if it is already taken keep trying until we find a vacant one
    // sample filename: 1140732936-filename.jpg
    //$now = time();
    //$uploadFileName = $now.'-'.$fileName;
    //while(file_exists($dir.$uploadFileName)) {
    //  $now++;
    //  $uploadFileName = $now.'-'.$fileName;
    //}
    $uploadFileName = $timeStamp . '-' . $fileName;
    unlink($dir . $uploadFileName); //make sure there's no exist file
    if (!move_uploaded_file($tempFile, $dir . $uploadFileName)) {
    	//echo "cannot move file, nothing uploaded";
    	$errorCode = 4;
    } else {
    	ConvertPic(150, 150, $dirThumb . $uploadFileName, $dir . $uploadFileName, $width, $height, $type);
    	//echo $uploadFileName;
    }
  } else {
  	//echo "file not valid" . $errorCode;
  }
} else {
//echo "upload error";
$errorCode = 5;
}

?>

Link to comment
https://forums.phpfreaks.com/topic/212421-upload-image-file-using-php/
Share on other sites

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.