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
- Start Apache from the XAMPP Control Panel (or just open a terminal).
- Save the snippet as
p17_create_file.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p17_create_file.php, or runphp p17_create_file.php. - Copy the printed path and open the file in Notepad — it holds the message line and the creation timestamp.
- Run it again:
file_put_contentswith default flags truncates and rewrites, so the timestamp inside the file updates.
Explanation of the Code
$filePathjoinssys_get_temp_dir(),DIRECTORY_SEPARATORand the filename — a portable path that never depends onhtdocsbeing writable.$contentis a double-quoted string, so the\nescape becomes a real newline, anddate("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 asstrpos()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
- Differentiate fopen modes
w,xanda.wcreates or truncates;xcreates only — it fails if the file already exists;aappends, creating the file if needed, with the pointer always at the end. - What does
file_put_contents()return, and why test with!== false? Bytes written on success,falseon failure; a 0-byte write is falsy but not a failure, so only the strict test is correct. - When is mode
xpreferable tow? Whenever an existing file must never be clobbered —xturns accidental overwriting into a detectable error instead of silent data loss. - Why use
sys_get_temp_dir()andDIRECTORY_SEPARATOR? They adapt to the OS — temp location and\vs/— so the script is portable and always writes somewhere writable. - Why must files opened with
fopen()be closed withfclose()? 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. - 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