PHP Tutorial: File Reading, Writing, and Upload Functionality

![[PHP 강의] PHP 8.4 웹 프로그래밍 강의를 시작하며 – 초보도 끝까지 완주할 수 있는 실전 강의](/uploads/editor/PHP-%EA%B0%95%EC%9D%98-PHP-8-4-%EC%9B%B9-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%EA%B0%95%EC%9D%98%EB%A5%BC-%EC%8B%9C%EC%9E%91%ED%95%98%EB%A9%B0-%EC%B4%88%EB%B3%B4%EB%8F%84-%EB%81%9D%EA%B9%8C%EC%A7%80-%EC%99%84%EC%A3%BC%ED%95%A0-%EC%88%98-%EC%9E%88%EB%8A%94-%EC%8B%A4%EC%A0%84-%EA%B0%95%EC%9D%98-20260702-5787b7.webp)
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
errorYou 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:
1048576This 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.phpUploaded 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:
jpgor
pngdepending 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
enctypeNot using
move_uploaded_file()Missing the
uploadsfolderIncorrect 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강 파일 읽기·쓰기와 파일 업로드 기능 만들기