WebMasterCampus
WEB DEVELOPER Resources

Php Change a File Extension Easily

Learn how to change a file extension easily in PHP


Change a File Extension

How can I change a file’s extension using PHP? The answer is very simple because PHP provides out of the box functionality to deal with files. Although, for file path, naming, directory name we can use some functions like pathinfo, basename and dirname.

pathinfo returns an array with key value. You can use following keys to get the specified value.

pathinfo Keys

  • dirname
  • basename
  • extension
  • filename
<?php
    $URL = "https://www.useyourlocaldevelopment.com/images/logo.jpg";

    $path_parts = pathinfo ($URL);

    echo $path_parts['dirname'], "<br>";
    echo $path_parts['basename'], "<br>";
    echo $path_parts['extension'], "<br>";
    echo $path_parts['filename'], "<br>";


	echo  $path_parts['dirname'] ."/". $path_parts['filename'].".png";

Other than pathinfo we have basename and dirname. These two functions return the string.

<?php
    $URL = "https://www.useyourlocaldevelopment.com/images/logo.jpg";

	echo basename ($URL), "<br>";  // basename return fileName with extension
	echo dirname ($URL), "<br>"; //dirname retrn directory Name
Created with love and passion.