search
HomeBackend DevelopmentPHP TutorialUse PHP to implement a simple version of file upload function (super detailed explanation)

1. PHP simplified version of image upload (without various verifications)

<form action="" enctype="multipart/form-data" method="post" >
请选择需要上传的文件:<input type="file" name="upfile" /><br>
<input type="submit" value="上传" />
</form>

First of all, we need to add enctype="multipart/form-data" to the form form to indicate that there will be images sent in the declaration form. action=”” means the current page is submitted, method=”post” The transmission method is post

<?php
if(is_uploaded_file($_FILES[&#39;upfile&#39;][&#39;tmp_name&#39;])){
$upfile=$_FILES["upfile"];
$name=$upfile[&#39;name&#39;];
$tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
move_uploaded_file($tmp_name,&#39;up/&#39;.$name);
echo "上传成功";
}
else{
    echo "您还没有上传文件";
}
?>

Keyword summary

is_uploaded_file means to verify whether the file is uploaded through HTTP POST, and the conditions are met. Normal upload

$_FILES['upfile']['tmp_name']) means getting the local location of the currently transferred image

move_uploaded_file($tmp_name,'up/'.$name); , this method has two parameters, the first is the file name of the uploaded file, the second is to move the file to this location

2. Writing and reading files

First Introduction to writing:

     $myfile = fopen("comment/" .time().&#39;-&#39;. rand(0, 1000) . ".comment", "a") or die("Unable to open file!");
        $txt = time().&#39;<br />&#39;;
        fwrite($myfile, $txt);
        fclose($myfile);

The role of the fopen function is to write data. The first parameter is the specific path to the file, and the second parameter means to put the read data into the file, where the file The name is composed of a timestamp plus a random number, and the suffix is ​​comment. A means opening in writing mode and pointing the file pointer to the end of the file. If the file does not exist, try to create it, or die means the execution fails, and execute Unable to open file! (unable to open the file).

The second sentence means data. The data can be transmitted by post or get, whatever you want

The third sentence fwrite means writing to the file. The first parameter is the location of the written file. , the second one is the data to be written

The fourth sentence means closing the file, indicating that the writing is completed, and this execution is completed

$list = glob("comment/*.comment");
rsort($list);
for ($i = 0; count($list) > $i; $i++) {
    $file_path = $list[$i];
    if (file_exists($file_path)) {
        $fp = fopen($file_path, "r");
        $str = fread($fp, filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
        echo $str = str_replace("\r\n", "<br />", $str);
    }
}

Read in the introduction:

The key statement is

The first sentence: First use (glob) to find the file that needs to be read. If there are many files that meet the conditions, then they will be saved in an array, and traversal is used when reading. Arrays are enough

Second sentence: rsort is descending order, mainly to meet the sorting under specific conditions, such as according to release time

Third sentence: Because it can be sorted through var_dump, print, etc. We know that glob saves paths in the form of an array, so we use count to calculate the total, and then traverse one by one to get the file path that needs to be read

The fourth sentence: $file_path gets the file path

Fifth sentence: file_exists determines whether the file exists

Sixth sentence: fopen reads the file and opens it in read-only mode

Seventh sentence: fread first parameter Indicates what is read, and the second one indicates the size of the file read, which here also indicates how much is read.

The eighth sentence: str_replace replacement function means replacing all \r\ in $str Replace n with br (indicates line break, replace it with line break in the web page)

The above is the detailed content of Use PHP to implement a simple version of file upload function (super detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version