search
HomeBackend DevelopmentPHP TutorialTeach you step by step how to use php to implement the image upload function

Teach you step by step how to use php to implement the image upload function

In order to test the image upload function and save the image path to the database, we must first create a new test table test_img.

Teach you step by step how to use php to implement the image upload function

CREATE TABLE test_img (
	id int(4) UNSIGNED NOT NULL AUTO_INCREMENT,
	path varchar(100) default NULL,
	upload_time  timestamp default CURRENT_TIMESTAMP,
	PRIMARY KEY(id)
)engine=myisam DEFAULT charset=utf8

sql command: Generate a unique number when inserting into the table. For example, if there is too much test data, the id will continue to increase by itself. If you want to Returning to step 1, you can try the following commands.

alter table test_img auto_increment = 1

Second, create a newimg.html file for selecting uploaded images

<!DOCTYPE html><html lang="utf-8"><head>
    <meta charset="UTF-8">
    <title>图片上传</title></head><body><form action="img.php" method="post" enctype="multipart/form-data">
    选择上传的图片: <input type="file" name="file" accept="image/*">
    <br><br>
    <input type="submit" value="上传"></form>

&lt ;form> The enctype in the tag controls whether to encode and send the form data. The default is application/x-www-form-urlencoded, which means all characters are encoded before sending.

##application/x-www-form-urlencoded Encode all characters before sending (default) multipart/form-dataDo not encode characters. This value must be used when using a form that contains a file upload controltext/plainSpaces are converted to " " plus signs, but special characters are not encoded
Value Description
##

accept in the tag limits the upload format.

三新

img.php Used to accept and process images

$_FILES

Get the image file and add the specific file name to the data table test_img, move_uploaded_file Store the image file in the target folder, iconv perform character encoding to prevent garbled characters after uploading images with Chinese names. <pre class='brush:php;toolbar:false;'>&lt;?php header(&quot;Content-Type: text/html;charset=utf-8&quot;); $conn = new mysqli(&amp;#39;localhost&amp;#39;, &amp;#39;root&amp;#39;, &amp;#39;&amp;#39;, &amp;#39;test&amp;#39;); if (!$conn) { die(&quot;Connection failed: &quot; . mysqli_connect_error()); } $destination = &amp;#39;../upload/image/&amp;#39;; $file = $_FILES[&amp;#39;file&amp;#39;]; // 获取上传的图片 $filename = $file[&amp;#39;name&amp;#39;]; $insert = &quot;INSERT INTO test_img (path) VALUES (&amp;#39;$filename&amp;#39;)&quot;; $test = move_uploaded_file($file[&amp;#39;tmp_name&amp;#39;], $destination . iconv(&quot;UTF-8&quot;, &quot;gb2312&quot;, $filename)); if ($insert &amp;&amp; $test) { $conn-&gt;query($insert); } else { echo &amp;#39;上传失败&amp;#39; . &amp;#39;&lt;br&gt;&amp;#39;; } $select = &amp;#39;SELECT path FROM test_img&amp;#39;; $result = $conn-&gt;query($select); while ($row = $result-&gt;fetch_assoc()) { echo &quot;&lt;img src=&quot;/static/imghwm/default1.png&quot; data-src=&quot; . $destination . $row[&amp;#39;path&amp;#39;] . &quot; class=&quot;lazy&quot; alt=&quot;Teach you step by step how to use php to implement the image upload function&quot; &gt;&quot;; }</pre>

print_r( $_FILES['file']); // Output the received uploaded image and get the following information

After the image is successfully uploaded, pass the data table The picture information matches the pictures under

upload/image

and is displayed in a loop. The effect is as follows.

Write four to the end

The above is just a rough version of how to upload pictures in PHP. You can try to modify and improve some details yourself. If you want to learn well, you must learn it by yourself. Cloud learning can only scratch the surface. If my sharing can help If you have some inspiration, why not give me a like and encourage me? Of course, you don’t have to give it, I will also drive myself to learn~

Thank you everyone for reading, I hope you can gain something

Recommended tutorial: "

php tutorial

"

The above is the detailed content of Teach you step by step how to use php to implement the image upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

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.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft