
SplFileObject::fpassthru 함수는 파일의 내용을 브라우저로 전송하는 데 사용됩니다. 이 함수를 사용하여 파일을 브라우저로 전송하려면, 먼저 파일을 읽어와야 합니다.
파일을 읽어오기 위해 SplFileObject::fpassthru 함수를 사용할 때, 브라우저가 파일을 다운로드할 수 있도록 하려면, Content-Disposition 헤더를 설정해야 합니다. Content-Disposition 헤더는 브라우저가 파일을 다운로드할 수 있도록 하는 헤더입니다.
Content-Disposition 헤더를 설정하는 예제 코드는 다음과 같습니다.
#hostingforum.kr
php
header('Content-Disposition: attachment; filename="example.txt"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize('example.txt'));
$file = new SplFileObject('example.txt');
$file->fpassthru();
이러한 예제 코드를 사용하면, 브라우저가 파일을 다운로드할 수 있습니다.
SplFileObject::fpassthru 함수를 사용할 때 발생할 수 있는 에러는 다음과 같습니다.
- 파일이 존재하지 않는 경우
- 파일을 읽어오기 위한 권한이 없는 경우
- 파일의 크기가 너무 큰 경우
이러한 에러를 해결하기 위해, 파일이 존재하는지 확인하고, 파일을 읽어오기 위한 권한을 확인하는 코드를 추가할 수 있습니다.
#hostingforum.kr
php
if (!file_exists('example.txt')) {
echo '파일이 존재하지 않습니다.';
exit;
}
if (!is_readable('example.txt')) {
echo '파일을 읽어오기 위한 권한이 없습니다.';
exit;
}
header('Content-Disposition: attachment; filename="example.txt"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize('example.txt'));
$file = new SplFileObject('example.txt');
$file->fpassthru();
이러한 예제 코드를 사용하면, 파일이 존재하지 않는 경우와 파일을 읽어오기 위한 권한이 없는 경우를 해결할 수 있습니다.
2025-06-27 20:56