Heim  >  Artikel  >  Backend-Entwicklung  >  php上传文件的简单示例

php上传文件的简单示例

WBOY
WBOYOriginal
2016-07-25 08:56:36957Durchsuche
本文介绍下,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 bbs.it-home.org
*/
if (!is_uploaded_file($_FILES['upload_file']['tmp_name'])) {
    $error = "You must upload a file!";
    unlink($_FILES['upload_file']['tmp_name']);
}
else {
   
}?>


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn