


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
.
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>
< ;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.
Value | Description |
---|---|
Encode all characters before sending (default) | |
Do not encode characters. This value must be used when using a form that contains a file upload control | |
Spaces are converted to " " plus signs, but special characters are not encoded |
accept
in the tag limits the upload format.
img.php Used to accept and process images
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;'><?php
header("Content-Type: text/html;charset=utf-8");
$conn = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;&#39;, &#39;test&#39;);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$destination = &#39;../upload/image/&#39;;
$file = $_FILES[&#39;file&#39;]; // 获取上传的图片
$filename = $file[&#39;name&#39;];
$insert = "INSERT INTO test_img (path) VALUES (&#39;$filename&#39;)";
$test = move_uploaded_file($file[&#39;tmp_name&#39;], $destination . iconv("UTF-8", "gb2312", $filename));
if ($insert && $test) {
$conn->query($insert);
} else {
echo &#39;上传失败&#39; . &#39;<br>&#39;;
}
$select = &#39;SELECT path FROM test_img&#39;;
$result = $conn->query($select);
while ($row = $result->fetch_assoc()) {
echo "<img src="/static/imghwm/default1.png" data-src=" . $destination . $row[&#39;path&#39;] . " class="lazy" alt="Teach you step by step how to use php to implement the image upload function" >";
}</pre>
After the image is successfully uploaded, pass the data table The picture information matches the pictures under
and is displayed in a loop. The effect is as follows.
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 tutorialThe 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!

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

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

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.

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

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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Powerful PHP integrated development environment

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
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
