How to get the value of a file field in PHP
To obtain the value of a file field, you can use the $_FILES superglobal variable. The specific steps are as follows:
- Add a name attribute to the file field in an HTML form, for example.
- In PHP scripts, use the $_FILES superglobal variable to access the value of the file field. $_FILES is an array that contains information about all the file fields in the form.
- Retrieve the original file name of the uploaded file using $_FILES[‘fileField’][‘name’].
- Use $_FILES[‘fileField’][‘tmp_name’] to obtain the temporary file name of the uploaded file.
Below is a simple example code:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileField">
<input type="submit" value="Upload">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取上传文件的原始文件名
$fileName = $_FILES['fileField']['name'];
// 获取上传文件的临时文件名
$tmpFileName = $_FILES['fileField']['tmp_name'];
// 其他操作,例如将文件保存到指定目录中
move_uploaded_file($tmpFileName, 'uploads/' . $fileName);
}
?>
In the example above, we obtained the original file name of the uploaded file using $_FILES[‘fileField’][‘name’] and the temporary file name using $_FILES[‘fileField’][‘tmp_name’]. Next, we can use the move_uploaded_file function to save the uploaded file to a specified directory.