100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
PHP

File Uploads in PHP

Learn how PHP handles multipart form uploads through the $_FILES superglobal, including validation, error codes, and safely moving uploaded files on disk.

Web Development with PHPIntermediate9 min readJul 9, 2026
Analogies

File Uploads in PHP

PHP has built-in support for handling file uploads submitted through HTML forms using the multipart/form-data encoding. When a browser submits such a form, PHP automatically parses the request body and populates the $_FILES superglobal with metadata about each uploaded file, while the raw bytes are written to a temporary location on disk. Your script's job is to validate that upload and move it to a permanent, safe location before the request ends and PHP cleans up the temp file.

🏏

Cricket analogy: When a player submits their kit bag at the stadium gate, ground staff log its contents and stash it in a temporary holding room until match officials formally clear it for the dressing room — just as PHP parks an upload in a temp file until your script clears it.

The $_FILES superglobal structure

For a form field named avatar, $_FILES['avatar'] is an associative array with keys name (original client-side filename), type (client-supplied MIME type, which is untrustworthy), tmp_name (the server-side temp path), error (an UPLOAD_ERR_* constant), and size (bytes). If the field allows multiple files via avatar[], each of these becomes a nested array indexed by position, which requires careful reshaping if you want one struct per file.

🏏

Cricket analogy: A scorer's entry sheet for a single batter lists name, declared batting style, actual delivery footage, dismissal code, and runs scored — and if multiple batters submit at once, each field becomes a list indexed by batting order, just like $_FILES['avatar'][] for multiple uploads.

php
<?php
declare(strict_types=1);

enum UploadStatus {
    case Ok;
    case TooLarge;
    case BadType;
    case UploadError;
}

function handleAvatarUpload(array $file, string $destDir): UploadStatus
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return UploadStatus::UploadError;
    }

    $maxBytes = 2 * 1024 * 1024; // 2MB
    if ($file['size'] > $maxBytes) {
        return UploadStatus::TooLarge;
    }

    // Never trust $file['type'] — inspect the real content instead.
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];
    if (!isset($allowed[$mime])) {
        return UploadStatus::BadType;
    }

    $ext = $allowed[$mime];
    $safeName = bin2hex(random_bytes(16)) . '.' . $ext;

    if (!is_uploaded_file($file['tmp_name'])) {
        return UploadStatus::UploadError;
    }

    move_uploaded_file($file['tmp_name'], rtrim($destDir, '/') . '/' . $safeName);

    return UploadStatus::Ok;
}

Validating size, type, and origin

Robust upload handling checks four things independently: the error code, the size against both php.ini limits and your own application limit, the actual file content type via fileinfo rather than the client-supplied MIME string, and that the temp file was genuinely produced by PHP's upload mechanism. That last check matters because tmp_name is just a string — without verifying it, a maliciously crafted request could reference an arbitrary server path.

🏏

Cricket analogy: Before certifying a bat for match use, officials independently check its willow grade, physical dimensions against the rulebook, an actual edge-thickness measurement rather than the manufacturer's claim, and a genuine certification stamp — four separate checks, just like robust upload validation.

PHP enforces two separate size ceilings from php.ini: upload_max_filesize caps a single file, while post_max_size caps the entire request body (all fields and files combined). If post_max_size is smaller than upload_max_filesize, large uploads silently fail — always keep post_max_size comfortably larger.

Moving and storing files safely

Always use move_uploaded_file() rather than rename() or copy() for the initial relocation — it internally verifies the source path is a genuine PHP upload before touching the filesystem, which rename() does not. Generate a new random filename instead of trusting the client's original name, since filenames can contain path traversal sequences like ../../etc/passwd or null bytes. Store uploads outside the web root when possible, or in a directory with script execution disabled, so an uploaded .php file can never be requested and executed directly.

🏏

Cricket analogy: A ground's official kit inspector uses a certified scale that verifies a bat is genuinely stamped for match use before it enters the field, rather than just glancing at a label — just as move_uploaded_file() verifies genuine PHP-uploaded origin, unlike rename().

Never store uploaded files inside a publicly served directory that also executes PHP. If an attacker can upload a file with a .php extension (or trick an extension check) and then request it via URL, the web server will execute it as code — a classic remote-code-execution path known as an unrestricted file upload vulnerability.

Understanding UPLOAD_ERR_* codes

PHP populates $file['error'] with one of several constants: UPLOAD_ERR_OK (0) means success, UPLOAD_ERR_INI_SIZE and UPLOAD_ERR_FORM_SIZE mean the file exceeded configured or form-specified limits, UPLOAD_ERR_PARTIAL means only part of the file arrived, UPLOAD_ERR_NO_FILE means no file was submitted, and UPLOAD_ERR_NO_TMP_DIR or UPLOAD_ERR_CANT_WRITE indicate server-side filesystem problems. Checking this code first, before inspecting size or tmp_name, avoids acting on a failed upload.

🏏

Cricket analogy: A match official checks the toss result code first — rain delay, no result, or completed — before even looking at the scoreboard, because acting on a score from an abandoned match would be meaningless, just as PHP checks $file['error'] before size or tmp_name.

  • $_FILES is populated automatically for multipart/form-data requests; tmp_name points to a temporary server file that is deleted at request end.
  • Always check $file['error'] against UPLOAD_ERR_OK before doing anything else with the upload.
  • Never trust the client-supplied 'type' or original 'name' — verify content type with fileinfo and generate a new random filename.
  • Use move_uploaded_file() (not rename/copy) so PHP verifies the file genuinely came through its upload mechanism.
  • post_max_size must be >= upload_max_filesize or large uploads fail silently.
  • Store uploads outside the web root or in a non-executable directory to prevent uploaded scripts from being run.

Practice what you learned

Was this page helpful?

Topics covered

#PHP#PHPProgrammingStudyNotes#Programming#FileUploadsInPHP#File#Uploads#FILES#Superglobal#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse