PHP使用之上傳圖片到指定位置路徑儲存到資料庫的具體實現
阿新 • • 發佈:2019-02-16
<?php
$uploaddir = "upfiles/";//設定檔案儲存目錄 注意包含/
$type=array("jpg","gif","bmp","jpeg","png");//設定允許上傳檔案的型別
$patch="upload/";//程式所在路徑
//獲取檔案字尾名函式
function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
}
//生成隨機檔名函式
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>";
}
//生成目標檔案的檔名
else{
$filename=explode(".",$_FILES['file']['name']);
do
{
$filename[0]=random(10); //設定隨機數長度
$name=implode(".",$filename);
//$name1=$name.".Mcncc";
$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
{//輸出圖片預覽
echo "<center>您的檔案已經上傳完畢 上傳圖片預覽: </center><br><center><img src='$uploadfile'></center>";
echo "<br><center><a href='upload.htm'>繼續上傳</a></center>";
}
}
}
?>