user3552551 user3552551 - 1 year ago 68
PHP Question

What are http headers and when do I need to specify them

I'm trying to download a file with laravel. I'm seeing a lot of examples that show the headers array with things link content-type/size etc.

My question is what are these headers and when do I need to set them

Sample of my code:

$file_path = public_path() . 'path/to/file' . $file_name;

if (file_exists($file_path)) {
return response()->download($file_path, $file_name);

This works for me. But I've seen some examples add a headers array as a third argument and I'm curious to know the uses of it.


Answer Source

HTTP Headers provide your webbrowser with extra information about the response it gets from a request. In your case, the Content-type header provides the browser with information about, believe it or not, the type of content the server returns. By specifying Content-type: application/pdf your browser will know it has to use the Adobe Reader plugin for example to display the content the server returns. You can find more information about HTTP headers in this Wikipedia article.

You can use HTTP response headers in your Laravel application like this:

return new \Illuminate\Http\Response(file_path, 200, [
            'Content-type' =>  'application/pdf',
            'Content-Disposition' => 'attachment; filename=' . $file_name,
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download