File Downloads and HTTP Headers in PHP Practice Questions with Solutions

Introduction

PHP allows developers to send files from a server to a user’s browser for downloading. HTTP headers help control how browsers handle responses, including file downloads, content types, redirects, and caching. In this chapter, you will practise downloading text files, PDFs, images, and other documents using PHP’s header() function. File Downloads and HTTP Headers in PHP practice questions with solutions to help you to understand the concepts.

Question 1: Download a Text File Using PHP

Problem Statement

Create a PHP program that allows users to download a text file named student.txt.

PHP Solution

download.php

<?php

$file = "student.txt";

if (file_exists($file)) {

    header("Content-Type: text/plain");
    header("Content-Disposition: attachment; filename=\"student.txt\"");
    header("Content-Length: " . filesize($file));

    readfile($file);
    exit;

} else {

    echo "File not found.";

}

?>

student.txt

Welcome to PHP File Downloads.
This is a sample student file.

Sample Output

When the user opens download.php, the browser downloads a file named:

student.txt

Explanation

  • file_exists() checks whether the file is available.
  • Content-Type tells the browser that the response contains plain text.
  • Content-Disposition: attachment asks the browser to download the file.
  • Content-Length specifies the file size in bytes.
  • readfile() sends the file contents to the browser.
  • exit stops further PHP execution.

Concepts Covered

  • File downloading
  • header()
  • readfile()
  • file_exists()
  • HTTP response headers

Question 2: Download a PDF File Using PHP

Problem Statement

Create a PHP program that allows users to download a PDF document named notes.pdf.

PHP Solution

download.php

<?php

$file = "notes.pdf";

if (file_exists($file)) {

    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"notes.pdf\"");
    header("Content-Length: " . filesize($file));

    readfile($file);
    exit;

} else {

    echo "PDF file not found.";

}

?>

Sample Output

The browser downloads:

notes.pdf

Explanation

  • application/pdf identifies the response as a PDF document.
  • Content-Disposition: attachment requests a download instead of displaying the PDF inline.
  • filesize() returns the file size.
  • readfile() sends the PDF contents to the browser.

Concepts Covered

  • PDF downloads
  • Content type
  • Content disposition
  • File size
  • readfile()

Question 3: Download an Image Using PHP

Problem Statement

Create a PHP program that allows users to download an image named photo.jpg.

PHP Solution

download.php

<?php

$file = "photo.jpg";

if (file_exists($file)) {

    header("Content-Type: image/jpeg");
    header("Content-Disposition: attachment; filename=\"photo.jpg\"");
    header("Content-Length: " . filesize($file));

    readfile($file);
    exit;

} else {

    echo "Image not found.";

}

?>

Sample Output

The browser downloads:

photo.jpg

Explanation

  • image/jpeg identifies the response as a JPEG image.
  • The attachment header requests a download.
  • file_exists() checks whether the image is available.
  • readfile() sends the image to the browser.

Concepts Covered

  • Image downloads
  • MIME types
  • HTTP headers
  • File checking

Question 4: Display a PDF in the Browser Instead of Downloading It

Problem Statement

Create a PHP program that opens a PDF file directly in the browser instead of asking the user to download it.

PHP Solution

view.php

<?php

$file = "notes.pdf";

if (file_exists($file)) {

    header("Content-Type: application/pdf");
    header("Content-Disposition: inline; filename=\"notes.pdf\"");
    header("Content-Length: " . filesize($file));

    readfile($file);
    exit;

} else {

    echo "PDF file not found.";

}

?>

Sample Output

The PDF opens inside the browser’s built-in PDF viewer, if supported.

Explanation

  • Content-Type: application/pdf identifies the file as a PDF.
  • Content-Disposition: inline asks the browser to display the PDF.
  • readfile() sends the PDF contents.
  • Unlike attachment, inline requests browser display rather than a download.

Concepts Covered

  • Inline content display
  • PDF response
  • Content-Disposition
  • HTTP headers

Question 5: Set a Custom Filename for a Download

Problem Statement

Create a PHP program that downloads a file named report.txt but saves it on the user’s device as Monthly_Sales_Report.txt.

PHP Solution

download.php

<?php

$file = "report.txt";

if (file_exists($file)) {

    $downloadName = "Monthly_Sales_Report.txt";

    header("Content-Type: text/plain");
    header(
        "Content-Disposition: attachment; filename=\""
        . $downloadName . "\""
    );

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

    readfile($file);
    exit;

} else {

    echo "Report not found.";

}

