SoFunction
Updated on 2025-04-04

PHP implements image upload and replace operations

First create two files: and

The form code of the file is as follows:

<html>
<head>
<title>change file example.</title>
<meta charset="UTF-8">
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<table border=0 cellspacing=0 cellpadding=0 align=center width="100%">
<tr>
<td width=55 height=20 align="center">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
document:
</td>
<td>
<input name="file" type="file" />
<input type="submit" name="submit" value="submit" /> 
</td>
</tr>
</table>
</form>
</body>
</html>

Here are a few things to pay attention to, first look at this sentence<form method="post" action="" enctype="multipart/form-data">,Here we use the POST method, and some browsers also support the PUT method. Of course, this requires modification of the script, and I do not recommend doing this. Must be set in the formenctype="multipart/form-data, so that the server knows that the uploaded file contains the regular form information, remember, this must be set. In addition, a hidden domain is needed to limit the maximum length of uploaded files:<input type="hidden" name="MAX_FILE_SIZE" value="2000000">,Here the name must be set to MAX_FILE_SIZE, and its value is the maximum length of the uploaded file, the unit is B, and I limit it to 2M here. Look at this sentence again: <input name="file" type="file"   value="browse" >,type="file" explains the file type, and such a basic upload file interface is completed. Next, let’s talk about how to use PHP to process uploaded files. In addition, the maximum length of the uploaded file set in your may affect your actual transmission. Please modify it according to the actual situation. In addition, the upload of PHP is first transmitted to the temporary directory and moved to the specified directory. The temporary directory can be modified as needed, or the default value can be used...

The following is the form submission file code. Let’s see what this file has:

&lt;?php
header("content-type:text/html;charset=utf-8");

 

/**
 * @param string $oldfile file name that needs to be replaced (including specific path name)
 */
function changeFile($oldfile){
$newfile = $_FILES['file']['name'];//Get uploaded file name$fileclass = substr(strrchr($newfile, '.'), 1);//Get the uploaded file extension and use it for judgment$type = array("jpg", "gif", "bmp", "jpeg", "png");//Set the type that allows uploading of filesif(in_array(strtolower($fileclass), $type)){
if(file_exists($oldfile)){
unlink($oldfile);
}

if(is_uploaded_file($_FILES['file']['tmp_name'])){//It must be uploaded through PHP's HTTP POST upload mechanismif(move_uploaded_file($_FILES['file']['tmp_name'], $oldfile)){ 
//Output picture previewecho "&lt;center&gt;Your file has been uploaded Upload image preview: &lt;/center&gt;&lt;br&gt;&lt;center&gt;&lt;img src='$oldfile'&gt;&lt;/center&gt;";
}
}else{
echo "<center>Upload failed, the file is greater than 2M, please upload it again!</center>";
}
}else{
$text = implode(",", $type);
echo "<center>You can only upload the following types of files:", $text, "&lt;/center&gt;&lt;br&gt;";
// echo "<script>alert('You can only upload files of the following types: $text')</script>";}
}

changeFile("./files/");

You may be a little dizzy when you just read these~~, look slowly, and you will find that this thing is actually SO EASY! ! Let’s talk about the principle first. This program uploads pictures as an example. First, determine whether the file type is in the image format. If so, upload the file, then upload the file to and replace the specified file. If it is successfully uploaded, output the uploaded image preview. Here we need to explain some functions in the program. See firstsubstr(strrchr($newfile, '.'), 1), What is the function of the strrchar() function? I will give you an example to know. For example, we use strrchar() to process it. strrchr(,'.'), and it will return .jpg. Do you understand? This function returns the string after the specified character appears at the last position of the string. With substr() we can get jpg, so we get the suffix name of the file to determine whether the uploaded file meets the specified format. This program places the specified format in an array and can be added as needed when actually used.
Next, we call the function that determines the file type and convert it to lowercasestrtolower($_FILES['file']['name']),There is a very critical thing here $_FILES, which is a super global array that saves the form data that needs to be processed. If register_globals is enabled, it can also be accessed directly, but this is not safe. Look at the upload interface just now <inputname="file" type="file">, based on this form name, we can get a lot of information:
$_FILES['file']['name']--   Get the file name
$_FILES['file']['tmp_name']-get temporary storage location
$_FILES['file']['size']-get file size
$_FILES['file']['type']-get file MIME type
By obtaining this information, you can easily judge the information of the file. Isn’t it very convenient? ^_^, next there are some functions to understand, file_exists()--judgment whether the specified directory exists. If it does not exist, we cannot upload it (it seems nonsense!), is_uploaded_file--judgment whether the file has been uploaded through HTTP POST, move_uploaded_file--moves the uploaded file to the specified directory. If the upload is successful, we will output the preview, otherwise the output upload will fail...

The content is very detailed, and the process is recorded for everyone to study carefully. I hope it will be helpful to everyone's learning.