Home >Backend Development >PHP Tutorial >PHP implements the function of uploading pictures
First you need a form, click the submit button to submit to the upload_file.php file
<form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form>
The upload_file.php file is as follows:
(recommended video tutorial : php video tutorial)
<?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "无效的文件"; }
The first step: Determine whether the image format is correct and whether the size is less than 2M, otherwise, "invalid file" will be output;
Second Step: Determine whether an error occurs. If there is an error, enter the error. If no error occurs, perform the next step;
Step 3: Output the image content and determine whether the image exists. If it exists, it will prompt, otherwise it will not. If it exists, perform the operation to save the image to the specified directory: upload.
Recommended related articles and tutorials: php tutorial
The above is the detailed content of PHP implements the function of uploading pictures. For more information, please follow other related articles on the PHP Chinese website!