파일업로드/다운로드

파일업로드

/**
 * File Uploads.
 *
 * php.ini
 *
 * file_uploads
 */
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        echo <<<'HTML'
<form action="/" method='POST' enctype="multipart/form-data">
    <input type="file" name="uploads">
    <input type="submit">
</form>
HTML;
        break;
    case 'POST':
        $file = $_FILES['uploads'];
        $pathinfo = pathinfo($file['name']);
        $accepts = [
            'png', 'jpg'
        ];
        if (in_array(strtolower($pathinfo['extension']), $accepts) && is_uploaded_file($file['tmp_name'])) {
            move_uploaded_file($file['tmp_name'], dirname(__FILE__) . '/uploads/' . $file['name']);
        }
        break;
    default:
        http_response_code(404);
}  

파일다운로드

<?php

/**
 * File Downloads.
 */

// $path = filter_input(INPUT_GET, 'path', FILTER_SANITIZE_STRING);
$path = '../../../README.md';
$filepath = realpath(dirname(__DIR__) . '/uploads/' . basename($path)); // 허용된 폴더 이외에 접근하는걸 막는다

if (file_exists($filepath)) {
    $pathinfo = pathinfo($filepath);
    $accepts = [
        'md'
    ];
    if (in_array(strtolower($pathinfo['extension']), $accepts)) {
        header('Content-type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . basename($filepath));
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . filesize($filepath));

        readfile($filepath);
    }
}

Apr 8, 2023 Views 144