Get only filename from url in php without any variable values which exist in the url Get only filename from url in php without any variable values which exist in the url php php

Get only filename from url in php without any variable values which exist in the url


This should work:

echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);

But beware of any malicious parts in your URL.


Following steps shows total information about how to get file, file with extension, file without extension. This technique is very helpful for me. Hope it will be helpful to you too.

  $url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';        $file = file_get_contents($url); // to get file        $name = basename($url); // to get file name        $ext = pathinfo($url, PATHINFO_EXTENSION); // to get extension        $name2 =pathinfo($url, PATHINFO_FILENAME); //file name without extension


Is better to use parse_url to retrieve only the path, and then getting only the filename with the basename. This way we also avoid query parameters.

<?php// url to inspect$url = 'http://www.example.com/image.jpg?q=6574&t=987';// parsed path$path = parse_url($url, PHP_URL_PATH);// extracted basenameecho basename($path);?>

Is somewhat similar to Sultan answer excepting that I'm using component parse_url parameter, to obtain only the path.