Home >Backend Development >PHP Tutorial >How to use PHP to accept files and get their suffix names, _PHP tutorial
HTML form
Use an HTML form to simulate a post request for file upload. The code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>File Upload</title> </head> <body> <form enctype="multipart/form-data" action="test.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> Send this File:<input name="userfile" type="file"/> <input type="submit" value="Send File" /> </form> </body> </html>
Note:
Make sure the attribute of the file upload form is enctype="multipart/form-data", otherwise the file cannot be uploaded
PHP
First, we need to explain PHP’s global variable $_FILES. This array contains all uploaded file information
Ideas
1. Generate a 40-digit random string as the file name
2. Transfer the file to different file locations depending on whether it is a picture or a voice
3. No verification of file size and file type will be performed for the time being
function processFile($files, $type) { $uploadName = null; foreach ($files as $name => $value) { $originalName = $value['name']; $arr = explode(".", $originalName); $postfix = $arr[count($arr) - 1]; $tmpPath = $value['tmp_name']; $tmpType = $value['type']; $tmpSize = $value['size']; } $newname = EhlStaticFunction::generateRandomStr(40).".".$postfix; switch ($type) { case 1 : // 处理声音文件 $destination = VIDEOUPLOADDIR.$newname; break; case 2 : // 处理图像文件 $destination = IMAGEUPLOADDIR.$newname; break; } move_uploaded_file($tmpPath, $destination); }
To get the suffix of the uploaded file, you can use the following code:
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta name="keywords" content=" keywords" /> <meta name="description" content="description" /> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="upfile" size="20" /> <input type="submit" name="submit" value="submit" /> </form> </body> </html>
PHP
<?PHP if(isset($_POST['submit'])) { $string = strrev($_FILES['upfile']['name']); $array = explode('.',$string); echo $array[0]; } ?>
Example results: