0% complete

Advanced PHP · Lesson 1 of 10

File Handling

Read and write files with explicit paths and checked results.

Lesson

PHP provides file functions and stream APIs for reading and writing. Check whether a file exists, whether the process has permission, and whether the operation succeeded. Use trusted paths rather than joining an unvalidated request value to a directory, and choose locking or atomic writes when concurrent updates are possible. The example writes to a known application-owned path and checks the result. Further guidance Make failure behavior explicit at system boundaries: validate decoded data, handle expected exceptions, and log diagnostics without exposing them to visitors. Keep dependencies locked and current, use a consistent namespace/autoloading scheme, and test error paths as well as successful responses. Practice task: Create a fresh example for File Handling. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

File Handling
PHP
$path = __DIR__ . '/notes.txt';
$written = file_put_contents($path, "PHP notes\n", LOCK_EX);
echo $written === false ? 'Write failed' : 'Saved';
Expected output
Saved

Key points

  • Read and write files with explicit paths and checked results.
  • Handle expected errors explicitly without exposing diagnostics.
  • Keep dependency and runtime configuration reproducible.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.