PHP? ??? MySql ??????? ??? ?? ???(3)
? ????? ? ?? ??? ???? ??????? ???? ?? ?? ??? ?? ??? ?????.
??, ??? ????? ???? 123.jpg, abc.png ?? ?? ??? ????.
?? .jpg, .png ???? ???? ???.
? ?? ??? ???? ??? ???? ?????. ?? ?? ??
strrchr() ??? ?? ??? ??? ????? ???? ???? ?? ?? ???? ??? ???? ?? ??? ?????.
substr() ??? ???? ??? ?????.
<?php function fileext($filename) { return substr(strrchr($filename, '.'), 1); } ?>
fileext? ??? ??? ?? ????, filename? ?? ?? ?????.
?? ??????? ??? ? ?? ??? ???????
??? ??? ??? ??? ???? ???
??? CR-? ???? A-Z, a-z, 0-9?? ? ??? ???? ???? ???? ? ?? ?? ???? ?????
?? ??: strlen() ? ??? ???? ??? ?????.
<?php function random($length) { $hash = 'CR-'; $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; $max = strlen($chars) - 1; mt_srand((double)microtime() * 1000000); for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; } ?>
?? ?? ?? ??
<?php $filename=explode(".",$_FILES['file']['name']); do{ $filename[0]=random(10); //設(shè)置隨機(jī)數(shù)長(zhǎng)度 $name=implode(".",$filename); $uploadfile = $uploaddir.$name; } while(file_exists($uploadfile)); ?>
explode() ??? ???? ??? ?????.
implode() ??? ?? ??? ??? ???? ?????.
????? ?? ??? PHP ?? upload.php? ??????(??? ??? ??? ?? ?? ??)
<?php $uploaddir = "upfiles/";//設(shè)置文件保存目錄 注意包含/ $type=array("jpg","gif","bmp","jpeg","png");//設(shè)置允許上傳文件的類型 //獲取文件后綴名函數(shù) function fileext($filename) { return substr(strrchr($filename, '.'), 1); } //生成隨機(jī)文件名函數(shù) function random($length) { $hash = 'CR-'; $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; $max = strlen($chars) - 1; mt_srand((double)microtime() * 1000000); for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; } $a = strtolower(fileext($_FILES['file']['name'])); //判斷文件類型 if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type)) { $text=implode(",",$type); echo "您只能上傳以下類型文件: ",$text,"<br>"; } //生成目標(biāo)文件的文件名 else{ $filename=explode(".",$_FILES['file']['name']); do{ $filename[0]=random(10); //設(shè)置隨機(jī)數(shù)長(zhǎng)度 $name=implode(".",$filename); $uploadfile = $uploaddir.$name; } while(file_exists($uploadfile)); if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)) { if(is_uploaded_file($_FILES['file']['tmp_name'])) { echo "上傳失敗!"; } else {//輸出圖片預(yù)覽 echo "<tr><td>您的文件已經(jīng)上傳完畢 上傳圖片預(yù)覽: <br><img src='$uploadfile'></td></tr>"; echo "<tr><td><a href='tu2.php'style='margin-left: 3%;'>繼續(xù)上傳</a></td></tr>"; } //可以在前端HTML頁(yè)面顯示上傳的文件預(yù)覽 } } ?>