PHP保存PDF文件出现截断无法打开问题求助
Hey there, let's break down why some of your PDFs are getting cut off when saving to localhost, and how to fix it—starting with your question about remote file size:
Remote file size absolutely could be the culprit
If the truncated files are the larger ones, PHP's default resource limits are probably cutting off the transfer mid-process. Here’s what to tweak:memory_limit: PHP might not have enough RAM to hold the entire PDF in memory before saving. Try increasing it in yourphp.ini(e.g.,memory_limit = 256M) or at runtime withini_set('memory_limit', '256M');max_execution_time: Downloading large files can take longer than PHP’s default timeout. Bump this up to 120 seconds or more—usemax_execution_time = 120inphp.iniorset_time_limit(120);directly in your function.
Ditch
file_get_contents()for large filesfile_get_contents()loads the entire file into memory at once, which is a disaster for big PDFs. Instead, use streamed downloads with cURL orfopento write the file in chunks—this avoids memory overload:
Example cURL implementation:function saveRemotePDF($remoteUrl, $localPath) { $ch = curl_init($remoteUrl); $fp = fopen($localPath, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Handle redirects curl_setopt($ch, CURLOPT_TIMEOUT, 120); // Match your execution timeout curl_setopt($ch, CURLOPT_FAILONERROR, true); // Catch HTTP errors like 404/500 $success = curl_exec($ch); curl_close($ch); fclose($fp); return $success; }This writes the PDF to disk as it downloads, so you never need to hold the full file in memory.
Check for partial HTTP responses
Some servers send partial content (HTTP 206) if your request doesn’t handle range headers correctly. Force a full file request by addingcurl_setopt($ch, CURLOPT_RANGE, '0-');to your cURL options—this ensures you get the entire PDF instead of a chunk.Verify local disk permissions and space
Even if the download completes, missing write permissions for the target directory or insufficient disk space can truncate the file. Quick checks:- Run
echo is_writable($targetDirectory);to confirm write access - Check disk space via your localhost control panel or
df -h(on Linux/macOS)
- Run
Validate file integrity post-save
Compare the local file size to the remote file’s reported size to catch truncation early:function getRemoteFileSize($remoteUrl) { $headers = get_headers($remoteUrl, 1); return isset($headers['Content-Length']) ? (int)$headers['Content-Length'] : false; } // After saving, cross-check sizes $remoteSize = getRemoteFileSize($remoteUrl); $localSize = filesize($localPath); if ($remoteSize && $localSize !== $remoteSize) { // Log the issue or retry the download }Disable output buffering
Accidental browser output (even whitespace) can interfere with file writing. Addob_clean();andob_end_flush();before your save logic to clear any stray output.
内容的提问来源于stack exchange,提问作者Roy Granit

