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 17: Create a File

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

Aim

To write a PHP program that creates a new file on disk and writes initial content into it.

Theory

PHP's classic file API is a three-step handle sequence: fopen($path, $mode) opens the file and returns a resource handle, fwrite($handle, $data) writes bytes through it, and fclose($handle) flushes buffers and releases the handle. The mode chooses the behaviour: w creates the file or truncates an existing one to zero length; x is the exclusive-create mode — it fails with a warning (returning false) if the file already exists, making it the safe choice when overwriting would be a bug; a opens for appending (creates if missing, pointer fixed at the end). Adding + to any of them (w+, x+, a+) also allows reading, while plain r requires the file to exist already.

file_put_contents($path, $data) wraps the whole sequence in one call — open in w mode, write, close — and returns the number of bytes written, or false on failure. It is the idiomatic way to create small files.

Creation fails when the target directory does not exist or is not writable — checkable in advance with is_writable(dirname($path)). The snippet sidesteps permission trouble entirely by writing into sys_get_temp_dir() (C:\Users\<you>\AppData\Local\Temp on Windows, /tmp on Linux), joined with DIRECTORY_SEPARATOR so the path is correct on every OS — the same file runs under XAMPP, the CLI and online compilers.

Requirements

  • XAMPP/WAMP with Apache and PHP 8.x, or the PHP CLI / an online PHP compiler
  • Code editor (VS Code); browser or terminal

Procedure

  1. Start Apache from the XAMPP Control Panel (or just open a terminal).
  2. Save the snippet as p17_create_file.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p17_create_file.php, or run php p17_create_file.php.
  4. Copy the printed path and open the file in Notepad — it holds the message line and the creation timestamp.
  5. Run it again: file_put_contents with default flags truncates and rewrites, so the timestamp inside the file updates.

Explanation of the Code

  • $filePath joins sys_get_temp_dir(), DIRECTORY_SEPARATOR and the filename — a portable path that never depends on htdocs being writable.
  • $content is a double-quoted string, so the \n escape becomes a real newline, and date("Y-m-d H:i:s") is concatenated as the second line.
  • file_put_contents($filePath, $content) performs create-write-close in one call and returns the byte count written.
  • if ($result !== false) uses a strict comparison: a legitimate zero-byte write would be falsy, so only a genuine failure (false) may take the error branch — the same idiom as strpos() checks.
  • On success the script echoes the full path so the file can be located; otherwise it prints Failed to create file.

Expected Output

Two lines: File created successfully at: followed by the temp path, e.g. C:\Users\<you>\AppData\Local\Temp\wbp_lab_created_file.txt under XAMPP on Windows, or /tmp/wbp_lab_created_file.txt on a Linux CLI / online compiler. The created file itself contains This is a newly created file. and Created at: <current timestamp>. Only if the temp directory were unwritable would Failed to create file. appear instead.

🎯 Viva Questions

  1. Differentiate fopen modes w, x and a. w creates or truncates; x creates only — it fails if the file already exists; a appends, creating the file if needed, with the pointer always at the end.
  2. What does file_put_contents() return, and why test with !== false? Bytes written on success, false on failure; a 0-byte write is falsy but not a failure, so only the strict test is correct.
  3. When is mode x preferable to w? Whenever an existing file must never be clobbered — x turns accidental overwriting into a detectable error instead of silent data loss.
  4. Why use sys_get_temp_dir() and DIRECTORY_SEPARATOR? They adapt to the OS — temp location and \ vs / — so the script is portable and always writes somewhere writable.
  5. Why must files opened with fopen() be closed with fclose()? To flush PHP's write buffer to disk and release the handle (and any lock); data can be lost if a script dies with buffers unflushed.
  6. How can a script check permissions before creating a file? is_writable(dirname($path)) on the target directory (or on the file itself when overwriting an existing one).

CO Mapping

CO1, CO2