Zend PHP5 Certification Exam study review 2: Streams And Network

This post is a final review on Zend PHP5 Certification Exam of php’s Streams and Networks feature. Since for php, any file operations are also considered as stream manipulation, this post includes the well-known php file manipulation functions as well as some points on file system aspect. Streams functionality on networks, such as sockets also mentioned. Streams seem very important in the Exam, so you maybe watch out this topic carefully.Magic constants
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

Two types of streams:
One group provides access to a certain type of stream resource; the standard PHP distribution includes several built in examples:
• php.*—standard PHP input/output
• file—standard file access
• http—access to remote resources via HTTP
• ftp—access to remote resources via FTP
• compress.zlib—access to compressed data stream using the zlib compression library.

Another group are several stream extensions that can be “installed” on top of the existing one to form chains of filters that act cumulatively on a data stream: Stream Filters
• 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

The second argument to fopen(); this determines two things: first, whether we are reading, writing or doing both things to the file at the same time. Secondly, if the file pointer—the position at which the next byte will be read or written—is set at the beginning or at the end of the file.

r: Opens the file for reading only and places the file pointer at the beginning of the file
r+: Opens the file for reading and writing; places the file pointer at the beginning of the file
w: Opens the file for writing only; places the file pointer at the beginning of the file and truncate it to zero length
w+: Opens the file for writing and reading; places the file pointer at the beginning of the file and truncate it to zero length
a: Opens the file for writing only; places the file pointer at the end of the file
a+: Opens the file for reading and writing; places the file pointer at the end of the file
x: Creates a new file for writing only
x+: Creates a new file for reading and writing

Each of these modes can be coupled with a modifier that indicates how the data is to be read and written: the b flag (e.g.: w+b) forces “binary” mode, which will make sure that all data is written to the file unaltered. There is also a Windows only flag, t, which will transparently translate UNIX newlines (\n) to Windows newlines (\r\n). In addition, the w, w+, a, and a+ modes will automatically create a new file if it doesn’t yet exist; in contrast, x and x+ will throw an E_WARNING if the file already exists.

resource fopen ( string $filename, string $mode [, bool $use_include_path [, resource $context]] )
Opens file or URL

string fread ( resource $handle, int $length )
Binary-safe file read
reads up to length bytes from the file pointer referenced by handle. Reading stops when up to length bytes have been read, EOF (end of file) is reached, (for network streams) when a packet becomes available, or (after opening user space stream) when 8192 bytes have been read whichever comes first.

string fgets ( resource $handle [, int $length] )
Gets a line from file pointer.
Reading 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.

int
fwrite ( resource $handle, string $string [, int $length] )
Binary-safe file write returns the number of bytes written, or FALSE on error.
Writes the contents of string to the file stream pointed to by handle. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

array fstat ( resource $handle )
Stat() does it without the file being open
array stat ( string $filename ) If filename is a symbolic link, statistics are from the file itself, not the symlink.
array lstat ( string $filename )

bool file_exists ( string $filename )
Checks whether a file or directory exists.

Files can be locked to prevent race conditions
bool flock ( resource $handle, int $operation [, int &$wouldblock] )
Placing and removing locks can inhibit performance as traffic increases, consider using a different data store

int fseek ( resource $handle, int $offset [, int $whence] )
Offset: When your starting position is SEEK_END, this number should always be zero or less, while, when you use SEEK_SET, it should always be zero or more. When you specify SEEK_CURRENT as a starting point, the value can be either positive (move forward) or negative (move backwards)—in this case, a value of zero, while perfectly legal, makes no sense.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

int ftell ( resource $handle )
ftell() gives undefined results for append-only streams (opened with “a” flag).

bool feof ( resource $handle )
Tests for end-of-file on a file pointer.

bool ftruncate ( resource $handle, int $size )
Truncates a file to a given length
The file pointer is changed only in append mode. In write mode, additional fseek() call is needed.

array fgetcsv ( resource $handle [, int $length [, string $delimiter [, string $enclosure]]] )
Gets line from file pointer and parse for CSV fields.
Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

int fputcsv ( resource $handle, array $fields [, string $delimiter [, string $enclosure]] )
Format line as CSV and write to file pointer.
If you don’t specify a delimiter and an enclosure character, both fgetcsv() and fputcsv() use a comma and quotation marks respectively.

int readfile ( string $filename [, bool $use_include_path [, resource $context]] )
Outputs a file.
Reads a file and writes it to the output buffer. Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.
int fpassthru ( resource $handle )
Output all remaining data on a file pointer
Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.
You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.
If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.

array file ( string $filename [, int $flags [, resource $context]] )
Reads an entire file into an array. Used with:
string implode ( string $glue, array $pieces )

PHP5 presents two functions which make handling files trivial, namely file_get_contents() and file_put_contents()
file_get_contents() was backported to PHP4 because it was so useful.

string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen]]]] )
Limit the amount of data read by file_get_contents() by specifying an appropriate set of parameters to the function.

int file_put_contents ( string $filename, mixed $data [, int $flags [, resource $context]] )
Specify a number flags to alter its behaviour:
• FILE_USE_INCLUDE_PATH — Causes the function to use the include_path to find
the file
• FILE_APPEND—Appends the data to the file, rather than overwriting
• LOCK_EX—Acquire an exclusive lock before accessing the file. (PHP > 5.1.0)
Pass an array to file_put_contents() instead of a string. The function will automatically apply the equivalent of implode(“”, $data) on the $data array and write the resulting string to the file. In addition, it is possible to pass file_put_contents() a stream resource instead of a string or an array; in this case, the unread remainder of the stream will be placed in the file.

string basename ( string $path [, string $suffix] )
Returns filename component of path.
Given a string containing a path to a file, this function will return the base name of the file.
If the optional suffix parameter is supplied, that suffix will be omitted if the returned file name contains that extension.

string realpath ( string $path )
Returns canonicalized absolute pathname.
realpath() expands all symbolic links and resolves references to ‘/./’, ‘/../’ and extra ‘/’ characters in the input path. and return the canonicalized absolute pathname.

bool chdir ( string $directory )
Changes PHP’s current directory to directory.

string getcwd ( void )
Gets the current working directory.
On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does.

bool unlink ( string $filename [, resource $context] )
Deletes filename. Similar to the Unix C unlink() function.

bool rename ( string $oldname, string $newname [, resource $context] )
Attempts to rename oldname to newname.

bool rmdir ( string $dirname [, resource $context] )
Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this.

bool mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context]]] )
Attempts to create the directory specified by pathname.
Note that, normally. only the last directory in the path will be created, and mkdir() will fail if any other component of the path does not correspond to an existing directory. The third parameter to the function, however, allows you to override this behaviour and actually create anymissing directories along the line. The second parameter allows you to specify the access mode for the file—an integer parameter that most people prefer to specify in the UNIX-style octal notation. Note that this parameter is ignored under Windows, where access control mechanisms are different.

Controlling File Access:
The information obtained via these functions is available in other ways (like using stat) but these wrappers make it easy.
bool is_dir ( string $filename )
Tells whether the given filename is a directory.

bool is_executable ( string $filename )
Tells whether the filename is executable.

bool is_file ( string $filename )
Tells whether the given file is a regular file.

bool is_link ( string $filename )
Tells whether the given file is a symbolic link.

bool is_readable ( string $filename )
Tells whether the filename is readable.

bool is_writable ( string $filename )
Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writeable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often ‘nobody’). Safe mode limitations are not taken into account.

bool is_uploaded_file ( string $filename )
Tells whether the file was uploaded via HTTP POST.
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working–for instance, /etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
For proper working, the function is_uploaded_file() needs an argument like $_FILES[‘userfile’][‘tmp_name’], – the name of the uploaded file on the clients machine $_FILES[‘userfile’][‘name’] does not work.

Note that the results of a call to any of these functions will be cached, so that two calls to a given function on the same stream resource and during the same script will return the same value, regardless of whether the underlying resource has changed in the meantime. Given the relatively short lifespan of a script, this is not generally a problem—but it is something to keep in mind when dealing with long-running scripts, or with scripts whose purpose is precisely that of waiting for a resource to change.
The internal cache maintained within PHP for these functions can be cleared by calling clearstatcache().

bool move_uploaded_file ( string $filename, string $destination )
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
Note: move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

bool link ( string $target, string $link )
Create a hard link.

bool symlink ( string $target, string $link )
symlink() creates a symbolic link to the existing target with the specified name link.

string readlink ( string $path )
Returns the target of a symbolic link.

float disk_free_space ( string $directory )
Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

string readdir ( resource $dir_handle )
Read entry from directory handle.
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

array scandir ( string $directory [, int $sorting_order [, resource $context]] )
Returns an array of files and directories from the directory.

int filectime (string filename) / int filemtime (string filename)
The “last changed time” differs from the “last modified time” in that the last changed time refers to any change in the file’s inode data, including changes to permissions, owner, group, or other inode-specific information, whereas the last modified time refers to changes to the file’s content (specifically, byte size).