?>

Sample Output

The downloaded file is saved as:

Monthly_Sales_Report.txt

Explanation

  • $file represents the actual file stored on the server.
  • $downloadName defines the filename presented to the browser.
  • Content-Disposition controls the suggested download filename.
  • The original server filename and downloaded filename can be different.

Concepts Covered

  • Custom download filename
  • Content disposition
  • File handling
  • HTTP headers

Question 6: Download a File After Checking Its Extension

Problem Statement

Create a PHP program that allows users to download only PDF, TXT, and JPG files from a specified folder.

PHP Solution

download.php

<?php

$allowedFiles = [
    "notes.pdf" => "application/pdf",
    "student.txt" => "text/plain",
    "photo.jpg" => "image/jpeg"
];

$fileName = $_GET["file"] ?? "";

if (!isset($allowedFiles[$fileName])) {

    http_response_code(403);
    exit("File type or file name is not allowed.");

}

$filePath = "downloads/" . $fileName;

if (!is_file($filePath) || !is_readable($filePath)) {

    http_response_code(404);
    exit("File not found.");

}

header("Content-Type: " . $allowedFiles[$fileName]);
header("Content-Disposition: attachment; filename=\""
    . $fileName . "\"");
header("Content-Length: " . filesize($filePath));

readfile($filePath);
exit;

?>

Sample Output

URL:

http://localhost/project/download.php?file=notes.pdf

Output:

The browser downloads notes.pdf.

If an unapproved filename is requested:

File type or file name is not allowed.

Explanation

  • $_GET["file"] receives the requested filename.
  • $allowedFiles contains only approved filenames and their content types.
  • isset() checks whether the requested file is in the allowlist.
  • is_file() checks whether the path points to a file.
  • is_readable() checks whether PHP can read it.
  • http_response_code() sends an appropriate HTTP status.

The allowlist prevents users from requesting arbitrary filenames through the URL.

Concepts Covered

  • Controlled file downloads
  • GET parameters
  • File allowlisting
  • http_response_code()
  • File access checking

Question 7: Set the Content-Type Header for JSON Data

Problem Statement

Create a PHP program that sends student information as JSON instead of displaying it as normal HTML.

PHP Solution

<?php

header("Content-Type: application/json; charset=UTF-8");

$student = [
    "name" => "Rahul Sharma",
    "course" => "PHP",
    "marks" => 85
];

echo json_encode($student);

?>

Sample Output

{
    "name": "Rahul Sharma",
    "course": "PHP",
    "marks": 85
}

Explanation

  • Content-Type: application/json tells the browser or client that the response contains JSON.
  • The $student array stores student information.
  • json_encode() converts the PHP array into JSON.
  • charset=UTF-8 specifies the character encoding.

Concepts Covered

  • HTTP Content-Type
  • JSON response
  • header()
  • json_encode()

Question 8: Redirect Users to Another Page Using PHP

Problem Statement

Create a PHP program that redirects users from one page to another using the HTTP Location header.

PHP Solution

redirect.php

<?php

header("Location: welcome.php");
exit;

?>

welcome.php

<?php

echo "Welcome to PHP Programming!";

?>

Sample Output

When a user opens redirect.php, the browser moves to:

welcome.php

The destination page displays:

Welcome to PHP Programming!

Explanation

  • header("Location: welcome.php") sends a redirect response.
  • The browser requests the destination page.
  • exit stops the current PHP script.
  • The redirect header must be sent before any output.

Concepts Covered

  • HTTP redirects
  • Location header
  • header()
  • exit

Question 9: Send a Custom HTTP Status Code

Problem Statement

Create a PHP program that sends a 404 Not Found status when a requested file does not exist.

PHP Solution

<?php

$file = "student_report.pdf";

if (file_exists($file)) {

    echo "File is available.";

} else {

    http_response_code(404);

    echo "404 - File Not Found.";

}

?>

Sample Output

404 - File Not Found.

<text color=”secondary” size=”xs”>The HTTP response status is 404 Not Found.</text>

Explanation

  • file_exists() checks whether the requested file is available.
  • http_response_code(404) sets the HTTP response status.
  • The browser or other client receives a 404 response.
  • A status code communicates the result of a request.

Common HTTP Status Codes

Status CodeMeaning
200OK
201Created
301Moved Permanently
302Found / Temporary Redirect
400Bad Request
403Forbidden
404Not Found
500Internal Server Error

Concepts Covered

  • HTTP status codes
  • http_response_code()
  • 404 errors
  • Server responses

