File handling and directories: include and require; file operations (fopen(), fread(), fwrite(), fclose()); file upload ($_FILES, move_uploaded_file()); file download using PHP headers; directory operations (opendir(), readdir(), mkdir(), rmdir())

PHP reads and writes files (fopen/fread/fwrite/fclose), reuses code with include and require, receives uploads via $_FILES, and manages directories: the portal gains persistent storage and file uploads.

11 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

When the server restarts, the data is gone

The event portal's registration list lives in a PHP array, which means it vanishes the moment the request ends: every page load starts blank. Real portals REMEMBER. The simplest way to make data survive is to write it to a FILE on the server.

And registration often needs an UPLOAD: a student's ID card or photo. PHP handles both: reading and writing files, and receiving uploads. This lesson gives the portal persistent storage and file uploads, plus the code-reuse tools (include, require) that keep a multi-page site tidy.

Theory

include vs require: the reuse pair

Real sites split shared code (a header, a database config) into separate files pulled into every page:

  • include 'header.php'; pulls the file in; if it is MISSING, PHP gives a WARNING and CONTINUES
  • require 'config.php'; pulls the file in; if it is MISSING, PHP throws a FATAL error and STOPS

The rule: use require for things the page CANNOT work without (database config), and include for optional extras (a sidebar). The _once variants (include_once, require_once) prevent accidentally pulling the same file in twice. Choosing require vs include correctly is a common exam question.

Practical

Reading and writing a registrations file

<?php
  require 'config.php';   // fatal if missing: the page needs it

  // WRITE (append a registration line)
  $f = fopen("registrations.txt", "a");   // 'a' = append
  fwrite($f, "Riya, Garba Night\n");
  fclose($f);                              // always close

  // READ the whole file back
  $data = file_get_contents("registrations.txt");
  echo nl2br($data);   // show it with line breaks
?>

Theory

File uploads, safely

To accept a file, the HTML form needs 2 things: method="POST" and enctype="multipart/form-data". The uploaded file then arrives in the $_FILES superglobal:

  • $_FILES['idcard']['name']: the original filename
  • $_FILES['idcard']['tmp_name']: a TEMPORARY location where PHP parked it
  • $_FILES['idcard']['size'], ['type'], ['error']

The file sits in a temp spot and is DELETED at the end of the request unless you save it: move_uploaded_file($_FILES['idcard']['tmp_name'], "uploads/" . $safeName). And because a stranger chose this file, you MUST validate its type and size before trusting it: an unchecked upload is a serious security hole.

Quiz

config.php holds the database settings the whole portal depends on. Should you pull it in with include or require, and why?

  1. include: it warns and continues, which is safer
  2. require: if the essential config is missing, the page should STOP with a fatal error rather than run broken
  3. Either is identical in effect
  4. Neither: config must be pasted into every file
Show the answer

require: if the essential config is missing, the page should STOP with a fatal error rather than run broken

For something the page CANNOT function without, use require: if config.php is missing, require halts execution with a fatal error, which is exactly right: a portal running without its database settings would fail in confusing, insecure ways, so stopping cleanly is safer. include only WARNS and CONTINUES, appropriate for optional pieces (a sidebar) but wrong for critical dependencies. Option C is false: the missing-file behaviour is the whole difference. Option D defeats the purpose of reuse. Rule: require for essentials (stop if absent), include for optional extras (continue if absent).

Think first

The upload that disappeared

A student's upload form works, $_FILES shows the file arrived, but the saved file is nowhere and later requests cannot find it. What single step was skipped, and why does PHP behave this way? Then tap.

Show the answer

The student never called move_uploaded_file(). PHP parks an upload in a TEMPORARY location (tmp_name) and automatically DELETES it at the end of the request; unless you move it to a permanent folder within that same request, it is gone. So $_FILES correctly showed the file DURING the request, but nothing saved it. The fix: move_uploaded_file($_FILES['idcard']['tmp_name'], "uploads/$safeName") before the request ends. (And validate type/size and generate a safe filename first, for security.) The temp-then-move design is deliberate: it lets you inspect and validate the upload before committing it to disk.

Watch out

File-handling traps

Forgetting move_uploaded_file: the temp file vanishes; the upload is lost.

Unvalidated uploads: check type and size; never trust a user-supplied filename or execute an uploaded file.

require for optional files: a missing optional file should not kill the page; use include there.

Not closing files: fclose() after fopen/fwrite; leaked handles cause problems.

Wrong fopen mode: 'w' TRUNCATES the file (erases it); use 'a' to append: the classic data-loss bug.

Theory

Files down, structured data next

The portal now persists data and accepts uploads. But plain text files are clumsy for structured records; the modern format for exchanging structured data is JSON, which you met in BCA405-01. The next lesson designs and validates forms properly with PHP filters (filter_var) and reads/writes JSON with json_encode and json_decode, so the portal can speak the same data language as JavaScript front-ends.

Summary

Key takeaways

  • include pulls in a file and WARNS + continues if missing; require throws a FATAL error and STOPS: use require for essentials.
  • include_once/require_once prevent double inclusion.
  • File ops: fopen(mode r/w/a), fread/fwrite, fclose; or file_get_contents/file_put_contents; 'w' truncates, 'a' appends.
  • Uploads need method POST + enctype multipart/form-data; the file arrives in $_FILES (name, tmp_name, size, error).
  • You MUST move_uploaded_file() to save an upload, or PHP deletes the temp file at request end; validate type/size.
  • Directory ops: opendir/readdir/closedir, scandir, mkdir, rmdir.
  • Memory hook: require for must-haves, and move the upload before it vanishes.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Advanced PHP and File Management

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

File handling and directories: include and require; file operations (fopen(), fread(), fwrite(), fclose()); file upload ($_FILES, move_uploaded_file()); file download using PHP headers; directory operations (opendir(), readdir(), mkdir(), rmdir()) · Web Framework and Services (Major-12) · Gri-Learn