1. 程式人生 > >【PHP】上傳影象的處理

【PHP】上傳影象的處理

<?
if(isset($_POST['send_image']))//當接到由表單發來的資料send_image時
 {
  if(is_uploaded_file( $_FILES['file']['tmp_name']))//是否上傳照片
   {
   list($width, $height, $type, $attr) = getimagesize($_FILES['file']['tmp_name']);//獲取上傳檔案的屬性
   if ( $type==1 )//判斷型別
   {
    $type=".gif";
   }
   else if( $type==2 )
   {
    $type=".jpg";
   }
   else if( $type==3 )
   {
    $type=".png";
   }
   else if( $type==6 )
   {
    $type=".bmp";
   }
   else
   {
    echo "您只能上傳以下型別圖片:jpg,gif,bmp,png!";
   }
   
   if ( ($width>100) || ($height>100 ))//判斷影象檔案的長寬
   {
    echo "圖片尺寸過大!";
   }
   else if ( $_FILES['image']['size']>IMAGE_MAX_SIZE)//檔案尺寸判斷(大小)
   {
    echo "圖片過大!";
   }
    else
    {
      do
      {
     $name=random(10).$type;
     if (!file_exists("./test/")){mkdir("./test/");} //判斷儲存圖片的路徑是否存在,如果不存在則建立一個
     $uploaddir = "./test/";
        $uploadfile=$uploaddir.$name;//最終的檔案儲存為$uploadfile(路徑+檔名)
      }
      while(file_exists($uploadfile));
      if(is_uploaded_file($_FILES['file']['tmp_name']))
      {
        if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile))
        {
      echo "成功!";
        }
      }
    }
  }
  else
  {
   echo "您還沒有選擇圖片檔案!";
  }
 }
?>


<?

function random($length)//取得指定長度的隨機字串
  {
    $hash = 'CR-';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
    return $hash;
  }

?>