Current Location: Home> Latest Articles> How to Use the main Function to Complete File Upload? A Complete Process and Example Analysis

How to Use the main Function to Complete File Upload? A Complete Process and Example Analysis

gitbox 2025-06-18

In PHP development, file uploading is a common feature. Although PHP does not have an entry point like the C language’s main function, we can simulate the structure of a main function to centralize the file upload business logic, improving the organization and maintainability of the code.

This article will explain in detail how to use the main function to complete the file upload operation, including the complete upload process and example code, to help you quickly understand and implement file uploads.


Basic Process of File Upload

  1. Create an Upload Form on the Frontend Page
    Users select files through an HTML form. The form’s enctype must be set to multipart/form-data to ensure the file can be uploaded correctly.

  2. Receive the Uploaded File
    PHP receives the uploaded file information through the $_FILES superglobal array.

  3. Validate the File
    This includes checking the file type, size restrictions, and security checks.

  4. Move the File to the Target Directory
    Use the move_uploaded_file function to move the temporary file to the specified directory.

  5. Return the Processing Result
    Notify the user whether the upload was successful or explain the reason for failure.


Encapsulate Upload Logic Using the main Function

Normally, PHP scripts do not have a main function, but we can define a main function and write the business logic inside it. The function is called at the end of the script to achieve process control and clear code structure.


Example Code

Here is a complete file upload example showing how to use the main function to complete the upload operation. The domain name in the example URL has been replaced with m66.net.

<?php
function main() {
    // Target directory for uploaded files
    $targetDir = "uploads/";
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

// Check if a file has been uploaded
if (!isset($_FILES['file'])) {
    echo "No file detected for upload";
    return;
}

$file = $_FILES['file'];

// Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
    echo "Error uploading file, error code: " . $file['error'];
    return;
}

// File size limit: max 5MB
$maxSize = 5 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    echo "File too large, must be less than 5MB";
    return;
}

// Allowed file extensions
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
$fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

if (!in_array($fileExt, $allowedExt)) {
    echo "Unsupported file type";
    return;
}

// Generate a unique file name to prevent overwriting
$newFileName = uniqid() . "." . $fileExt;
$targetFile = $targetDir . $newFileName;

// Move the temporary file to the target directory
if (move_uploaded_file($file['tmp_name'], $targetFile)) {
    echo "File uploaded successfully! Access link: ";
    echo "<a href=\"https://m66.net/" . $targetFile . "\">https://m66.net/" . $targetFile . "</a>";
} else {
    echo "File upload failed, error moving file";
}

}

// Call the main function to execute the upload logic
main();
?>


Frontend Upload Form Example

<form action="https://m66.net/upload.php" method="post" enctype="multipart/form-data">
    <label for="file">Choose a file to upload:</label>
    <input type="file" name="file" id="file" required>
    <button type="submit">Upload</button>
</form>

Explanation

  • The above PHP example assumes that the upload file directory is uploads/ and it will be automatically created (with 0755 permissions).

  • After a successful upload, the page will output an access link with the domain m66.net, making it easy to access the file.

  • The code limits the file size and type to ensure security and compliance.

  • By encapsulating the main function, the code logic is clear and easy to maintain.


In summary, although PHP does not have a traditional main function, simulating the main function structure can make the file upload code more modular and clear. Mastering the file upload process, combined with reasonable function encapsulation, can make your PHP applications more robust and maintainable.