I/O – PHP Certification Exam Series [5]


PHP Input and Output - PHP Certification Exam

Introduction: This is the fifth part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.

Files

Provide a simple temporary or permanent data store. There are two major types of functions:
f* () :  Functions that work with a file resource, e.g. fopen()
file* (): Functions that work with a filename, e.g. file_get_contents()

Functions with File Resources

  • fopen($filename,$filemode,$use_include_path,$context) – open a file and return the file pointer resource on success; $filename is the full path to the file, $use_include_path is false by default; when safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed; can open thru url when allow_url_fopen is enabled in php.ini; if error is detected, an E_WARNING will be generated, context is accepted
  • fread($resource,$length); – reading stops either the $length (the bytes to be read) is reached or EOF is reached; returns the read string; ftell($resource); – return the current position; rewind($resource); – rewind the position of the file pointer; fseek($resource,$offset,$from-start-or-end); – move the file pointer to $offset bytes from the beginning or end (SEEK_SET,SEEK_CUR,SEEK_END); feof($resource); – return TRUE if end of file is reached or an error occurred, if a connection is opened by the fsockopen() function that is not closed by the server, feof() waits until a timeout reaches to return TRUE. The default timeout value of the feof() function is 60 seconds; if only need to get all the file contents to as a string, file_get_contents($filename); is more efficient
  • fwrite($resource,$data,$length) and fputs($resource,$data,$length) – write data into a resource, returns the number of bytes written; if called twice, the second fwrite will act as the resource is in the append mode; if $length is given, the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string;
  • fclose($resource)  – close the resource
  • fputcsv($resource,$array)  – writes an array in CSV format into a file
  • fscanf($resource,$format) , fprintf($resource,$format) and fsprintf($resource,$format) – sscanf(), printf() and sprintf() for resources
  • fpassthru($resource) – reads to EOF on the given file pointer from the current position and writes the results to the output buffer, returns the number of bytes on success;
  • fflush($resource) – writes all the buffered output to the open file/resource
  • fgetc($resource) – gets a character from the give file pointer, returns FALSE if EOF
  • fgetcsv($resource) – gets a line from the file pointer and parse and return an indexed array
  • fgets($resource) – gets a line from the file pointer
  • fgetss($resource) – gets a line from the file pointer and strips any PHP and HTML tags and NUL bytes
  • fnmatch($pattern,$string) – match a string against a shell pattern (preg_match for Regular Expression pattern); glob($pattern,$flag) – find pathnames matching a pattern
  • fstat($resource) – get the information on the open file
  • ftruncate($resource,$size) – truncates a file to a given length

Example:

$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "r+b");
$contents = fread($handle, filesize($filename));
fwrite($handle,"hello error");
fclose($handle);

$handle = fopen("http://www.example.com/", "rb");  // remote file
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);  // 8192 is the default maximum chunk
}
fclose($handle);

 

Functions with Filenames and Directories

  • Filenames need to be urlencode() if special characters are used.
  • file_exists($filename) – check whether a file or directory exists; E_WARNING is emitted upon failure; is_readable($filename); – tells whether a file exists and is readable; is_writable($filename);is_writeable($filename); – tells whether a file exists and is writable; is_file($filename); – tells whether a filename is a file; is_link($filename); – tells whether a filename is a symbolic link; is_dir($pathname); – tells whether a path is a directory; is_executable($pathname); – tells whether a path is a executable (for scripts, if assigned to a directory, allows the file to be accessed if the filename is know);
  • file_get_contents($filename,$use_include,$context,$offset) – read and return the file contents as a string;
  • readfile($filename) – read and output the file to the output buffer; returns the number of bytes;
  • file($filename) – read and return the file contents as an array (one line for each array value);
  • file_put_contents($filename,$data,$flag) – existing file is overwritten unless FILE_APPEND flag is added, return the number of bytes written;
  • fileatime($filename) – get the last access time in Unix timestamp; filectime($filename) – get the last change time to inode in Unix timestamp;fileinode($filename) – get the file inode in integer;  filemtime($filename) – get the last modification time in Unix timestamp; filegroup($filename) – Gets the file group, the group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name; fileowner($filename) – get the file owner id, use posix_getpwuid() to resolve to name; fileperms($filename) – get permissions for the given file, substr(sprintf(‘%o’, fileperms(‘/tmp’)), -4) to get the octal value; filesize($filename) – get the file size; filetype($filename) – get the type, possible values are fifo, char, dir, block, link, file, socket and unknown; clearstatcache() – clear the cache returned by the above functions, nothing is returned
  • touch($filename,$time) – change the access and modification time of the file, if $time will be default to present if not set
  • stat($filename) – return the file information
  • tempnam($dir,$prefix) – creates a file with a unique filename, with access permission set to 0600, in the specified directory and returns the name of the file
  • tmpfile() – creates a temporary file with a unique name in read-write (w+) mode and returns a file handle
  • basename($filename,$suffix) – return the name of the last component of the path, if $suffix is set, the same $suffix will also be truncated, e.g. base name(“/1/b/c/hello.jpg”,”.jpg“) // hello
  • pathinfo($path) – return the info of the path as an array, e.g. $path_parts = pathinfo(‘/www/htdocs/inc/lib.inc.php’); $path_parts[‘dirname’], $path_parts[‘basename’], $path_parts[‘extension’], $path_parts[‘filename’]
  • dirname($filename) – return the directory of the file
  • disk_free_space($directory) or diskfreespace($directory) – return the free space of the directory; disk_total_space($directory) – get the total disc space
  • copy($source,$destination) – copy a file to the destination
  • unlink($filename) – delete a file
  • rename($oldfilename,$newfilename) – rename or move a file
  • parse_ini_file($filename) – parse an ini file and return as an associative array
  • parse_ini_string($string) – parse an ini string and return as an associative array
  • popen($command,$mode) – opens process file pointer, e.g. $command = ‘/path/to/executable 2>&1’;
  • pclose($resource) – closes process file pointer
  • mkdir($pathname,$mode) – create directory
  • rmdir($pathname) – delete directory
  • chdir($directory) – change the directory
  • chroot($directory) – change the root directory and change the current directory to “/”
  • opendir($directory) – open directory handle
  • closedir($resource) – close the directory handle
  • readdir($resource) – return the name of the next entry in the directory (e.g. . .. filename sub-directory)
  • scandir($resource,$order) – return an array of files and directories from the directory
  • rewinddir($resource) – rewind the directory handle to the beginning
  • getcwd() – get the current working directory (from root)
  • dir($directory) – return an instance of the Directory class

Example:

if ($handle = opendir('/path/to/files')) {
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
closedir($handle);
}
if ($d = dir('/path/to/files')) { // directory object
while (false !== ($entry = $d->read())) {
echo "$entry\n";
}
$d->close();
}

 

Links

  • link($filename,$link) – create a hard link (file will still be available even the source file is deleted)
  • readlink($link) – read contents of a symbolic link
  • symlink($filename,$link) – create a symbolic link (file will NOT be available when source file is deleted)
  • lstat($filename) – get the statistics of the file; linkinfo($link) – get the information of the link; lchgrp(); lchown();
  • realpath($link) – returns the absolute real path
  • realpath_cache_get() – returns the contents of the realpath cache
  • realpath_cache_size() – returns how much memory realpath cache is using

File Permissions

  • chgrp($filename,$group) – change the group of the file
  • chmod($filename,$mode) – change the mode of the file, chmod(“filename.jpg”,0755);
  • chown($filename,$group) – change the owner of the file, only superusers are allowed to change
  • umask($mask) – change the current umask, the mask acts as a last-stage filter that strips away permissions as a file or directory

Fileinfo

  • The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file
  • enabled by default in PHP 5.3
  • finfo_open() creates a new file finfo resource
  • finfo_file($resource,$filename) a textual description of the contents of the filename argument
  • finfo_close($resource) close the finfo resource

Example:

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type extension
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);

Constants

  • __LINE__ – The current line number of the file.
  • __FILE__ The full path and filename of the file.
  • __FUNCTION__ The function name. (Added in PHP 4.3.0) (case-sensitive)
  • __CLASS__ The class name. (Added in PHP 4.3.0) (case-sensitive)
  • __METHOD__ The class method name. (Added in PHP 5.0.0) (case-sensitive)

File Modes

  • r    Open for reading only; place the file pointer at the beginning of the file.
  • r+    Open for reading and writing; place the file pointer at the beginning of the file.
  • w    Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • w+    Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • a    Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • a+    Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • x    Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.
  • x+    Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING
  • c    Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired,ftruncate() can be used after the lock is requested).
  • c+    Open the file for reading and writing; otherwise it has the same behavior as ‘c’.

Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character. For correcting the discrepancies, additional mode flags can be specified:

  • b    mode for binary files (recommended for portability)
  • t    mode: text-mode translation mode, i.e. \n to \r\n

Locks

  • bool flock ( resource $handle , int $operation [, int &$wouldblock ] )Placing and removing locks can inhibit performance as traffic increases, all locks need to be unlocked manually (fclose() will not unlock the file automatically after PHP 5.3.1)
    • LOCK_SH – place Shared (read) lock
    • LOCK_EX – place Exclusive (write) lock
    • LOCK_UN – release lock

Streams

  • Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses
  • A wrapper is additional code which tells the stream how to handle specific protocols/encodings
  • A stream is referenced as: scheme://target
  • Components include: Wrappers, Pipelines, Context and Meta Data

Protocols and Wrappers

  • file://  Accessing local filesystem
  • http://  Accessing HTTP(s) URLs
  • ftp://  Accessing FTP(s) URLs
  • php://  Accessing various I/O streams, php://stdin,stdout,stderr,input,output,fd,memory,temp,filter
  • compress.zlib://   Compression Streams
  • data://  Data (RFC 2397)
  • glob://  Find pathnames matching pattern
  • phar://  PHP Archive
  • ssh2://  Secure Shell 2
  • rar://  RAR
  • ogg://  Audio streams
  • expect://  Process Interaction Streams
  • stream_wrapper_register(protocol,classname) may be used to  wrappers not included above, the class will provide implementation of reading, writing or changing, etc.
  • file wrappers provides information on protocols and encoding, allows for two pipelines at most (reading & writing)

Pipelines / Transport

  • code wrapper communication
  • Meta Data can be determined by stream_get_meta_data()

Contexts

  • A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions
  • Pass additional information for a stream, e.g. HTTP headers for HTTP streams
  • resource stream_context_create ([ array $options [, array $params ]] )
  • bool stream_context_set_option ( resource $stream_or_context , string $wrapper , string $option , mixed $value ) orbool stream_context_set_option ( resource $stream_or_context , array $options )
  • bool stream_context_set_params ( resource $stream_or_context , array $params )
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp); fclose($fp);

Filters

  • stream filters – extensions that can be “installed” on top of the existing one to form chains of filters that act cumulatively on a data stream
  • string.rot13 — encodes the data stream using the ROT-13 algorithm
  • string.toupper — converts strings to uppercase
  • string.tolower — converts strings to lowercase
  • string.strip_tags — removes XML tags from a stream
  • convert.* — a family of filters that converts to and from the base64 encoding.
  • mcrypt.* — a family of filters that encrypts and decrypts data according to multiple algorithms
  • zlib.* — a family of filters that compressed and decompresses data using the zlib compression library
  • Can be applied to stream data using stream_filter_append($fp,’filtername’); Can create custom filters using stream_filter_register(filtername,classname); Class implements the following method: function filter($in,$out,&$consumed,$closing);

Stream Functions

  • stream_copy_to_stream()
  • stream_get_line()
  • gethostbyaddr()
  • gethostname()
  • resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags [, resource $context]]]] )
  • array stream_get_transports ( void )
  • resource stream_socket_accept ( resource $server_socket [, float $timeout [, string &$peername]] )
  • array stream_get_wrappers ( void )
  • bool stream_wrapper_register ( string $protocol, string $classname )
  • resource stream_socket_client ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout [, int $flags [, resource $context]]]]] )
  • string stream_socket_get_name ( resource $handle, bool $want_peer )
  • bool stream_filter_register ( string $filtername, string $classname )
  • resource stream_filter_prepend ( resource $stream, string $filtername [, int $read_write [, mixed $params]] )
  • resource stream_filter_append ( resource $stream, string $filtername [, int $read_write [, mixed $params]] )
  • int stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

Sockets

<?php
$fp = fsockopen("example.preinheimer.com", 80, $errno, $errstr, 30)

 

 

You can read more about my PHP Certification exam journey here.

GreyCampus PMP online training course bundle for US$149 only

Support website running for FREE, thanks!

If you find this post helpful and if you are thinking of buying from Amazon, please support the running cost of this website at no extra cost to you by searching and buying through the search box below. Thank you very much for your help!

Edward Chung

Edward Chung aspires to become a full-stack web developer and project manager. In the quest to become a more competent professional, Edward studied for and passed the PMP Certification, ITIL v3 Foundation Certification, PMI-ACP Certification and Zend PHP Certification. Edward shares his certification experience and resources here in the hope of helping others who are pursuing these certification exams to achieve exam success.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

2 Responses

  1. Duc Thang says:

    Hi Edward, I’m learning PHP from your blog.
    You wrote: “rewind($resource); – return the position of the file pointer;”. It makes me confused, because rewind($resource) returns boolean http://php.net/manual/en/function.rewind.php, not position of the file pointer. But it has ‘;’ between “rewind($resource)” and ” – return the position of the file pointer;”. Do you missing something in that? or Am I wrong :D?