文件名中的句点识别为扩展名

时间:2017-05-22 00:43:31

标签: php mysql file-upload

我有一个可以将文件上传到我的数据库的管理页面,问题是当文件上有一个句点(。)时,脚本将其作为扩展名读取。例如:我上传了一个名为" flower1.1.jpg"的文件。它变成了" flower1.1"没有jpg扩展名。 我的php上传脚本:

<?php

function upload_file()
{
    if(isset($_FILES["user_image"]))
    {
        $extension = explode('.', $_FILES['user_image']['name']);
        $new_name = $extension[0] . '.' . $extension[1];
        $destination = './upload/' . $new_name;
        move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
        return $new_name;
    }
}

function get_image_name($user_id)
{
    include('db3.php');
    $statement = $connection->prepare("SELECT image FROM users1 WHERE id = '$user_id'");
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        return $row["image"];
    }
}

function get_total_all_records()
{
    include('db3.php');
    $statement = $connection->prepare("SELECT * FROM users1");
    $statement->execute();
    $result = $statement->fetchAll();
    return $statement->rowCount();
}

?>

1 个答案:

答案 0 :(得分:1)

为什么你甚至试图获得扩展?你只是再次爆炸并将它们重新组合在一起:

function upload_file()
{
    if ( isset($_FILES["user_image"]) )
    {
        $destination = './upload/' . $_FILES['user_image']['name'];
        move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
        return $_FILES['user_image']['name'];
    }
}

请注意,请检查以确保您的用户仅上传图片:

function upload_file()
{
    static $valid_formats = array(
        'image/jpeg',
        'image/png',
        'image/gif'
    );

    if ( isset($_FILES['user_image']) )
    {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($_FILES['user_image']['tmp_name']);

        if ( !in_array($mime, $valid_formats) )
        {
            throw new RuntimeException('Invalid file format.');
        }

        $destination = './upload/' . $_FILES['user_image']['name'];
        move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
        return $_FILES['user_image']['name'];
    }
}