"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > PHP를 사용하여 파일을 안전하게 업로드하려면 어떻게해야합니까?

PHP를 사용하여 파일을 안전하게 업로드하려면 어떻게해야합니까?

2025-03-24에 게시되었습니다
검색:775

How Can I Securely Upload Files Using PHP?

// 업로드 된 파일의 대상 디렉토리를 선언합니다. $ target_dir = "업로드/"; // 허용 파일 유형에 대한 빈 배열을 초기화합니다 $ alludtypes =

; // 양식이 제출되었는지 확인하십시오 if (isset ($ _ post )) { // 파일 세부 정보를 검색합니다 $ target_file = $ target_dir. Basename ($ _ files

); $ file_type = strtolower (pathinfo ($ target_file, pathinfo_extension)); // 파일 유형의 유효성 if (! in_array ($ file_type, $ alludtypes)) { Echo "유효하지 않은 파일 유형. JPG 및 PNG 파일 만 허용됩니다."; } // 파일이 이미 존재하는지 확인하십시오 elseif (file_exists ($ target_file)) { Echo "파일이 이미 존재합니다. 다른 파일을 선택하십시오."; } // 파일 크기 확인 (5MB 제한을 가정) elseif ($ _files

> 5000000) { Echo "파일이 너무 큽니다. 최대 파일 크기는 5MB입니다."; } 또 다른 { // 파일을 대상 디렉토리로 이동하려고 시도 if (move_uploaded_file ($ _ files
// Declare the target directory for uploaded files
$target_dir = "uploads/";

// Initialize an empty array for allowed file types
$allowedTypes = ['jpg', 'png'];

// Check if the form has been submitted
if (isset($_POST['submit'])) {
    // Retrieve the file details
    $target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
    $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Validate the file type
    if (!in_array($file_type, $allowedTypes)) {
        echo "Invalid file type. Only JPG and PNG files are allowed.";
    } 

    // Check if the file already exists
    elseif (file_exists($target_file)) {
        echo "File already exists. Please choose a different file.";
    } 

    // Check file size (assumes a 5MB limit)
    elseif ($_FILES['fileToUpload']['size'] > 5000000) {
        echo "File is too large. Maximum file size is 5MB.";
    } 

    else {
        // Attempt to move the file to the target directory
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
            echo "File uploaded successfully!";
        } else {
            echo "File upload failed. Please try again.";
        }
    }
}

?>
, $ target_file)) { Echo "파일이 성공적으로 업로드되었습니다!"; } 또 다른 { Echo "파일 업로드가 실패했습니다. 다시 시도하십시오."; } } } ?>

이 스크립트는 개선 된 오류 처리 및 유효성 검사 메커니즘을 제공하므로 허용 파일 유형 만 업로드하고 중복 또는 지나치게 큰 파일이 허용되는 것을 방지합니다.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3