KOSUNI KOREA
Korean News in English
Technology

PHP Tutorial: File Reading, Writing, and Upload Functionality

Published October 18, 2026 · 1 views
PHP Tutorial: File Reading, Writing, and Upload Functionality

[PHP 강의] PHP 8.4 웹 프로그래밍 강의를 시작하며 – 초보도 끝까지 완주할 수 있는 실전 강의


Why Do Websites Store Files?

So far, we've been working with string and numeric data.

However, real websites also manage various types of files.

For example:

  • Profile pictures

  • Board attachments

  • Product images

  • PDF documents

  • Excel files

  • Videos

These need to be stored on the server.

PHP provides various functions for easily reading and storing these files.


What Are File Reading and Writing?

File reading is the function of retrieving contents from a stored file.

File writing creates new files or modifies existing file contents.

This is commonly used for board log storage or configuration file management.


File Writing

Let's create a simple text file first.

<?php

$text = "Hello. This is PHP 8.4.";

file_put_contents("test.txt", $text);

echo "File saved successfully";

After execution, a test.txt file will be created in your project folder.


File Reading

Let's read the file we just created.

<?php

echo file_get_contents("test.txt");

Execution result:

Hello. This is PHP 8.4.

This is the basic principle for saving and reading files - very simple!


Adding Content to Existing Files

You can also add new content while keeping existing content.

<?php

file_put_contents(
    "log.txt",
    "Log entry\n",
    FILE_APPEND
);

Using the FILE_APPEND option adds new content to the end without deleting existing content.

This is commonly used when creating log files.


Checking if a File Exists

It's good practice to check if a file exists first.

<?php

if (file_exists("test.txt")) {
    echo "File exists.";
}

Trying to read a non-existent file can cause errors.


Deleting Files

You can delete unnecessary files as well.

<?php

unlink("test.txt");

In practice, when deleting posts, attachments are often deleted along with them.


What Is File Upload?

This is the feature that sends files from a user's computer to the server.

Common examples include:

  • User profile pictures

  • Board attachments

  • E-commerce product images

  • Resume uploads

In PHP, the $_FILES array is used to process uploaded files.


Creating an Upload Form

To enable file upload, you must add the enctype attribute.

<form method="post"
      enctype="multipart/form-data">
    <input
        type="file"
        name="photo">
    <button>
        Upload
    </button>
</form>

Without multipart/form-data, files won't be transmitted properly.


About $_FILES

This is the array that stores information about uploaded files.

<?php

print_r($_FILES);

After uploading, various information will be displayed:

For example:

name
size
tmp_name
error

You can check these details.


Checking File Names

<?php

echo $_FILES["photo"]["name"];

This retrieves the original file name.


Checking File Size

<?php

echo $_FILES["photo"]["size"];

File size is measured in bytes.

For example:

1048576

This equals approximately 1MB.


Temporary Files

Uploaded files are first stored in a temporary folder.

<?php

echo $_FILES["photo"]["tmp_name"];

You need to move this file to your desired location.


move_uploaded_file()

This is the function that actually stores files on the server.

<?php

move_uploaded_file(
    $_FILES["photo"]["tmp_name"],
    "uploads/" . $_FILES["photo"]["name"]
);

This is the most important function for file uploads.


Creating an Upload Folder

Create a folder within your project to store uploaded files.

project/
 ├── uploads/
 ├── index.php

Uploaded files will be stored in this folder.


Confirming Successful Uploads

<?php

if (
    move_uploaded_file(
        $_FILES["photo"]["tmp_name"],
        "uploads/" . $_FILES["photo"]["name"]
    )
) {
    echo "Upload successful";
}
else {
    echo "Upload failed";
}

Checking File Extensions

It's good practice to limit which files can be uploaded.

<?php

$ext = pathinfo(
    $_FILES["photo"]["name"],
    PATHINFO_EXTENSION
);

echo $ext;

For example, this might output:

jpg

or

png

depending on the file type.


Allowing Only Image Files

<?php

$allow = [
    "jpg",
    "jpeg",
    "png",
    "gif",
    "webp"
];

if (
    in_array(
        strtolower($ext),
        $allow
    )
) {
    echo "Upload allowed";
}

Preventing File Name Conflicts

If files with the same name are uploaded, they will overwrite existing files.

In practice, developers often use:

<?php

$fileName =
time() . "_" .
$_FILES["photo"]["name"];

or

uniqid()

To prevent name conflicts.


Limiting Upload Size

You can also limit the size of files users can upload.

<?php

if (
    $_FILES["photo"]["size"]
    > 5 * 1024 * 1024
) {
    echo "Only files under 5MB allowed.";
}

Checking for Upload Errors

<?php

if (
    $_FILES["photo"]["error"]
    == 0
) {
    echo "Successful upload";
}

If errors occur, different numbers will be returned.


Security Considerations for Real-World Use

File uploads must always consider security.

The following points are essential to check:

  • Extension checking

  • File size limits

  • Upload folder permissions

  • Renaming files

  • Preventing execution of PHP files

Failing to implement these checks can leave your server vulnerable to attacks.


Real-World Example

Let's create a simple image upload program:

<form
method="post"
enctype="multipart/form-data">
<input
type="file"
name="photo">
<button>
Upload
</button>
</form>

<?php

if (
    isset($_FILES["photo"])
) {
$fileName =
time() . "_" .
$_FILES["photo"]["name"];

move_uploaded_file(
$_FILES["photo"]["tmp_name"],
"uploads/" . $fileName
);

echo "Upload completed";
}

This structure is nearly identical to how board image uploads work.


Common Mistakes for Beginners

When first implementing file uploads, beginners often make these mistakes:

  • Forgetting to include enctype

  • Not using move_uploaded_file()

  • Missing the uploads folder

  • Incorrect permissions for upload folders

  • Not checking file size limits

  • Skipping extension checks

Checking these points will resolve most common upload issues.


How This Will Be Used in Future Board Projects

The upload functionality we've created can be directly applied to future board projects.

For example:

  • Uploading main images

  • Attaching files to posts

  • User profile pictures

  • Admin image uploads

All operate on the same principle.

If you fully understand this lecture, implementing future projects will be much easier.


In Conclusion

This session covered file reading/writing and file upload functionality.

File handling is a very common feature in web development, especially essential for boards and e-commerce sites.

Remember that file uploads require careful security considerations beyond just storing files.

In the next lesson, we'll learn about Cookies and Sessions, covering how to store user information - the core of login functionality.

FAQ

Why is the enctype attribute important in HTML forms?

The enctype="multipart/form-data" attribute is required for file uploads to work properly. Without it, files won't be transmitted from the user's browser to the server.

What does FILE_APPEND do in PHP?

FILE_APPEND allows you to add content to an existing file without deleting its current contents. It appends new data to the end of the file.

Korean Source

This article is an English localization of a Korean-language report from BlogScore. Original: [PHP 강좌] 6강 파일 읽기·쓰기와 파일 업로드 기능 만들기