AllordEmad AllordEmad - 4 months ago 20
PHP Question

Url ends with specific file format

Hi guys i want a way to echo something if the end of the url is mp4 or txt or any other files formats like this

<?php
$url = $_SERVER['REQUEST_URI'];
if (substr($url,-9)=="php"){
echo "the url end with php";
} else {
echo "the url doesn't end with php";
}
?>


but it doesn't work please some help

Answer

Checkout pathinfo() in the PHP core as well as parse_url(): http://php.net/parse_url. http://php.net/manual/en/function.pathinfo.php

Use it with $_SERVER['REQUEST_URI'] and the PATHINFO_EXTENSION flag. This should help. Then you can use it within a switch statement:

$url_parts = parse_url($_SERVER['REQUEST_URI']);
$extension = pathinfo($url_parts['path'], PATHINFO_EXTENSION);

switch ($extension) {
 case "mp4":
   //do something for mp4.
   break;
 case "wav":
   //do something for wav.
   break;
}

This works for if the URL has paramters on it as well. http://website.com/file.mp4?param=var would still yeild mp4. Using just pathinfo() would give you "mp4?param=var" in this case.

I've not run this code, just I expect it to work. You may also want to use strtolower() before your extension just in case its in upper case in the address bar.