웹 개발에서 파일 업로드는 일반적이고 중요한 기능입니다. PHP는 $ _files Global Variable을 통해 파일 수신 및 관리를 실현합니다. 업로드 프로세스에는 일반적으로 파일을 제출하는 클라이언트가 포함되며 서버는이를 임시 디렉토리로 저장하고 파일의 정당성을 확인한 후 파일을 지정된 디렉토리로 이동하여 업로드를 완료합니다.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="파일 업로드">
</form>
<?php
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
?>
<?php
$allowedTypes = ['image/jpeg', 'image/png']; // 파일 유형을 업로드 할 수 있습니다
$maxSize = 2 * 1024 * 1024; // 最大允许파일 업로드大小,2MB
if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
$destination = 'uploads/' . $fileName;
move_uploaded_file($fileTmp, $destination);
echo '파일 업로드를 성공적으로 업로드하십시오!';
} else {
echo '이 유형의 파일 또는 파일 크기의 업로드는 한계를 초과합니다.!';
}
?>
파일 다운로드는 웹 응용 프로그램의 또 다른 주요 기능입니다. 요청을 보내면 서버는 파일을 읽고 HTTP 응답을 통해 파일을 클라이언트로 전송합니다. 합리적인 HTTP 헤더를 설정하면 파일을 올바르게 다운로드하고 저장할 수 있습니다.
<span class="fun"><a href = "download.php? file = filename"> 다운로드 파일 </a></span>
<?php
$filePath = 'path/to/file/' . $_GET['file'];
if (file_exists($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filePath));
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
} else {
echo '파일이 존재하지 않습니다!';
}
?>
올바른 파일 이동 및 다운로드 헤드 설정과 결합 된 합리적인 파일 유형 및 크기 확인을 통해 파일 업로드 및 다운로드의 보안 및 안정성을 효과적으로 보장 할 수 있습니다. 이 기사에 대한 설명이 PHP 개발자가 기본 파일 처리 원칙을 이해하는 데 도움이되며 실제 프로젝트에 유연하게 적용될 수 있기를 바랍니다.