Showing posts with label Advanced PHP Function Reference. Show all posts
Showing posts with label Advanced PHP Function Reference. Show all posts

Wednesday, 28 August 2013

PHP Filesystem Functions

The filesystem functions are used to access and manipulate the filesystem PHP provides you all the posible functions you may need to manipulate a file.

Installation:

The error and logging functions are part of the PHP core. There is no installation needed to use these functions.

Runtime Configuration:

The behaviour of these functions is affected by settings in php.ini.
NameDefaultChangeableChangelog
allow_url_fopen"1"PHP_INI_ALLPHP_INI_ALL in PHP <= 4.3.4. PHP_INI_SYSTEM in PHP < 6. Available since PHP 4.0.4.
allow_url_include"0"PHP_INI_ALLPHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0.
user_agentNULLPHP_INI_ALLAvailable since PHP 4.0.3.
default_socket_timeout"60"PHP_INI_ALLAvailable since PHP 4.3.0.
from""PHP_INI_ALL
auto_detect_line_endings"0"PHP_INI_ALLAvailable since PHP 4.3.0.

PHP Error and Logging Constants:

PHP: indicates the earliest version of PHP that supports the constant.
You can use any of the constant while configuring your php.ini file.
ConstantDescriptionPHP
GLOB_BRACE
GLOB_ONLYDIR
GLOB_MARK
GLOB_NOSORT
GLOB_NOCHECK
GLOB_NOESCAPE
PATHINFO_DIRNAME
PATHINFO_BASENAME
PATHINFO_EXTENSION
PATHINFO_FILENAME5.2.0
FILE_USE_INCLUDE_PATHSearch for filename in include_path5.0.0
FILE_APPENDAppend content to existing file.
FILE_IGNORE_NEW_LINESStrip EOL characters5.0.0
FILE_SKIP_EMPTY_LINESSkip empty lines5.0.0
FILE_BINARYBinary mode6.0.0
FILE_TEXTText mode6.0.0

List of Functions

PHP: indicates the earliest version of PHP that supports the function.
FunctionDescriptionPHP
basename()Returns filename component of path3
chgrp()Changes file group3
chmod()Changes file mode3
chown()Changes file owner3
clearstatcache()Clears file status cache3
copy()Copies file3
delete()Deletes file
dirname()Returns directory name component of path3
disk_free_space()Returns available space in directory4.0.7
disk_total_space()Returns the total size of a directory4.0.7
diskfreespace()Alias of disk_free_space()4.0.7
fclose()Closes an open file pointer3
feof()Tests for end-of-file on a file pointer3
fflush()Flushes the output to a file4
fgetc()Gets character from file pointer3
fgetcsv()Gets line from file pointer and parse for CSV fields3
fgets()Gets line from file pointer3
fgetss()Gets line from file pointer and strip HTML tags3
file_exists()Checks whether a file or directory exists3
file_get_contents()Reads entire file into a string4.3.0
file_put_contents()Write a string to a file5
file()Reads entire file into an array3
fileatime()Gets last access time of file3
filectime()Gets inode change time of file3
filegroup()Gets file group3
fileinode()Gets file inode3
filemtime()Gets file modification time3
fileowner()Gets file owner3
fileperms()Gets file permissions3
filesize()Gets file size3
filetype()Gets file type3
flock()Portable advisory file locking3
fnmatch()Match filename against a pattern4.0.3
fopen()Opens file or URL3
fpassthru()Output all remaining data on a file pointer3
fputcsv()Format line as CSV and write to file pointer5.1.0
fputs()Alias of fwrite()3
fread()Binary-safe file read3
fscanf()Parses input from a file according to a format4.0.1
fseek()Seeks on a file pointer3
fstat()Gets information about a file using an open file pointer4
ftell()Tells file pointer read/write position3
ftruncate()Truncates a file to a given length4
fwrite()Binary-safe file write3
glob()Find pathnames matching a pattern4.0.3
is_dir()Tells whether the filename is a directory3
is_executable()Tells whether the filename is executable3
is_file()Tells whether the filename is a regular file3
is_link()Tells whether the filename is a symbolic link3
is_readable()Tells whether the filename is readable3
is_uploaded_file()Tells whether the file was uploaded via HTTP POST4.0.3
is_writable()Tells whether the filename is writable3
is_writeable()Alias of is_writable()3
lchgrp()Changes group ownership of symlink5.1.2
lchown()Changes user ownership of symlink5.1.2
link()Create a hard link3
linkinfo()Gets information about a link3
lstat()Gives information about a file or symbolic link3
mkdir()Makes directory3
move_uploaded_file()Moves an uploaded file to a new location4.0.3
parse_ini_file()Parse a configuration file4
pathinfo()Returns information about a file path4.0.3
pclose()Closes process file pointer3
popen()Opens process file pointer3
readfile()Outputs a file3
readlink()Returns the target of a symbolic link3
realpath()Returns canonicalized absolute pathname4
rename()Renames a file or directory3
rewind()Rewind the position of a file pointer3
rmdir()Removes directory3
set_file_buffer()Alias of stream_set_write_buffer()3
stat()Gives information about a file3
symlink()Creates a symbolic link3
tempnam()Create file with unique file name3
tmpfile()Creates a temporary file3
touch()Sets access and modification time of file3
umask()Changes the current umask3
unlink()Deletes a file3

PHP Function filegroup()

Syntax

int filegroup ( string $filename );

Definition and Usage

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Paramters

ParameterDescription
filenamePath to the file.

Return Value

Returns the group ID of the file, or FALSE in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.
Upon failure, an E_WARNING is emitted.

Example

Following is the usage of this function:
<?php
$filename = "/home/httpd/html/index.php";
$group = filegroup($filename);
echo "File group is $group\n";
?>
This will produce following result:
File group is guest

PHP Function filectime()

Syntax

int filectime ( string $filename )

Definition and Usage

Gets the inode change time of a file.

Paramters

ParameterDescription
filenamePath to the file.

Return Value

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Example

Following is the usage of this function:
<?php
$filename = "/home/httpd/html/index.php";
if (file_exists($filename)) {
    echo "$filename was last changed: " . 
               date("F d Y H:i:s.", filectime($filename));
}
?>

PHP Function fileatime()

Syntax

int fileatime ( string $filename );

Definition and Usage

Gets the last access time of the given file.

Paramters

ParameterDescription
filenamePath to the file.

Return Value

Returns the time the file was last accessed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Example

Following is the usage of this function:
<?php
$filename = "/home/httpd/html/index.php";
if (file_exists($filename)) {
    echo "$filename was last accessed: " . 
          date("F d Y H:i:s.", fileatime($filename));
}
?>

PHP Function file()

Syntax

array file ( string $filename [, int $flags [, resource $context]] );

Definition and Usage

Reads an entire file into an array.

Paramters

ParameterDescription
filenamePath to the file.
flagsThe optional parameter flags can be one, or more, of the following constants:
  • FILE_USE_INCLUDE_PATH: Search for the file in the include_path.
  • FILE_IGNORE_NEW_LINES: Do not add newline at the end of each array element
  • FILE_SKIP_EMPTY_LINES: Skip empty lines
  • FILE_TEXT; The content is returned in UTF-8 encoding. You can specify a different encoding by creating a custom context. This flag cannot be used with FILE_BINARY. This flag is only available since PHP 6.
  • FILE_BINARY: The content is read as binary data. This is the default setting and cannot be used with FILE_TEXT. This flag is only available since PHP 6.
contextA context resource created with the stream_context_create() function.

Return Value

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Example

Following is the usage of this function:
<?php
// Get a file into an array.
$lines = file('http://www.tutorialspoint.com/');

// Loop through our array,
foreach ($lines as $line_num => $line) {
  echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line)
  echo "<br />\n";
}
?>

PHP Function file_put_contents()

Syntax

int file_put_contents ( string $filename, mixed $data [, int $flags [, resource $context]] );

Definition and Usage

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flags is set.

Paramters