Question 10: Build a Complete Secure File Download System

Problem Statement

Create a PHP program that allows users to download approved files from a downloads folder. The system should:

  • Allow only selected files.
  • Check whether the requested file exists.
  • Check whether the file is readable.
  • Set the correct Content-Type header.
  • Send the file as an attachment.
  • Display suitable HTTP errors for invalid requests.

PHP Solution

download.php

<?php

$allowedFiles = [
    "php_notes.pdf" => [
        "path" => __DIR__ . "/downloads/php_notes.pdf",
        "type" => "application/pdf"
    ],

    "student_list.txt" => [
        "path" => __DIR__ . "/downloads/student_list.txt",
        "type" => "text/plain"
    ],

    "course_image.jpg" => [
        "path" => __DIR__ . "/downloads/course_image.jpg",
        "type" => "image/jpeg"
    ]
];

$fileName = $_GET["file"] ?? "";

if (!isset($allowedFiles[$fileName])) {

    http_response_code(403);
    exit("Access to this file is not allowed.");

}

$filePath = $allowedFiles[$fileName]["path"];
$contentType = $allowedFiles[$fileName]["type"];

if (!is_file($filePath) || !is_readable($filePath)) {

    http_response_code(404);
    exit("Requested file is not available.");

}

$fileSize = filesize($filePath);

if ($fileSize === false) {

    http_response_code(500);
    exit("Unable to read file information.");

}

header("Content-Type: " . $contentType);

header(
    "Content-Disposition: attachment; filename=\""
    . $fileName . "\""
);

header("Content-Length: " . $fileSize);

header("X-Content-Type-Options: nosniff");

readfile($filePath);

exit;

?>

Sample Output

Download URL:

http://localhost/project/download.php?file=php_notes.pdf

Result:

The browser downloads:

php_notes.pdf

If the user requests an unapproved file:

Access to this file is not allowed.

If an approved file is missing:

Requested file is not available.

Explanation

  • $allowedFiles stores approved filenames, server paths, and content types.
  • $_GET["file"] receives the requested filename.
  • isset() prevents users from requesting files outside the allowlist.
  • is_file() and is_readable() check file availability.
  • filesize() retrieves the file size.
  • Content-Type identifies the file format.
  • Content-Disposition requests a file download.
  • X-Content-Type-Options: nosniff tells browsers not to guess a different content type.
  • readfile() sends the file to the browser.
  • exit prevents additional output from being added to the download response.

Concepts Covered

  • Complete file download system
  • File allowlisting
  • HTTP headers
  • Content-Type and Content-Disposition
  • HTTP error responses
  • Secure file access

Key Takeaways

  • PHP uses the header() function to send HTTP response headers.
  • Content-Type identifies the type of response.
  • Content-Disposition: attachment requests a file download.
  • Content-Disposition: inline requests browser display.
  • Content-Length specifies the response size in bytes.
  • readfile() sends file contents to the browser.
  • file_exists() checks whether a file exists.
  • http_response_code() sets an HTTP status code.
  • Location redirects users to another page.
  • Always restrict downloads to approved files.
  • Send headers before producing any output.

Frequently Asked Questions (FAQs)

1. What are HTTP headers in PHP?

HTTP headers are information sent between a web server and a browser. They help identify response content, control redirects, specify status codes, and manage file downloads.

2. What is the header() function in PHP?

The header() function sends raw HTTP headers from PHP to the browser. It must be called before any actual response output.

3. How can we download a file using PHP?

Use header() to set the content type and attachment disposition, then use readfile() to send the file contents.

4. What is the difference between attachment and inline?

attachment asks the browser to download a file, while inline asks the browser to display it if the format is supported.

5. What is the purpose of the Content-Type header?

It tells the browser or client what kind of content the server is sending, such as PDF, JSON, plain text, or an image.

6. Why should we use readfile()?

readfile() reads a file and writes its contents directly to the output stream. It is useful for sending files to browsers.

7. What is http_response_code() in PHP?

It is a PHP function used to get or set the HTTP response status code, such as 200, 404, or 500.

8. How do we redirect a page using PHP?

Use the Location header and stop the script with exit.

header("Location: welcome.php");
exit;

9. Why must headers be sent before HTML output?

HTTP headers are sent before the response body. If PHP has already started sending output, it may no longer be able to modify the headers.

10. How can we prevent users from downloading unauthorized files?

Use an allowlist of approved filenames, verify that files exist and are readable, and check the user’s permissions when downloads require authentication.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top