Php filename file extension

How to Get a File Extension in PHP

In PHP, there exist various ways of getting a file extension. In our tutorial, we have chosen the 5 best ways that will help you to get a file extension straightforwardly.

Go ahead and choose the one that matches your project better.

Explode a File Variable

The first way is exploding a file variable and getting the last element of the array. That will be a file extension. Here is how you can do it:

 $fileName = 'banner.jpg'; $fileNameParts = explode('.', $fileName); $ext = end($fileNameParts); echo $ext; ?>

Find the Last Occurrence of ‘.’

In the framework of the second approach, we recommend detecting the last occurrence of ‘.’, which will return a ‘.jpg’ . Afterwards, you need to remove the first character of a string using substr. As a result, the exact file extension ‘.jpg’ will be returned.

 $fileName = 'banner.jpg'; $ext = substr(strrchr($fileName, '.'), 1); echo $ext; ?>

Use strrpos

The next way is to use strrpos for detecting the position of the last occurrence of ‘.’ inside a file name, incrementing that position by 1 so that it explodes a string from (.).

The example is shown below:

 $fileName = 'banner.jpg'; $ext = substr($fileName, strrpos($fileName, '.') + 1); echo $ext; ?>

Use preg_replace

In the framework of this approach, you should apply a regular expression reach and replacement.

 $fileName = 'banner.jpg'; $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName); echo $ext; ?>

Use pathinfo

And, the final approach that we recommend is to use the PHP pathinfo() function. It is aimed at returning information about the file. In case the second optional parameter is not passed, an associative array will be returned. It will include the dirname, extension, basename, and filename. Once the second parameter is passed, then specific information will be returned.

 $fileName = 'banner.jpg'; $ext = pathinfo($fileName, PATHINFO_EXTENSION); echo $ext; ?>

So, after learning about all the possible ways described above, you are free to choose the best one for you. In our opinion, the simplest, yet the most efficient way among all these options is the pathinfo() function.

Источник

pathinfo

pathinfo() returns information about path : either an associative array or a string, depending on flags .

Note:

For information on retrieving the current path info, read the section on predefined reserved variables.

Note:

pathinfo() operates naively on the input string, and is not aware of the actual filesystem, or path components such as » .. «.

Note:

On Windows systems only, the \ character will be interpreted as a directory separator. On other systems it will be treated like any other character.

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Parameters

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION or PATHINFO_FILENAME .

If flags is not specified, returns all available elements.

Return Values

If the flags parameter is not passed, an associative array containing the following elements is returned: dirname , basename , extension (if any), and filename .

Note:

If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).

Note:

If the path does not have an extension, no extension element will be returned (see second example below).

Note:

If the basename of the path starts with a dot, the following characters are interpreted as extension , and the filename is empty (see third example below).

If flags is present, returns a string containing the requested element.

Examples

Example #1 pathinfo() Example

$path_parts = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

echo $path_parts [ ‘dirname’ ], «\n» ;
echo $path_parts [ ‘basename’ ], «\n» ;
echo $path_parts [ ‘extension’ ], «\n» ;
echo $path_parts [ ‘filename’ ], «\n» ;
?>

The above example will output:

/www/htdocs/inc lib.inc.php php lib.inc

Example #2 pathinfo() example showing difference between null and no extension

$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);

$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>

The above example will output something similar to:

string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL

Example #3 pathinfo() example for a dot-file

The above example will output something similar to:

Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => )

Example #4 pathinfo() example with array dereferencing

The flags parameter is not a bitmask. Only a single value may be provided. To select only a limited set of parsed values, use array destructuring like so:

[ ‘basename’ => $basename , ‘dirname’ => $dirname ] = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

var_dump ( $basename , $dirname );
?>

The above example will output something similar to:

string(11) "lib.inc.php" string(15) "/www/htdocs/inc"

See Also

  • dirname() — Returns a parent directory’s path
  • basename() — Returns trailing name component of path
  • parse_url() — Parse a URL and return its components
  • realpath() — Returns canonicalized absolute pathname

Источник

How to Get a File Extension in PHP

In PHP, there exist various ways of getting a file extension. In our tutorial, we have chosen the 5 best ways that will help you to get a file extension straightforwardly.

Go ahead and choose the one that matches your project better.

Explode a File Variable

The first way is exploding a file variable and getting the last element of the array. That will be a file extension. Here is how you can do it:

 $fileName = 'banner.jpg'; $fileNameParts = explode('.', $fileName); $ext = end($fileNameParts); echo $ext; ?>

Find the Last Occurrence of ‘.’

In the framework of the second approach, we recommend detecting the last occurrence of ‘.’, which will return a ‘.jpg’ . Afterwards, you need to remove the first character of a string using substr. As a result, the exact file extension ‘.jpg’ will be returned.

 $fileName = 'banner.jpg'; $ext = substr(strrchr($fileName, '.'), 1); echo $ext; ?>

Use strrpos

The next way is to use strrpos for detecting the position of the last occurrence of ‘.’ inside a file name, incrementing that position by 1 so that it explodes a string from (.).

The example is shown below:

 $fileName = 'banner.jpg'; $ext = substr($fileName, strrpos($fileName, '.') + 1); echo $ext; ?>

Use preg_replace

In the framework of this approach, you should apply a regular expression reach and replacement.

 $fileName = 'banner.jpg'; $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName); echo $ext; ?>

Use pathinfo

And, the final approach that we recommend is to use the PHP pathinfo() function. It is aimed at returning information about the file. In case the second optional parameter is not passed, an associative array will be returned. It will include the dirname, extension, basename, and filename. Once the second parameter is passed, then specific information will be returned.

 $fileName = 'banner.jpg'; $ext = pathinfo($fileName, PATHINFO_EXTENSION); echo $ext; ?>

So, after learning about all the possible ways described above, you are free to choose the best one for you. In our opinion, the simplest, yet the most efficient way among all these options is the pathinfo() function.

Источник

Php filename file extension

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?

Источник

Читайте также:  Html status codes 200
Оцените статью