Home  >  Article  >  php教程  >  一个简单的PHP文件上传示例程序

一个简单的PHP文件上传示例程序

WBOY
WBOYOriginal
2016-05-25 16:47:48974browse

本文章来给各位初学者来介绍一个简单的PHP文件上传示例程序代码,有需要学习的朋友可进入参考参考.

实例代码如下:

<?php
// 定义提示函数
function alert($msg) {
    return &#39;<script type="text/javascript">alert("&#39; . $msg . &#39;");window.history.back(-1);</script>&#39;;
}
// 定义允许的文件类型
$allowType = array(
    &#39;image/jpeg&#39;,
    &#39;image/gif&#39;,
    &#39;image/jpg&#39;
);
// 定义路径,可以是绝对路径,或者相对路径都可以
$filePath = &#39;./uploadFileDir/&#39;;
// 接收表单信息 其中里边写的 file 值是 静态页form表单里的name值
$file = $_FILES[&#39;file&#39;];
// 第一步,判断上传的文件是否有错误
if ($file[&#39;error&#39;] !== 0) {
    exit(alert(&#39;文件上传错误&#39;));
}
// 第二步,判断文件大小,这里的102400是字节,换算为kb就是100kb
if ($file[&#39;size&#39;] > 102400) {
    exit(alert(&#39;文件过大&#39;));
}
// 第三步,判断文件类型
if (!in_array(mime_content_type($file[&#39;tmp_name&#39;]) , $allowType)) {
    exit(alert(&#39;文件类型错误&#39;));
}
// 第四步,判断路径是否存在,如果不存在则创建
if (!file_exists($filePath) && !mkdir($filePath, 0777, true)) {
    exit(alert(&#39;创建目录错误&#39;));
}
// 第五步,定义上传后的名字及路径
$filename = time() . &#39;_&#39; . $file[&#39;name&#39;];
// 第六步,复制文件
if (!copy($file[&#39;tmp_name&#39;], $filePath . $filename)) {
    exit(alert(&#39;上传文件出错,请稍候重试&#39;));
}
// 第七步,删除临时文件
unlink($file[&#39;tmp_name&#39;]);
// 提示上传成功
echo alert(&#39;恭喜,上传文件[&#39; . $filename . &#39;]成功!&#39;);
?>


教程网址:

欢迎收藏∩_∩但请保留本文链接。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn