File type for pdf in php

правильные заголовки PHP для загрузки pdf-файлов

Я действительно пытаюсь заставить мое приложение открыть PDF-файл, когда пользователь нажимает на ссылку.

Пока тег привязки перенаправляется на страницу, которая отправляет заголовки, которые:

$filename='./pdf/jobs/pdffile.pdf; $url_download = BASE_URL . RELATIVE_PATH . $filename; header("Content-type:application/pdf"); header("Content-Disposition:inline;filename='$filename"); readfile("downloaded.pdf"); 

это, похоже, не работает, кто-нибудь успешно разбирал эту проблему в прошлом?

Пример 2 в w3schools показывает, чего вы пытаетесь достичь.

Важно заметить, что header () необходимо вызвать до отправки любого фактического вывода (в PHP 4 и более поздних версиях вы можете использовать буферизацию вывода для решения этой проблемы)

$name = 'file.pdf'; //file_get_contents is standard function $content = file_get_contents($name); header('Content-Type: application/pdf'); header('Content-Length: '.strlen( $content )); header('Content-disposition: inline; filename="' . $name . '"'); header('Cache-Control: public, must-revalidate, max-age=0'); header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); header('Last-Modified: '.gmdate('D, d MYH:i:s').' GMT'); echo $content; 

В вашем коде есть некоторые вещи.

Во-первых, правильно напишите эти заголовки. Вы никогда не увидите ни одного сервера, отправляющего Content-type:application/pdf , заголовок Content-Type: application/pdf , spaced, с заглавными буквами и т. Д.

Имя файла в Content-Disposition – это только имя файла, а не полный путь к нему, и, несмотря на то, что я не знаю, является ли оно обязательным или нет, это имя заносится в » нет ‘ . Кроме того, ваш последний ‘ отсутствует».

Content-Disposition: inline подразумевает, что файл должен отображаться, а не загружаться. Вместо этого используйте attachment .

Кроме того, сделайте расширение файла в верхнем регистре, чтобы сделать его совместимым с некоторыми мобильными устройствами.

Все, что сказано, ваш код должен выглядеть следующим образом:

Content-Length является необязательным, но также важно, если вы хотите, чтобы пользователь мог отслеживать ход загрузки и определять, была ли загрузка прервана. Но при его использовании вы должны убедиться, что вы не будете отправлять что-либо вместе с файловыми данными. Удостоверьтесь, что нет ничего перед , Даже пустая строка.

У меня была такая же проблема в последнее время, и это помогло мне:

 header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="FILENAME"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize("PATH/TO/FILE")); ob_clean(); flush(); readfile(PATH/TO/FILE); exit(); 

Можете ли вы попробовать это, readfile нужен полный путь к файлу.

 $filename='/pdf/jobs/pdffile.pdf'; $url_download = BASE_URL . RELATIVE_PATH . $filename; //header("Content-type:application/pdf"); header("Content-type: application/octet-stream"); header("Content-Disposition:inline;filename='".basename($filename)."'"); header('Content-Length: ' . filesize($filename)); header("Cache-control: private"); //use this to open files directly readfile($filename); 

Вам нужно определить размер файла …

header('Content-Length: ' . filesize($file)); 

заголовок ( «Content-Disposition: встроенный; имя файла = ‘$ имя_файла»);

Источник

Php header PDF Open in Browser

Before going to learn the use of the PHP header function for a pdf file, we need to understand the header function, its properties, and how it works in short. The header function is basically used to send raw HTTP header to the browser (client).

Header Syntax:

header(Param 1 , Param 2, Param 3)

Param 1 — This requires a param of type string. It represents the header string. It’s required param to pass.

  • Location: http://www.anyWebPage.com
  • HTTP/1.1 404 Not Found
  • Content-Type: application/pdf

Param 2 : It is an Optional param of boolean type. It indicates header replacement. Default value is true means it will replace previous.

Param 3: It is an Optional param of Integer type. It represents a response code.

Now let’s understand how we can use the header function to force browsers to prompt save data sent from the server. We will require the following certain headers to accomplish the PHP header pdf open in the browser.

Content Type : Content-Type header string required to signalize media type. It is used to tell browsers about the type of content being sent over.

  • Media type is image/png or image/jpg for image per image extension.
  • Media type is text/html to indicate an html file.
  • Media type is application/pdf to indicate a pdf file.

Therefore to tell about pdf file we need to use header like header(‘Content-Type: application/pdf’);

Content Disposition: Content-Disposition header string used as inline to let the browser know that content passed needs to be inline meaning that it should be part of a web page.

Content-Disposition header string with attachment option is used to prompt use of the «Save as» dialog box.

Therefore to display pdf file on browser we can use header as header(‘Content-Disposition: inline; filename=»abc.pdf»‘);

Let’s explore the following useful ways to download or View pdf in the browser without downloading PHP with related concepts and example codes.

Scroll for More Useful Information and Relevant FAQs

Источник

Identifying a pdf file and upload it to folder

I´m using this php code to upload images to a folder but I would like to allow pdf files to be uploaded also, so I modified a little the code:

 Correct image type.
"; $uploadOk = 1; > else < echo "
File is not an image.
"; $uploadOk = 0; > > // Check if file already exists if (file_exists($target_file)) < echo "
File already exists.
"; $uploadOk = 0; > // Check file size if ($_FILES["fileToUpload"]["size"] > 3750000) < echo "
Your file is too large.
"; $uploadOk = 0; > // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $textFileType != "pdf" ) < echo "
Only jpg, jpeg, png, gif and pdf (for the Plan Article) files are allowed.
"; $uploadOk = 0; > // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) < echo "
The file was not uploaded.
"; // if everything is ok, try to upload file > else < if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) < echo "
The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.

Please copy this filename: And paste it in an empty Extra image field above and save the form."; > else < echo "
There was an error uploading your file.
"; > > echo "

"; ?>

But this changes I made are not working, it still returns the «this is not an image» message. What part of the code identifies the filetype? is the $imageFileType a special variable that php uses to identify filetypes? I´m really confused about this. Can anyone help?

the problem here, is that you need to use the OR || operator for that entire line, not the AND && operator. You’re telling PHP to check if a file uploaded is JPG AND PNG AND GIF AND PDF.

No, the script worker fine for image type files. I got it here: w3schools.com/php/php_file_upload.asp

2 Answers 2

The file type for pdfs is application/pdf if you want to check the extension.

However, while you can check file extensions, but that’s not a very reliable way of identifying whether a file is a pdf or not (it’s easy to change a file extension for just about any file, creating a huge security hole).

While there’s nothing in php like getimagesize() for pdfs, you can still check the mime type which is a fairly good step in the process like so:

 if (!empty($_FILES['fileToUpload']['tmp_name'])) < $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $_FILES['fileToUpload']['tmp_name']); if ($mime != 'application/pdf')

Thank you for the reply. I´ve tried your code but I can´t get it to work, I´m a php beginner. Probably I´ll look for a piece of code that does the mime verification for all file formats i´d like to allow. but for now would like to just have this one working since the upload page is only used by a very limited amount of people.

This may have something to do with it $_FILES['article_pdf'] if you haven't changed that. @FredericoLopes

@FredericoLopes note that as I mentioned getimagesize() will not work for pdf files, and that this code above WILL work for all file types. I just gave you the pdf one because that was what you requested.

Thank you for all the help, after some code wrestling here it is the final functional version:

 Correct image type.
"; $uploadOk = 1; > else < echo "
File is not an image.
"; $uploadOk = 0; > >*/ // Check if file already exists if (file_exists($target_file)) < echo "
File already exists.
"; $uploadOk = 0; > // Check file size if ($_FILES["fileToUpload"]["size"] > 3750000) < echo "
Your file is too large.
"; $uploadOk = 0; > // Allow certain file formats /*if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) < echo "
Only jpg, jpeg, png, gif and pdf (for the Plan Article) files are allowed.
"; $uploadOk = 0; >*/ //Check for pdf format if (!empty($_FILES['fileToUpload']['tmp_name'])) < $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $_FILES['fileToUpload']['tmp_name']); if (($mime != 'application/pdf') && ($mime != 'image/jpg') && ($mime != 'image/jpeg') && ($mime != 'image/gif') && ($mime != 'image/png')) < $uploadOk = 0; echo "
This file is not a valid file.
"; //exit(); >> //this bracket was missing I think // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) < echo "
The file was not uploaded.
"; // if everything is ok, try to upload file > else < if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) < echo "
The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.

Please copy this filename: And paste it in an empty Extra image field above and save the form."; > else < echo "
There was an error uploading your file.
"; > > echo "

"; ?>

Regarding the && / || issue, at first I also had the idea of using the || operator, I tried it and it did´t worked, probably because we are using the != to compare so if some file is NOT jpg, NOT pdf. and so on it is not allowed and gets the error message and the &uploadOK = 0 so won´t upload.

Looking at the code this is what is written but still goes against my logic 🙂

Thank you very much for the help 😉

Источник

PHP: Check is file upload is a valid PDF file

The only thing i need to know is if the file is in fact a PDF. ¿What lower-level solution can i use? Like reading the first x chars and look for %PDF or something like that.

PHP 5.0.4 is more than 13 years old, support for the 5.0 branch ended in 2005 with 5.0.5. Hopefully this is not an application on the public internet

if you can use fopen all PDF files start with %PDF- like you suggest. Any reason you can't just do that?

3 Answers 3

You're limited, but you can do of things in the backend after form submission using $_FILES , which is from a form submitted with input type="file":

$_FILES['form_name_for_input_type_equals_file']['name'] ---> check if extension here is .pdf $_FILES['form_name_for_input_type_equals_file']['type'] ---> check if mime type here is application/pdf 

For more info about $_FILES click here.

Thanks, but i dont trust in those validations. The user can rename a executable file (changing the extension to .pdf) and bypass the validation. Something similar can happen whit the mime type.

$allowed = array('pdf'); $filename = $_FILES['document_file']['name']; $ext = pathinfo($filename, PATHINFO_EXTENSION); if(!in_array($ext,$allowed) )

What you could also do is let PHP call up a BASH script to confirm if it is a pdf by the OS, which I wouldn't advise you to do but it's as low level as it can get. What you could also do is use a regex in either bash or PHP to check the fileheaders if they match with the fileheaders of a PDF.

Источник

Читайте также:  Python pyodbc cursor execute
Оцените статью