In PHP development, retrieving a file's extension is a common and essential task, especially when handling file uploads and verifying file types. This article introduces several commonly used PHP methods to obtain file extensions and demonstrates the complete process with a practical example.
A file extension is the part of a file name following the last period (".") and is used to identify the file type. For example, in the file name "example.txt", the extension is "txt". Extensions help the system recognize the file type and decide which program to use to open it.
PHP offers multiple functions to easily extract a file's extension. Here are two common and practical methods:
The pathinfo() function returns an associative array containing path information, allowing direct retrieval of the extension.
$file = 'example.txt';
$ext = pathinfo($file, PATHINFO_EXTENSION);
echo $ext;
This will output: txt.
The strrchr() function returns the part of a string starting from the last occurrence of a specified character. Combined with substr(), it can extract the extension without the dot.
$file = 'example.txt';
$ext = strrchr($file, '.');
// Outputs .txt
// Remove the dot
$ext = substr($ext, 1);
echo $ext;
This also outputs: txt.
Below is a common file upload scenario showing how to get the uploaded file鈥檚 extension and perform type and size validation.
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileExt = strtolower(end(explode('.', $fileName)));
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$allowed = array('jpg', 'jpeg', 'png', 'gif');
if (in_array($fileExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
$fileNameNew = uniqid('', true) . '.' . $fileExt;
$fileDest = "uploads/" . $fileNameNew;
move_uploaded_file($fileTmpName, $fileDest);
echo "File uploaded successfully!";
} else {
echo "Your file is too big!";
}
} else {
echo "There was an error uploading your file!";
}
} else {
echo "You cannot upload files of this type!";
}
}
This code obtains uploaded file info via $_FILES, extracts the extension, converts it to lowercase, and verifies that the file type is allowed. If the file size is within the limit and there are no upload errors, the file is saved to the specified directory with a unique name, and the upload result is reported.
This article thoroughly covers several methods for getting file extensions in PHP and uses a file upload example to help developers understand and master the basic workflow of extracting file extensions and handling uploads. Mastering these techniques will improve the efficiency and security of PHP file handling.