ParameterDescription
filenamePath to the file where to write the data.
dataThe data to write. Can be either a string, an array or a stream resource
flagsThe value of flags can be any combination of the following flags (with some restrictions), joined with the binary OR (|) operator.
  • FILE_USE_INCLUDE_PATH: Search for filename in the include directory.
  • FILE_APPEND: If file filename already exists, append the data to the file instead of overwriting it.
  • LOCK_EX: Acquire an exclusive lock on the file while proceeding to the writing.
  • FILE_TEXT: data is written in text mode. This flag cannot be used with FILE_BINARY. This flag is only available since PHP 6.
  • FILE_BINARY: data will be written in binary mode. This is the default setting and cannot be used with FILE_TEXT. This flag is only available since PHP 6.
contextA valid context resource created with stream_context_create().

Return Value

The function returns the amount of bytes that were written to the file, or FALSE on failure.

Example

Following is the usage of this function:
<?php
// Copy input file into output file.

$inputFile = "/home/httpd/inputFile.txt";
$outputFile = "/home/httpd/outputFile.txt";
$fi = fopen($inputFile, 'r');
$source = '';
while (!feof($fi)) {
   $source .= fgets($fi);
}
fclose($fi);
file_put_contents($outputFile,$source);
?>

PHP Function file_get_contents()

Syntax

string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen]]]] );

Definition and Usage

This function is identical to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes.

Paramters

ParameterDescription
filenameName of the file to read.
flagsThe value of flags can be any combination of the following flags joined with the binary OR (|) operator.
  • FILE_USE_INCLUDE_PATH: Search for filename in the include directory.
  • FILE_TEXT: If unicode semantics are enabled, the default encoding of the read data is UTF-8. his flag cannot be used with FILE_BINARY.
  • FILE_BINARY: With this flag, the file is read in binary mode. This is the default setting and cannot be used with FILE_TEXT.
contextA valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.
offsetThe offset where the reading starts.
maxlenMaximum length of data read.

Return Value

The function returns the read data or FALSE on failure.

Example

Following is the usage of this function:
<?php
$lines = file_get_contents('http://www.example.com/');

# This will read complete index.htm file.
echo $lines;
?>

PHP Function file_exists()

Syntax

bool file_exists ( string $filename );

Definition and Usage

Checks whether a file or directory exists.

Paramters

ParameterDescription
filenamePath to the file or directory.

Return Value

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Example

Following is the usage of this function:
<?php
$filename = '/home/httpd/index.htm';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

PHP Function fgetss()

Syntax

string fgetss ( resource $handle [, int $length [, string $allowable_tags]] );

Definition and Usage

Identical to fgets(), except that fgetss() attempts to strip any HTML and PHP tags from the text it reads.

Paramters

ParameterDescription
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
lengthLength of the data to be retrieved.
allowable_tagsYou can use the optional third parameter to specify tags which should not be stripped.

Return Value

Returns a string of up to length - 1 bytes read from the file pointed to by handle, with all HTML and PHP code striped. If an error occurs, returns FALSE.

Example

Following is the usage of this function:
<?php
$handle = @fopen("/tmp/inputfile.htm", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

PHP Function fgets()

Syntax

string fgets ( resource $handle [, int $length] );

Definition and Usage

Gets a line from file pointer.

Paramters

ParameterDescription
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
lengthReading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Return Value

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If an error occurs, returns FALSE.

Example

Following is the usage of this function:
<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 1024);
        echo $buffer;
    }
    fclose($handle);
}
?>

PHP Function fgetcsv()

Syntax

array fgetcsv ( resource $handle [, int $length [, string $delimiter [, string $enclosure [, string $escape]]]] );

Definition and Usage

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Paramters

ParameterDescription
handleA valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
lengthMust be greater than the longest line.
delimiterSet the field delimiter (one character only). Defaults as a comma.
enclosureSet the field enclosure character (one character only). Defaults as a double quotation mark.
escapeSet the escape character (one character only). Defaults as a backslash (\)

Return Value

Returns an indexed array containing the fields read.

Example

Following is the usage of this function:
<?php
row = 1;
$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
}
fclose($handle);
?>