Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 21: Web Page for File Upload and Download

Lesson 28 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Aim

To create a web page that provides file uploading and file downloading using PHP.

Theory

File upload needs two cooperating pieces. The form must declare method="post" and enctype="multipart/form-data" — without that encoding the browser sends only the file's name, never its bytes. On the server, PHP exposes each uploaded file through the $_FILES superglobal: $_FILES["myfile"] is an array with five keys — name (original filename), type (browser-claimed MIME type), tmp_name (where PHP parked the bytes), error (0 = UPLOAD_ERR_OK) and size (bytes).

PHP deliberately quarantines every upload in a temporary directory and deletes it when the request ends; the script must claim it with move_uploaded_file(), which also verifies the source really is an HTTP upload. Size is capped by two php.ini directives: upload_max_filesize (one file) and post_max_size (the whole POST body, so it must be at least as large).

Downloading is the reverse trick: before any output the script sends Content-Type: application/octet-stream and Content-Disposition: attachment; filename="..." headers — the second forces the browser's Save dialog — then streams the bytes with readfile() and exits so no HTML corrupts the stream.

Requirements

  • XAMPP/WAMP with Apache and PHP 8.x (or PHP CLI for the simulated run)
  • Code editor (VS Code); browser (Chrome/Edge)

Procedure

  1. Start Apache from the XAMPP Control Panel.
  2. Save the snippet as p21_upload_download.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p21_upload_download.php — a file chooser and an Upload button appear.
  4. Pick a small file and submit; on success a Download Uploaded File link appears — clicking it makes the browser save the same file back.
  5. Run php p21_upload_download.php in a terminal: with no browser available, the compiler/CLI branch demonstrates the workflow using local temporary files — it writes a demo file and prints usage hints instead of rendering the form.

Explanation of the Code

  • $uploadDir is built from sys_get_temp_dir() plus wbp_uploads and created on first run with mkdir() — the system temp dir keeps the demo portable (a real site would use an uploads/ folder inside htdocs).
  • php_sapi_name() === "cli" selects the compiler branch: file_put_contents() fakes an upload by writing sample_upload.txt, then its path and two hint lines are printed.
  • Upload half (web): on a POST with $_FILES["myfile"] set, basename() strips any directory part from the client-supplied name (blocking ../ path traversal) and move_uploaded_file() moves the quarantined tmp_name to $target. Success echoes a link whose ?download= query carries the filename through urlencode().
  • Download half: when $_GET["download"] is present the script re-applies basename(), checks file_exists(), emits the two download headers, streams the file with readfile() and calls exit immediately.
  • Finally the form itself is echoed — note the enctype='multipart/form-data' attribute, without which $_FILES would stay empty.

Expected Output

In the browser the page first shows only a file input and an Upload button. After a successful upload it prints File uploaded successfully. followed by the Download Uploaded File link; clicking the link downloads that exact file (no page renders, because the script exits after readfile()). A failed move prints Upload failed. instead. Run from the CLI/compiler, it prints CLI Demo Upload Path: with the temp-folder path of sample_upload.txt, plus the hints about using <input type='file' name='myfile'> and the ?download=filename query string.

🎯 Viva Questions

  1. Why is enctype="multipart/form-data" compulsory for uploads? It makes the browser encode the request in parts that carry the raw file bytes; the default encoding sends only the filename text.
  2. Name the five keys of $_FILES["myfile"]. name, type, tmp_name, error and size.
  3. Why does PHP put uploads in a temp directory first? As a quarantine — the file is discarded at request end unless the script explicitly accepts it with move_uploaded_file().
  4. Which php.ini directives limit upload size? upload_max_filesize and post_max_size; the second covers the whole request body and must be ≥ the first.
  5. Which header forces a download instead of inline display? Content-Disposition: attachment; filename="...".
  6. Why call basename() on both the uploaded and requested names? To strip path components, preventing directory-traversal attacks like ?download=../../config.php.

CO Mapping

CO1, CO2