Uploads and .htaccess
Two things make a PHP site feel finished: a visitor can upload a file, and the addresses look clean. In PHP the upload arrives in a superglobal, and the clean address comes from a rule in .htaccess.
The $_FILES array
A form with a file input arrives in $_FILES, not $_POST. Each entry carries five keys: name, type, tmp_name, error, and size. Check error first - it tells whether a file arrived at all.
The file upload.php in the folder you serve with php -S 127.0.0.1:8000:
<?php if ($_FILES["photo"]["error"] === UPLOAD_ERR_OK) { echo $_FILES["photo"]["size"]; }
curl -s -F "photo=@photo.png" "http://127.0.0.1:8000/upload.php"
5
The request carries a five-byte file named photo.png, and the script answers with its size. The other keys of the entry hold the client name, the temporary path and the extension the browser claimed.
Validate and move
Uploaded files sit in a temp folder and vanish at the end of the request. Keep them with move_uploaded_file(), but only after checks: a real upload, a sane size, an allowed extension. Never trust the client name - build the target name yourself.
The file move.php in the same folder:
<?php $ext = strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION)); if ($ext === "png" || $ext === "jpg") { $target = sys_get_temp_dir() . "/img_" . time() . "." . $ext; move_uploaded_file($_FILES["photo"]["tmp_name"], $target); echo "moved ", $ext; unlink($target); } else { echo "refused ", $ext; }
curl -s -F "photo=@photo.png" "http://127.0.0.1:8000/move.php"
moved png
The extension is lowered and checked, the target name is built by the script and the temporary file moves there. The same request with a photo.php file answers refused php instead, which is the check that keeps code out of the upload folder.
Clean URLs with rewrite
Clean URLs turn post.php?id=7 into post/7. Apache does it with rewrite rules in .htaccess: match the pretty path, silently serve the real file. PHP keeps reading $_GET like nothing changed.
RewriteEngine On RewriteRule ^post/([0-9]+)$ post.php?id=$1 [L]
The pattern is anchored at both ends, so it matches post/7 and nothing longer. The replacement passes the captured number to the real file, and PHP finds it in $_GET["id"].
Safe rule patterns
Order rules from specific to general, anchor both ends, and end each rule so matching stops after the first hit. Test with curl after every edit - one greedy rule can swallow the whole site. The full rule reference is Creating rules in .htaccess.
RewriteRule ^about$ about.php [L] RewriteRule ^post/([0-9]+)$ post.php?id=$1 [L]
The exact address comes before the pattern, and each rule stops the run with [L]. A request for /about therefore reaches about.php and never falls into the post rule below it.
Exercises
- Refuse a file larger than two megabytes in move.php and print the reason.
- Send a photo.php file to move.php and check which branch answers.
- Add a rewrite rule that turns /tag/php into tag.php?name=php.
- Put the general post rule above the exact about rule and describe what happens to /about.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which superglobal holds an uploaded file?
Answer
$_FILESThe file input is filled into $_FILES with its own entry for each field name.
-
Which key of an upload entry tells whether the file arrived?
Answer
errorThe error key is UPLOAD_ERR_OK only when the upload completed, so it is checked first.
-
What does
move_uploaded_file()do?Answer
It moves the temporary file to the target path
The function is the safe way to take the uploaded temporary file out of the temp folder.
-
What should the target name of an upload be built from?
Answer
A base name of the script plus an allowed extension
The client name can carry a path or a dangerous extension, so the script builds its own name.
-
What does this program print?
<?php $files = ["photo" => ["name" => "Photo.PNG"]]; echo strtolower(pathinfo($files["photo"]["name"], PATHINFO_EXTENSION));Answer
png
pathinfo returns the part after the last dot and strtolower makes it lower case.
-
What does this program print?
<?php $files = ["photo" => ["error" => 4]]; var_dump($files["photo"]["error"] === UPLOAD_ERR_OK);Answer
bool(false)
The error code 4 means no file was uploaded, so it is not the OK constant.
-
What does this program print?
<?php echo UPLOAD_ERR_OK;Answer
0
The constant is the integer zero, the code of a successful upload.
-
What does this program print?
<?php preg_match("#^post/([0-9]+)$#", "post/7", $m); echo $m[1];Answer
7
The digits after post/ are the first capture group, so they land in $m[1].
-
Why is the extension of the client name not enough to trust an upload?
Answer
A file named .png can still hold code or another format
The name is written by the client, so the script checks the real type and stores the file under its own name.
-
What does the
[L]flag of a rewrite rule do?Answer
It stops the processing of further rules after this match
The rule is the last one for that request, which keeps later patterns from rematching it.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev