5 Useful PHP Function for Working with Files

PHP is definitely one of the most popular programming language for web developers. And this article is about 5 useful function that every PHP developer must know when working with files and directories.

1. file_put_contentsWrite a string to a file

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.  It mean if you use this function you don’t need to use three other functions like: fopen(),fwrite() and fclose().

Usage : 

This function takes two arguments. The first one is for file name if doesn’t exist it will create one. The second argument is for data to be written in that file.

Example

<?php file_put_contents("Technig.txt", "Hello world"); ?>

 

You can pass an array as second argument

<?php
 $data = array("Ali","Hamid", "Mahmod");
 file_put_contents("Technig.txt", $data);
 ?>

 2. file_get_contents() reads a file into a string.

file_get_contents() function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, it will return FALSE.

Usage:

This function takes five arguments.

file_get_contents(path,include_path,context,start,max_length)

First argument is required: specifies the file path to read.

Second argument is optional: Set this parameter to ‘1’ if you want to search for the file in the include_path (in php.ini) as well.

Third argument is optional: Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.

Fourth argument is optional:  Specifies where in the file to start reading. This parameter was added in PHP 5.1

And Last Argument is also optional: Specifies how many bytes to read. This parameter was also added  in PHP 5.1

Tip: This function is binary-safe (meaning that both binary data, like images, and character data can be written with this function).

Example:

<?php 
file_get_contents("Technig.txt");
 ?>

 

3.  glob() Function

The glob() function returns an array of filenames or directories matching a specified pattern.

 

Usage:

This function takes two arguments:

The first argument is pattern and it is required, specifies the pattern to search for.

The second argument is optional for some special settings.

Possible values:

  • GLOB_MARK – Adds a slash to each item returned
  • GLOB_NOSORT – Return files as they appear in the directory (unsorted)
  • GLOB_NOCHECK – Returns the search pattern if no match were found
  • GLOB_NOESCAPE – Backslashes do not quote metacharacters
  • GLOB_BRACE – Expands {a,b,c} to match ‘a’, ‘b’, or ‘c’
  • GLOB_ONLYDIR – Return only directories which match the pattern
  • GLOB_ERR – (added in PHP 5.1) Stop on errors (errors are ignored by default)

Example :

if you want to show all files with “.txt” extension in one directory.

<?php
print_r(glob("*.txt"));
?>

The start (*) means whatever the name is but it must have “.txt” extension.

It will output an array with all file which has “.txt” extension.

Array
(
[0] => Technig.txt
[1] => source.txt
[2] => file.txt
[3] => password.txt
)

If you want to show all files with any extension you can do.  Simply use “*” as filename and extension.

<?php
print_r(glob("*.*"));
?>

Output:

Array
(
[0] => contacts.csv
[1] => default.php
[2] => Technig.txt
[3] => Data.txt
[4] => tem1.tmp
[5] => test.htm
[6] => test.ini
[7] => test.php
[8] => test.txt
)

4. basename() Function

The basename() function returns the filename from a path.

Usage:

basename ($path, $suffix);

 

This function takes two arguments. The first one is required and specifies the path to check.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

The second argument is optional. Specifies a file extension. If the filename has this file extension, the file extension will not show.

Example: 

<?php
echo "
 0) ".basename("/Technig/test.d"); // file with extension 
echo "
 1) ".basename("/Technig/test.d", ".d"); // file without extension
echo "
 2) ".basename("/Technig/passwd"); 
echo "
 3) ".basename("/Technig/");
echo "
 4) ".basename(".");
echo "
 5) ".basename("/");
?>

Output

0) test.d
1) test
2) passwd
3) Technig
4) .
5)

 

5. pathinfo() Function

The pathinfo() function returns an array that contains information about a path.

The following array elements are returned:

  • [dirname]
  • [basename]
  • [extension]

Usage : 

This function also takes two arguments. The first argument is the path. It’s required. Specifies the path to check.

The second argument is the options. it’s optional. Specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

Note:

If options is not specified, returns all available elements.

pathinfo ($path,$options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] );

Example 1:

<?php
$path_parts = pathinfo('/www/Technig/test.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

Output: returned an array.

/www/Teching
test.inc.php
php
test.inc

Example 2 :

You can print_r it directly with second argument.

<?php
print_r(pathinfo("/Technig/test.txt",PATHINFO_BASENAME));
?>

It will output only basename.

test.txt

Although there are a lots of PHP function to talk about,  I wrap up this article here, and I hope it has been informative for you. If you want to learn more about file system in php you can refer to this article on w3schools : PHP 5 Filesystem Functions.

PHPPHP FunctionProgrammingweb developement
Comments (0)
Add Comment