Home  >  Article  >  Backend Development  >  Simple example of uploading files in php

Simple example of uploading files in php

WBOY
WBOYOriginal
2016-07-25 08:56:36992browse
This article introduces a simple example of file upload in PHP. Friends in need can refer to it.

Share a piece of PHP code to implement file upload. Mainly learn how to receive uploaded data in PHP, including the usage of enctype="multipart/form-data", move_uploaded_file, etc.

1, Simple example of uploading files in 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. Code to detect whether the uploaded file exists

<?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 {
   
}?>


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