使用 HTML PHP 上传文件

Uploading a file using HTML PHP

我是 PHP 的新手,我从互联网上获取了一些示例代码,使用 PHP 脚本将文件上传到服务器。

我正在尝试使用以下代码上传文件,

HTML代码:

    This form allows you to upload a file to the server.<br>

    <form action="classes.php" method="post"><br>
        Type (or select) Filename: <input type="file" name="upfile">
        <input type="submit" value="Upload File">
    </form>

PHP代码:

 <?php

header('Content-Type: text/plain; charset=utf-8');


try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}
?>

我在尝试上传文件时收到 "Invalid parameters." 消息。

谁能帮我解决这个问题。

在您的 HTML 中您需要 enctype

<form action="classes.php" method="post" enctype="multipart/form-data"> 

查看here了解更多详情

您错过了代码中的 enctype...

<form action="classes.php" method="post" enctype="multipart/form-data">

这样做,它会很好地工作...