php 文件上傳類與圖片處理類的實現(xiàn)代碼
Jul 25, 2016 am 09:00 AM
為大家介紹php開發(fā)的文件上傳類與圖片處理類,有需要的朋友,可以參考學習下。
php實現(xiàn)文件的上傳比較簡單,如果再有一個高效的php文件上傳類,那真是如虎添翼,不想飛都不行。 那么,那么,如果再有一個好用的圖片處理類呢,可以縮減圖片,可以加水印,是不是更爽呢? 小聲地告訴你,那是必須的,哈哈。 來看今天的php 教程吧。 1、文件上傳類的代碼 <?php /** * 文件上傳類 * by bbs.it-home.org */ class uploadFile { public $max_size = '1000000';//設置上傳文件大小 public $file_name = 'date';//重命名方式代表以時間命名,其他則使用給予的名稱 public $allow_types;//允許上傳的文件擴展名,不同文件類型用“|”隔開 public $errmsg = '';//錯誤信息 public $uploaded = '';//上傳后的文件名(包括文件路徑) public $save_path;//上傳文件保存路徑 private $files;//提交的等待上傳文件 private $file_type = array();//文件類型 private $ext = '';//上傳文件擴展名 /** * 構造函數(shù),初始化類 * @access public * @param string $file_name 上傳后的文件名 * @param string $save_path 上傳的目標文件夾 */ public function __construct($save_path = './upload/',$file_name = 'date',$allow_types = '') { $this->file_name = $file_name;//重命名方式代表以時間命名,其他則使用給予的名稱 $this->save_path = (preg_match('/\/$/',$save_path)) ? $save_path : $save_path . '/'; $this->allow_types = $allow_types == '' ? 'jpg|gif|png|zip|rar' : $allow_types; } /** * 上傳文件 * @access public * @param $files 等待上傳的文件(表單傳來的$_FILES[]) * @return boolean 返回布爾值 */ public function upload_file($files) { $name = $files['name']; $type = $files['type']; $size = $files['size']; $tmp_name = $files['tmp_name']; $error = $files['error']; switch ($error) { case 0 : $this->errmsg = ''; break; case 1 : $this->errmsg = '超過了php.ini中文件大小'; break; case 2 : $this->errmsg = '超過了MAX_FILE_SIZE 選項指定的文件大小'; break; case 3 : $this->errmsg = '文件只有部分被上傳'; break; case 4 : $this->errmsg = '沒有文件被上傳'; break; case 5 : $this->errmsg = '上傳文件大小為0'; break; default : $this->errmsg = '上傳文件失??!'; break; } if($error == 0 && is_uploaded_file($tmp_name)) { //檢測文件類型 if($this->check_file_type($name) == FALSE){ return FALSE; } //檢測文件大小 if($size > $this->max_size){ $this->errmsg = '上傳文件<font color=red>'.$name.'</font>太大,最大支持<font color=red>'.ceil($this->max_size/1024).'</font>kb的文件'; return FALSE; } $this->set_save_path();//設置文件存放路徑 $new_name = $this->file_name != 'date' ? $this->file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//設置新文件名 $this->uploaded = $this->save_path.$new_name;//上傳后的文件名 //移動文件 if(move_uploaded_file($tmp_name,$this->uploaded)){ $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上傳成功!'; return TRUE; }else{ $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上傳失?。?; return FALSE; } } } /** * 檢查上傳文件類型 * @access public * @param string $filename 等待檢查的文件名 * @return 如果檢查通過返回TRUE 未通過則返回FALSE和錯誤消息 */ public function check_file_type($filename){ $ext = $this->get_file_type($filename); $this->ext = $ext; $allow_types = explode('|',$this->allow_types);//分割允許上傳的文件擴展名為數(shù)組 //echo $ext; //檢查上傳文件擴展名是否在請允許上傳的文件擴展名中 if(in_array($ext,$allow_types)){ return TRUE; }else{ $this->errmsg = '上傳文件<font color=red>'.$filename.'</font>類型錯誤,只支持上傳<font color=red>'.str_replace('|',',',$this->allow_types).'</font>等文件類型!'; return FALSE; } } /** * 取得文件類型 * @access public * @param string $filename 要取得文件類型的目標文件名 * @return string 文件類型 */ public function get_file_type($filename){ $info = pathinfo($filename); $ext = $info['extension']; return $ext; } /** * 設置文件上傳后的保存路徑 */ public function set_save_path(){ $this->save_path = (preg_match('/\/$/',$this->save_path)) ? $this->save_path : $this->save_path . '/'; if(!is_dir($this->save_path)){ //如果目錄不存在,創(chuàng)建目錄 $this->set_dir(); } } /** * 創(chuàng)建目錄 * @access public * @param string $dir 要創(chuàng)建目錄的路徑 * @return boolean 失敗時返回錯誤消息和FALSE */ public function set_dir($dir = null){ //檢查路徑是否存在 if(!$dir){ $dir = $this->save_path; } if(is_dir($dir)){ $this->errmsg = '需要創(chuàng)建的文件夾已經(jīng)存在!'; } $dir = explode('/', $dir); foreach($dir as $v){ if($v){ $d .= $v . '/'; if(!is_dir($d)){ $state = mkdir($d, 0777); if(!$state) $this->errmsg = '在創(chuàng)建目錄<font color=red>' . $d . '時出錯!'; } } } return true; } } ?> 2、圖片處理類的代碼 <?php /************************************************* * 圖片處理類 * * 可以對圖片進行生成縮略圖,打水印等操作 * 本類默認編碼為UTF8 如果要在GBK下使用請將img_mark方法中打中文字符串水印iconv注釋去掉 * * 由于UTF8漢字和英文字母大小(像素)不好確定,在中英文混合出現(xiàn)太多時可能會出現(xiàn)字符串偏左 * 或偏右,請根據(jù)項目環(huán)境對get_mark_xy方法中的$strc_w = strlen($this->mark_str)*7+5進 * 行調(diào)整 * 需要GD庫支持,為更好使用本類推薦使用GD庫2.0+ * * @author http://bbs.it-home.org *************************************************/ class uploadImg extends uploadFile { public $mark_str = 'bbs.it-home.org'; //水印字符串 public $str_r = 0; //字符串顏色R public $str_g = 0; //字符串顏色G public $str_b = 0; //字符串顏色B public $mark_ttf = './upload/SIMSUN.TTC'; //水印文字字體文件(包含路徑) public $mark_logo = './upload/logo.png'; //水印圖片 public $resize_h;//生成縮略圖高 public $resize_w;//生成縮略圖寬 public $source_img;//源圖片文件 public $dst_path = './upload/';//縮略圖文件存放目錄,不填則為源圖片存放目錄 /** * 生成縮略圖 生成后的圖 * @access public * @param integer $w 縮小后圖片的寬(px) * @param integer $h 縮小后圖片的高(px) * @param string $source_img 源圖片(路徑+文件名) */ public function img_resized($w,$h,$source_img = NULL){ $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果為空則默認為上次上傳的圖片 if(!is_file($source_img)) { //檢查源圖片是否存在 $this->errmsg = '文件'.$source_img.'不存在'; return FALSE; } $this->source_img = $source_img; $img_info = getimagesize($source_img); $source = $this->img_create($source_img); //創(chuàng)建源圖片 $this->resize_w = $w; $this->resize_h = $h; $thumb = imagecreatetruecolor($w,$h); imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);//生成縮略圖片 $dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //取得目標文件夾路徑 $dst_path = (preg_match('/\/$/',$dst_path)) ? $dst_path : $dst_path . '/';//將目標文件夾后加上/ if(!is_dir($dst_path)) $this->set_dir($dst_path); //如果不存在目標文件夾則創(chuàng)建 $dst_name = $this->set_newname($source_img); $this->img_output($thumb,$dst_name);//輸出圖片 imagedestroy($source); imagedestroy($thumb); } /** *打水印 *@access public *@param string $source_img 源圖片路徑+文件名 *@param integer $mark_type 水印類型(1為英文字符串,2為中文字符串,3為圖片logo,默認為英文字符串) *@param integer $mark_postion 水印位置(1為左下角,2為右下角,3為左上角,4為右上角,默認為右下角); *@return 打上水印的圖片 */ public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) { $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果為空則默認為上次上傳的圖片 if(!is_file($source_img)) { //檢查源圖片是否存在 $this->errmsg = '文件'.$source_img.'不存在'; return FALSE; } $this->source_img = $source_img; $img_info = getimagesize($source_img); $source = $this->img_create($source_img); //創(chuàng)建源圖片 $mark_xy = $this->get_mark_xy($mark_postion);//取得水印位置 $mark_color = imagecolorallocate($source,$this->str_r,$this->str_g,$this->str_b); switch($mark_type) { case 1 : //加英文字符串水印 $str = $this->mark_str; imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color); $this->img_output($source,$source_img); break; case 2 : //加中文字符串水印 if(!is_file($this->mark_ttf)) { //檢查字體文件是否存在 $this->errmsg = '打水印失?。鹤煮w文件'.$this->mark_ttf.'不存在!'; return FALSE; } $str = $this->mark_str; //$str = iconv('gbk','utf-8',$str);//轉換字符編碼 如果使用GBK編碼請去掉此行注釋 imagettftext($source,12,0,$mark_xy[2],$mark_xy[3],$mark_color,$this->mark_ttf,$str); $this->img_output($source,$source_img); break; case 3 : //加圖片水印 if(is_file($this->mark_logo)){ //如果存在水印logo的圖片則取得logo圖片的基本信息,不存在則退出 $logo_info = getimagesize($this->mark_logo); }else{ $this->errmsg = '打水印失敗:logo文件'.$this->mark_logo.'不存在!'; return FALSE; } $logo_info = getimagesize($this->mark_logo); if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //如果源圖片小于logo大小則退出 $this->errmsg = '打水印失?。涸磮D片'.$this->source_img.'比'.$this->mark_logo.'小!'; return FALSE; } $logo = $this->img_create($this->mark_logo); imagecopy ( $source, $logo, $mark_xy[4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]); $this->img_output($source,$source_img); break; default: //其它則為文字圖片 $str = $this->mark_str; imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color); $this->img_output($source,$source_img); break; } imagedestroy($source); } /** * 取得水印位置 * @access private * @param integer $mark_postion 水印的位置(1為左下角,2為右下角,3為左上角,4為右上角,其它為右下角) * @return array $mark_xy 水印位置的坐標(索引0為英文字符串水印坐標X,索引1為英文字符串水印坐標Y, * 索引2為中文字符串水印坐標X,索引3為中文字符串水印坐標Y,索引4為水印圖片坐標X,索引5為水印圖片坐標Y) */ private function get_mark_xy($mark_postion){ $img_info = getimagesize($this->source_img); $stre_w = strlen($this->mark_str)*9+5 ; //水印英文字符串的長度(px)(5號字的英文字符大小約為9px 為了美觀再加5px) //(12號字的中文字符大小為12px,在utf8里一個漢字長度為3個字節(jié)一個字節(jié)4px 而一個英文字符長度一個字節(jié)大小大約為9px // 為了在中英文混合的情況下顯示完全 設它的長度為字節(jié)數(shù)*7px) $strc_w = strlen($this->mark_str)*7+5 ; //水印中文字符串的長度(px) if(is_file($this->mark_logo)){ //如果存在水印logo的圖片則取得logo圖片的基本信息 $logo_info = getimagesize($this->mark_logo); } //由于imagestring函數(shù)和imagettftext函數(shù)中對于字符串開始位置不同所以英文和中文字符串的Y位置也有所不同 //imagestring函數(shù)是從文字的左上角為參照 imagettftext函數(shù)是從文字左下角為參照 switch($mark_postion){ case 1: //位置左下角 $mark_xy[0] = 5; //水印英文字符串坐標X $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐標Y $mark_xy[2] = 5; //水印中文字符串坐標X $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐標Y $mark_xy[4] = 5;//水印圖片坐標X $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y break; case 2: //位置右下角 $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐標Y $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐標Y $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y break; case 3: //位置左上角 $mark_xy[0] = 5; //水印英文字符串坐標X $mark_xy[1] = 5;//水印英文字符串坐標Y $mark_xy[2] = 5; //水印中文字符串坐標X $mark_xy[3] = 15;//水印中文字符串坐標Y $mark_xy[4] = 5;//水印圖片坐標X $mark_xy[5] = 5;//水印圖片坐標Y break; case 4: //位置右上角 $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X $mark_xy[1] = 5;//水印英文字符串坐標Y $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X $mark_xy[3] = 15;//水印中文字符串坐標Y $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X $mark_xy[5] = 5;//水印圖片坐標Y break; default : //其它默認為右下角 $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X $mark_xy[1] = $img_info[1]-5;//水印英文字符串坐標Y $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X $mark_xy[3] = $img_info[1]-15;//水印中文字符串坐標Y $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y break; } return $mark_xy; } /** * 創(chuàng)建源圖片 * @access private * @param string $source_img 源圖片(路徑+文件名) * @return img 從目標文件新建的圖像 */ private function img_create($source_img) { $info = getimagesize($source_img); switch ($info[2]){ case 1: if(!function_exists('imagecreatefromgif')){ $source = @imagecreatefromjpeg($source_img); }else{ $source = @imagecreatefromgif($source_img); } break; case 2: $source = @imagecreatefromjpeg($source_img); break; case 3: $source = @imagecreatefrompng($source_img); break; case 6: $source = @imagecreatefromwbmp($source_img); break; default: $source = FALSE; break; } return $source; } /** * 重命名圖片 * @access private * @param string $source_img 源圖片路徑+文件名 * @return string $dst_name 重命名后的圖片名(路徑+文件名) */ private function set_newname($sourse_img) { $info = pathinfo($sourse_img); $new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//將文件名修改為:寬_高_文件名 if($this->dst_path == ''){ //如果存放縮略圖路徑為空則默認為源文件同文件夾 $dst_name = str_replace($info['basename'],$new_name,$sourse_img); }else{ $dst_name = $this->dst_path.$new_name; } return $dst_name; } /** * 輸出圖片 * @access private * @param $im 處理后的圖片 * @param $dst_name 輸出后的的圖片名(路徑+文件名) * @return 輸出圖片 */ public function img_output($im,$dst_name) { $info = getimagesize($this->source_img); switch ($info[2]){ case 1: if(!function_exists('imagegif')){ imagejpeg($im,$dst_name); }else{ imagegif($im, $dst_name); } break; case 2: imagejpeg($im,$dst_name); break; case 3: imagepng($im,$dst_name); break; case 6: imagewbmp($im,$dst_name); break; } } } ?> 就是這些了,有關php文件上傳原理,大家有時間也可以看看,以更好地理解以上的代碼。 |

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

TOVERSIONAPHP-berasaskan-berasaskan, UseUrl-berasaskan Forversioningforclarityandeaseofrouting, separateVersionedcodetoavoidconflicts, decrecateoldversionswithclearCommunication, andconsidercustomheadershipshenershipshenershipshenershipshenershinlyhenershinlywenershinly

TosecurelyhandleAuthenticationandauthorizationInphp, ikuti: 1.alwayshashpasswordswithpassword_hash () andverifyUsingPassword_verify (), usePePreparedStatementStopreventsqlInjection, andStoreUserDatain $ _SessionAsLogin.2.implescureRoleRoleRoleRoleRole

Proseduralandobject-orientedprogramming (OOP) inphpdiffers significelyinstructure, kebolehgunaan semula, dandatahandling.1.ProceduralProgrammingusesFunctionsaganediediedieds, sesuai, pemodelan

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

Untuk mengendalikan muat naik fail dengan selamat di PHP, terasnya adalah untuk mengesahkan jenis fail, menamakan semula fail, dan menyekat kebenaran. 1. Gunakan finfo_file () untuk memeriksa jenis mime sebenar, dan hanya jenis tertentu seperti imej/jpeg dibenarkan; 2. Gunakan uniqid () untuk menghasilkan nama fail rawak dan simpannya dalam direktori akar bukan web; 3. Hadkan saiz fail melalui borang php.ini dan html, dan tetapkan kebenaran direktori ke 0755; 4. Gunakan Clamav untuk mengimbas malware untuk meningkatkan keselamatan. Langkah -langkah ini dengan berkesan menghalang kelemahan keselamatan dan memastikan bahawa proses muat naik fail adalah selamat dan boleh dipercayai.

Ya, PHP boleh berinteraksi dengan pangkalan data NoSQL seperti MongoDB dan Redis melalui sambungan atau perpustakaan tertentu. Pertama, gunakan pemacu MongoDBPHP (dipasang melalui PECL atau komposer) untuk membuat contoh pelanggan dan mengendalikan pangkalan data dan koleksi, penyisipan sokongan, pertanyaan, pengagregatan dan operasi lain; Kedua, gunakan perpustakaan predis atau lanjutan phpredis untuk menyambung ke REDIS, lakukan tetapan dan pengambilalihan nilai utama, dan mengesyorkan PHPREDI untuk senario berprestasi tinggi, sementara Predis mudah untuk penempatan pesat; Kedua-duanya sesuai untuk persekitaran pengeluaran dan didokumentasikan dengan baik.

Dalam PHP, perbezaan utama antara == dan == adalah ketat pemeriksaan jenis. == Penukaran jenis akan dilakukan sebelum perbandingan, contohnya, 5 == "5" pulangan benar, dan === meminta nilai dan jenis adalah sama sebelum benar akan dikembalikan, sebagai contoh, 5 === "5" mengembalikan palsu. Dalam senario penggunaan, === lebih selamat dan harus digunakan terlebih dahulu, dan == hanya digunakan apabila penukaran jenis diperlukan.

Kaedah menggunakan operasi matematik asas dalam PHP adalah seperti berikut: 1. Tanda tambahan menyokong bilangan bulat dan nombor terapung, dan juga boleh digunakan untuk pembolehubah. Nombor rentetan akan ditukar secara automatik tetapi tidak disyorkan kepada kebergantungan; 2. Tanda -tanda pengurangan - tanda, pembolehubah adalah sama, dan penukaran jenis juga terpakai; 3. Tanda -tanda pendaraban menggunakan tanda *, yang sesuai untuk nombor dan rentetan yang serupa; 4. Bahagian menggunakan / tanda, yang perlu mengelakkan pembahagian dengan sifar, dan perhatikan bahawa hasilnya mungkin nombor terapung; 5. Mengambil tanda modulus boleh digunakan untuk menilai angka ganjil dan bahkan, dan apabila memproses nombor negatif, tanda -tanda selebihnya selaras dengan dividen. Kunci untuk menggunakan pengendali ini dengan betul adalah untuk memastikan bahawa jenis data adalah jelas dan keadaan sempadan ditangani dengan baik.
