php文件上传

来源:互联网 发布:java适配器模型 编辑:程序博客网 时间:2024/06/03 14:10

test1.html

<html><head><title>文件上传</title><meta charset="utf-8"></head><body><form action="test2.php" method="post" enctype="multipart/form-data" name="form1"><input type="file" name="file"><input type="submit" name="submit" value="上传"></form></body</html>

entype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
mutipart/form-date 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。


test2.php

<?phpheader("Content-Type: text/html; charset=utf-8");//得到一个目录file来放置上传的文件$dirname = "file";if(is_dir($dirname))    echo "目录file已存在";else {    mkdir("file");    echo "创建目录file成果";}$max_file_size = 500000;//设置上传文件大小$updir= "file/";if($_FILES["file"]["name"]) {    $file_name=$_FILES["file"]["name"];    $type=$_FILES["file"]["type"];    $size=$_FILES["file"]["size"];    $tmp_name=$_FILES["file"]["tmp_name"];    if ($size > $max_file_size) {        echo "<script>          //javascript代码,弹出警告并返回。          alert('文件大于500K');window.history.back();          </script>";    }    //限制上传文件,仅允许.JPEG文件    if ($type != "image/jpeg") {        echo "<script>          alert('文件类型错误');window.history.back();          </script>";    }    if (move_uploaded_file($tmp_name, $updir.$file_name)) {        echo "<script>alert('上传成功')</script>";    }}

move_uploaded_file(file,newloc)
file
必需。规定要移动的文件。
newloc
必需。规定文件的新位。

原理:

文件上传后,首先被存储于‘服务器得临时目录中,PHP将获得一个$_FILE的全局变量,上传后得文件保存在此变量中。

1 0
原创粉丝点击