Files and uploads
Read and write files safely and validate uploaded files before trusting them.
What you will be able to do
- Use file_get_contents and file_put_contents for small files.
- Check upload errors and is_uploaded_file.
- Generate a random filename and keep the extension whitelist.
- Never execute uploaded content.
In plain English
File access is ordinary PHP until users are involved. Uploads need a size limit, a type check and a generated filename; never trust the client-supplied name or extension. Store uploads outside the document root when possible.
<?php
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
$file = $_FILES['photo'] ?? null;
if ($file && $file['error'] === UPLOAD_ERR_OK && $file['size'] <= 2_000_000) {
$type = mime_content_type($file['tmp_name']);
if (isset($allowed[$type])) {
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$type];
move_uploaded_file($file['tmp_name'], __DIR__ . '/uploads/' . $name);
echo 'Saved ' . htmlspecialchars($name);
}
}Your turn
EasyAppend a log line
Append a timestamped line to app.log using FILE_APPEND and LOCK_EX.
PHP · starter
$line = date('c') . " visited\n";Check your understanding before moving on.
Knowledge checkQuestion 1
Which function moves a verified uploaded file into its final location?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.