PHP文件上传

PHP编程语言中的常见的$_FILES系统函数用法有:

$_FILES['myFile']['name'] 显示客户端文件的原名称。
$_FILES['myFile']['type'] 文件的 MIME 类型,例如"image/gif"。
$_FILES['myFile']['size'] 已上传文件的大小,单位为字节。
$_FILES['myFile']['tmp_name'] 储存的临时文件名,一般是系统默认。
$_FILES['myFile']['error'] 该文件上传相关的错误代码。以下为不同代码代表的意思:
0; 文件上传成功。
1; 超过了文件大小php.ini中即系统设定的大小。
2; 超过了文件大小MAX_FILE_SIZE 选项指定的值。
3; 文件只有部分被上传。
4; 没有文件被上传。
5; 上传文件大小为0。

前端

<form action="accept-file.php" method="post" enctype="multipart/form-data">
    Your Photo: <input type="file" name="photo" size="25" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>

后端

<?php
$valid_file = true;
//if they DID upload a file...
if($_FILES['photo']['name'])
{
    //if no errors...
    if(!$_FILES['photo']['error'])
    {
        //now is the time to modify the future file name and validate the file
        $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
        if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
        {
            $valid_file = false;
            $message = 'Oops!  Your file\'s size is to large.';
        }
        
        //if the file has passed the test
        if($valid_file)
        {
            $new_file_name = $_FILES["photo"]["name"];
            echo "Upload: " . $_FILES["photo"]["name"] . "<br />";
            echo "Type: " . $_FILES["photo"]["type"] . "<br />";
            echo "Size: " . ($_FILES["photo"]["size"] / 1024) . " Kb<br />";
            echo "Stored in: " . $_FILES["photo"]["tmp_name"] . "<br />";
            
            //move it to where we want it to be
            move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
            $message = 'Congratulations!  Your file was accepted.';
        }
    }
    //if there is an error...
    else
    {
        //set that to be the returned message
        $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
    }
}
echo $message;
?>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容