w3resource

PHP file extension checker: Display messages for different file types


12. Check File Extension and Display Messages

Write a PHP script to check the file extension and display appropriate messages for different file types.

Sample Solution:

PHP Code :

<?php
  $filename = "i:/test.txt";
//$filename = "i:/CTips.pdf";
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION);

switch ($fileExtension) {
    case "txt":
        echo "Text file detected.";
        break;
    case "jpg":
    case "jpeg":
    case "png":
        echo "Image file detected.";
        break;
    case "pdf":
        echo "PDF file detected.";
        break;
    default:
        echo "File type not supported.";
        break;
}
?>

Sample Output:

Text file detected.
PDF file detected.

Explanation:

In the above exercise -

  • The $filename variable holds the name of the file we want to check the extension for.
  • We use the pathinfo() function with the PATHINFO_EXTENSION constant to extract the file extension from the filename and store it in the $fileExtension variable.
  • We then use a switch statement to check the value of $fileExtension and perform different actions based on the detected file type.

Flowchart:

Flowchart: Display messages for different file types

For more Practice: Solve these Related Problems:

  • Write a PHP script to examine a file's extension and display custom messages for image, text, and PDF files.
  • Write a PHP function to determine if a file extension belongs to a set of allowed types and output an appropriate message.
  • Write a PHP program to validate file extensions before processing file uploads and display error messages for disallowed types.
  • Write a PHP script to automatically rename files based on their extensions and output corresponding status messages.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Program to add a string to an existing file.
Next: PHP function to check directory and create If not found.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.