php上传文件的简单示例

发布时间:2020-05-24编辑:脚本学堂
本文介绍下,php实现文件上传的简单例子,有需要的朋友可以参考下。

分享一段php实现文件上传的代码,主要学习下在php中接收上传数据的方法,包括enctype="multipart/form-data"、move_uploaded_file等的用法。

1,php上传文件的简单示例

<?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { ?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" enctype="multipart/form-data">
<input type="file" name="document"/>
<input type="submit" value="上传文件"/>
</form>
<?php } else { 
    if (isset($_FILES['document']) &&
    ($_FILES['document']['error'] == UPLOAD_ERR_OK)) {
        $newPath = '/tmp/' . basename($_FILES['document']['name']);
        if (move_uploaded_file($_FILES['document']['tmp_name'], $newPath)) {
            print "File saved in $newPath";
        } else {
            print "Couldn't move file to $newPath";
        }
    } else {
        print "No valid file uploaded.";
    }
}
?>

2,检测上传文件是否存在的代码

<?php
/**
* 通过$_FILES['file']['tmp_name']检查上传文件存在与否
* by www.jb200.com
*/
if (!is_uploaded_file($_FILES['upload_file']['tmp_name'])) {
    $error = "You must upload a file!";
    unlink($_FILES['upload_file']['tmp_name']);
}
else {
   
}?>