int fileperms (string filename) and string base_convert ( string $number, int $frombase, int $tobase )
The fileperms() function returns filename’s permissions in decimal format, or FALSE in case of error. Because the decimal permissions representation is almost certainly not the desired format, you’ll need to convert fileperms()’s return value. This is easily accomplished using the base_convert() function in conjunction with substr(). The base_convert() function converts a value from one number base to another; therefore, you can use it to convert fileperms()’s returned decimal value from base 10 to the desired base 8. The substr() function is then used to retrieve only the final three digits of base_convert()’s returned value, which are the only digits referred to when discussing Unix file permissions.

Stream
Each stream consists of several components:
– file wrapper
– one or two pipe-lines
– an optional context
– metadata about the stream

Stream Meta Data
array stream_get_meta_data ( resource $stream )

resource stream_context_create ( [array $options [, array $params]] )

Using stream context and a few other techniques a lot can be done without resorting to sockets, however for more detailed control sockets can be used.
Sockets allow read/write access to various socket connections, while things like HTTP may seem read only, at the protocol level information is being sent to identify the desired resource.

resource fsockopen ( string $hostname [, int $port [, int &$errno [, string &$errstr [, float $timeout]]]] )
Open Internet or Unix domain socket connection.

resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags [, resource $context]]]] )

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

array stream_get_transports ( void )
Returns an indexed array containing the name of all socket transports available on the running system.

resource stream_socket_accept ( resource $server_socket [, float $timeout [, string &$peername]] )
Accept a connection on a socket previously created by stream_socket_server(). If timeout is specified, the default socket accept timeout will be overridden with the time specified in seconds. The name (address) of the client which connected will be passed back in peername if included and available from the selected transport.

peername can also be determined later using stream_socket_get_name().

array stream_get_wrappers ( void )
Retrieve list of registered streams
Returns an indexed array containing the name of all stream wrappers available on the running system.

bool stream_wrapper_register ( string $protocol, string $classname )
Register a URL wrapper implemented as a PHP class
make reference to http://cn.php.net/manual/en/function.stream-wrapper-register.php

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 )
Retrieve the name of the local or remote sockets
Returns the local or remote name of a given socket connection. If want_peer is set to TRUE the remote socket name will be returned, if it is set to FALSE the local socket name will be returned.

bool stream_filter_register ( string $filtername, string $classname )
Register a stream filter implemented as a PHP class derived from php_user_filter
make reference to http://php.net/manual/en/function.stream-filter-register.php

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]] )

10 Comments - Leave a comment
  1. Heena says:

    hi,
    there is another quetion

    which of the following are not true about streams?
    1> they are always seekable
    2> when used properly they significantly reduce memory consumption
    3> they can be applied to any data source
    4> they are alwyas bi-directional
    4> they can be filtered

    please help me if u know

    thanks

  2. David Adam says:

    Hi,
    The answer is 1>. And you can use stream_get_meta_data() to find out if it seekable or not.

  3. Heena says:

    using flock() to lock a stream is only assured to work under what circumstances?
    1> when running in a linux environment local filesystem
    2> when accessing the stream of the local filesystem
    3> when running in a windows environment and accessing a share
    4> when accessing a bi-directional stream
    5> when accessing a read-only stream

  4. David Adam says:

    Hi, The right answer is: 1> when running in a linux environment local filesystem I think. You can refer the php.net on the warning section on flock() function.

  5. kavita says:

    If you know please post answer to following question:

    How can one take advantage of the time waiting for a lock during a stream access, to do other tasks using the following locking code as the base:

    $retval = flock($fr, LOCK_EX);

    Answer Choices
    1. Use flock_lazy() instead of flock()
    2. Use LOCK_EX|LOCK_NB instead of LOCK_EX
    3. Use LOCK_UN instead of LOCK_EX
    4. Check the value of $retval to see if the lock was obtained
    5. Check to see if $retval == LOCK_WAIT

  6. David Adam says:

    1: flock_lazy() does not exist.
    2. unlogical.
    3.Please read the question again!
    4. seems good.
    5.LOCK_WAIT does not exist.

    Therefore, the answer is 4. I think.

  7. Jagat says:

    Hi,

    Thanks A Lot For The Tutorial.

  8. Naveen says:

    The answer to “How can one take advantage of the time waiting for a lock during a stream access, to do other tasks using the following locking code as the base” is
    Use LOCK_EX|LOCK_NB instead of LOCK_EX
    Got it from here

  9. Amit Verma says:

    For those who just want to check if a file is available for locking and return immediately (without blocking), use the following syntax:

    This is a quick, easy way to determine if another process is using the file or not, without blocking your script.

  10. Refrigerator says:

    >which of the following are not true about streams?

    In this question in mock test need to choose 2 answers, so the second answer is “they are always bi-directional”

Leave a Reply

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

*