1.upload_file.php
<?php
//该文件负责获取上传的图片的扩展名和随机生成文件名
header("content-type:text/html;charset=utf-8");
/**
* 获取文件扩展名
*Enter description here ...
* @param unknown_type $filename
*/
function getFileName($filename){
//strrchr— 查找指定字符在字符串中的最后一次出现
return substr(strrchr($filename,‘.‘), 1);
}
/**
* 随机生成n位字符串
* Enterdescription here ...
* @param unknown_type $num
*/
function rand_str($num){
$str = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKOLP1234567890";
$str_len = strlen($str)-1;
//echo$str_len;
$s=‘‘;
for ($i = 0; $i < $num; $i++) {
$s.=$str[rand(0,$str_len)];
}
echo $s;
}
?>
2.index.html
<formaction="upload_file.php"method="post">
<inputtype="file" name="file1"/>
<inputtype="submit" value="上传"/>
</form>
3.deal_upload.php
<?php
header("content-type:text/html;charset=utf-8");
//引入获取上传文件的名称已经生成文件名的函数lib
require ‘upload_file.php‘;
//设置文件要保存的目录
$upload_dir = "files/";
if(!file_exists($upload_dir)){
mkdir($upload_dir);
}
//设置运行上传的文件类型
$type =array(‘jpg‘,‘png‘,‘gif‘,‘jpeg‘);
//in_array — 检查数组中是否存在某个值
if(!in_array(strtolower(getFileName($_FILES[‘file‘][‘name‘])),
$type)){
//implode,将数组联合成一个字符串
$text = implode(‘,‘, $type);
echo "<script>alert(‘文件类型只允许是{$text}‘);window.location=‘index.html‘;</script>";
}else{
//获取文件名称
$filename = explode(‘.‘, $_FILES[‘file‘][‘name‘]);
$filename[0] =rand_str(10);
$name =implode(‘.‘, $filename);
$uploadfile=$upload_dir.$name;
//is_uploaded_file — 判断文件是否是通过 HTTP POST上传的
if(is_uploaded_file($_FILES[‘file‘][‘tmp_name‘])){
//move_uploaded_file— 将上传的文件移动到新位置
if(move_uploaded_file($_FILES[‘file‘][‘tmp_name‘],$uploadfile)){
$file_path = getcwd().‘\\‘.$uploadfile; echo "<center> 您的文件上传完毕,上传图片预览:</center>";
echo "<img src=‘$uploadfile‘/><br/>";
echo "<a href=‘javascript:history.go(-1)‘>继续上传</a>";
}else{
echo "上传失败";
}
}
}
?>
felayman——PHP中图片上传到服务器