w3resource

PHP file extension checker: Display messages for different file types

PHP File Handling: Exercise-12 with Solution

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

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.