I have a custom plugin that works great. I added an ability to save a generated PDF file on the server, within a seperate plugin based folder. The folder has read and execute permissions.
On the backend it reads and displays fine. ON the front is says:
Error Failed to load PDF document.
Anyone have any thoughts as to why? The file is already created and stored. This is just a read and display.
The code is as follows:
$PluginDir = plugin_dir_path( __DIR__ );
$ServerVault = $PluginDir . 'plugin-name/ServerVault/';
$filename = 'file.pdf';
$SavedResults = $ServerVault . $filename;
header("Content-type: application/pdf");
header("Content-Length: " . filesize($SavedResults));
@readfile($SavedResults);
Based on the information you provided there should be some things you should check.
First of all, don't suppress errors with @readfile().
If you have an error there, please update your post so we can see what is the error exactly.
**
However:
1. Check if file really exists and is readable:
if (!file_exists($SavedResults)) {
http_response_code(404);
exit("File not found.");
}
if (!is_readable($SavedResults)) {
http_response_code(403);
exit("File not readable.");
}
2. Try adding Content-Disposition header:
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"$filename\"");
header("Content-Length: " . filesize($SavedResults));
readfile($SavedResults);
exit;
3. Sometimes wordpress adds output buffering, clear it before putting PDF to output:
while (ob_get_level()) {
ob_end_clean();
}
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"$filename\"");
header("Content-Length: " . filesize($SavedResults));
readfile($SavedResults);
exit;
Additionally, I would say validate the plugin_dir_path(_DIR_) that is resolves the correct directory.
Let me know if any of this helps!