[Zend PHP5 Cerification] Lectures -- 3. Streams And Network

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

Another group are several streamextensions that can be “installed” on top of the existing one toform chains of filters that act cumulatively on a data stream: StreamFilters
• string.rot13—encodes the data stream using theROT-13 algorithm
• string.toupper—converts strings touppercase
• string.tolower—converts strings to lowercase
•string.strip_tags—removes XML tags from a stream
• convert.*—afamily of filters that converts to and from the base64 encoding.
•mcrypt.*—a family of filters that encrypts and decrypts dataaccording to multiple algorithms
• zlib.*—a family of filtersthat compressed and decompresses data using the zlib compressionlibrary

 

Somefile system related functions:

fopen()

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

r: Opens the file for reading only andplaces the file pointer at the beginning of the file
r+: Opens thefile for reading and writing; places the file pointer at thebeginning of the file
w: Opens the file for writing only; placesthe file pointer at the beginning of the file and truncate it to zerolength
w+: Opens the file for writing and reading; places the filepointer at the beginning of the file and truncate it to zerolength
a: Opens the file for writing only; places the file pointerat 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 newfile for writing only
x+: Creates a new file for reading andwriting

Each of these modes can be coupled with a modifierthat 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 alldata is written to the file unaltered. There is also a Windows onlyflag, t, which will transparently translate UNIX newlines (\n) toWindows newlines (\r\n). In addition, the w, w+, a, and a+ modes willautomatically create a new file if it doesn’t yet exist; incontrast, x and x+ will throw an E_WARNING if the file alreadyexists.

 

 

 

resourcefopen ( string $filename, string $mode [, bool $use_include_path [,resource $context]] )
Opens fileor URL

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

stringfgets ( resource $handle [, int $length] )
Getsa line from file pointer.
Reading ends when length - 1 bytes havebeen read, on a newline (which is included in the return value), oron EOF (whichever comes first). If no length is specified, it willkeep reading from the stream until it reaches the end of theline.

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

arrayfstat ( resource $handle )
Stat()does it without the file being open
arraystat ( string $filename )   
Iffilenameis a symbolic link, statistics are from the file itself, not thesymlink.
array lstat ( string$filename )

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


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


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

intftell ( resource $handle )
ftell()gives undefined results for append-only streams (opened with "a"flag).

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

boolftruncate ( resource $handle, int $size )
Truncatesa file to a given length
The file pointer is changed only in
appendmode. In writemode, additional fseek() call is needed.

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

intfputcsv ( resource $handle, array $fields [, string $delimiter [,string $enclosure]] )
Format lineas CSV and write to file pointer.
Ifyou don’t specify a delimiter and an enclosure character, bothfgetcsv() and fputcsv() use a comma and quotation marksrespectively.

intreadfile ( string $filename [, bool $use_include_path [, resource$context]] )
Outputs afile.
Reads a file and writes it to the output buffer. Returns thenumber of bytes read from the file. If an error occurs,
FALSEis returned and unless the function was called as @readfile(),an error message is printed.
intfpassthru ( resource $handle )
Outputall remaining data on a file pointer
Reads to EOF on the givenfile pointer from the current position and writes the results to theoutput buffer.
You may need to call rewind() to reset the filepointer to the beginning of the file if you have already written datato the file.
If you just want to dump the contents of a file tothe output buffer, without first modifying it or seeking to aparticular offset, you may want to use the readfile(), which savesyou the fopen() call.

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

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

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

intfile_put_contents ( string $filename, mixed $data [, int $flags [,resource $context]] )
Specify anumber flags to alter its behaviour:
 •FILE_USE_INCLUDE_PATH — Causes the function to use the include_pathto find
the file
• FILE_APPEND—Appends the data to thefile, rather than overwriting
• LOCK_EX—Acquire an exclusivelock before accessing the file. (PHP > 5.1.0)
Pass an array tofile_put_contents() instead of a string. The function willautomatically 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 insteadof a string or an array; in this case, the unread remainder of thestream will be placed in the file.

stringbasename ( string $path [, string $suffix] )
Returnsfilename component of path.
Given a string containing a path to afile, this function will return the base name of the file.
If theoptional suffix parameter is supplied, that suffix will be omitted ifthe returned file name contains that extension.

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

boolchdir ( string $directory )
ChangesPHP's current directory to
directory.

stringgetcwd ( void )
Gets the currentworking directory.
On some Unix variants,
getcwd()will return FALSEif any one of the parent directories does not have the readable orsearch mode set, even if the current directory does.

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

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

boolrmdir ( string $dirname [, resource $context] )
Attemptsto remove the directory named by
dirname.The directory must be empty, and the relevant permissions must permitthis.

bool mkdir ( string$pathname [, int $mode [, bool $recursive [, resource $context]]])
Attempts to create thedirectory specified by pathname.
Note that, normally. only thelast directory in the path will be created, and mkdir() will fail ifany other component of the path does not correspond to an existingdirectory. The third parameter to the function, however, allows youto override this behaviour and actually create anymissing directoriesalong the line. The second parameter allows you to specify the accessmode for the file—an integer parameter that most people prefer tospecify in the UNIX-style octal notation. Note that this parameter isignored under Windows, where access control mechanisms aredifferent.

Controlling File Access:
Theinformation obtained via these functions is available in other ways(like using stat) but these wrappers make it easy.
boolis_dir ( string $filename )
Tellswhether the given filename is a directory.

boolis_executable ( string $filename )
Tellswhether the filename is executable.

boolis_file ( string $filename )
Tellswhether the given file is a regular file.

boolis_link ( string $filename )
Tellswhether the given file is a symbolic link.

boolis_readable ( string $filename )
Tellswhether the filename is readable.

boolis_writable ( string $filename )
ReturnsTRUE if the filename exists and is writable. The filename argumentmay be a directory name allowing you to check if a directory iswriteable.
Keep in mind that PHP may be accessing the file as theuser id that the web server runs as (often 'nobody'). Safe modelimitations are not taken into account.

boolis_uploaded_file ( string $filename )
Tellswhether the file was uploaded via HTTP POST.
Returns TRUE if thefile named by filename was uploaded via HTTP POST. This is useful tohelp ensure that a malicious user hasn't tried to trick the scriptinto working on files upon which it should not be working--forinstance, /etc/passwd.
This sort of check is especially importantif there is any chance that anything done with uploaded files couldreveal their contents to the user, or even to other users on the samesystem.
For proper working, the function is_uploaded_file() needsan argument like $_FILES['userfile']['tmp_name'], - the name of theuploaded file on the clients machine $_FILES['userfile']['name'] doesnot work.

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

boolmove_uploaded_file ( string $filename, string $destination )
Thisfunction checks to ensure that the file designated by filename is avalid upload file (meaning that it was uploaded via PHP's HTTP POSTupload mechanism). If the file is valid, it will be moved to thefilename given by destination.
If filename is not a valid uploadfile, then no action will occur, and move_uploaded_file() will returnFALSE.
If filename is a valid upload file, but cannot be moved forsome reason, no action will occur, and move_uploaded_file() willreturn 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 toallow the moving of uploaded files in which filename may conflictwith such restrictions. move_uploaded_file() ensures the safety ofthis operation by allowing only those files uploaded through PHP tobe moved.

boollink ( string $target, string $link )
Createa hard link.

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

stringreadlink ( string $path )
Returnsthe target of a symbolic link.

floatdisk_free_space ( string $directory )
Givena string containing a directory, this function will return the numberof bytes available on the corresponding filesystem or diskpartition.

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

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

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

intfileperms (string filename)  andstring base_convert ( string $number,int $frombase, int $tobase )
Thefileperms() function returns filename’s permissions in decimalformat, or FALSE in case of error. Because the decimal permissionsrepresentation is almost certainly not the desired format, you’llneed to convert fileperms()’s return value. This is easilyaccomplished using the base_convert() function in conjunction withsubstr(). The base_convert() function converts a value from onenumber base to another; therefore, you can use it to convertfileperms()’s returned decimal value from base 10 to the desiredbase 8. The substr() function is then used to retrieve only the finalthree digits of base_convert()’s returned value, which are the onlydigits referred to when discussing Unix file permissions.

 

 

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

StreamMeta Data
arraystream_get_meta_data ( resource $stream )

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

Usingstream context and a few other techniques a lot can be done withoutresorting to sockets, however for more detailed control sockets canbe used.
Sockets allow read/writeaccess to various socket connections, while things like HTTP may seemread only, at the protocol level information is being sent toidentify the desired resource.

resourcefsockopen ( string $hostname [, int $port [, int &$errno [,string &$errstr [, float $timeout]]]] )
OpenInternet or Unix domain socket connection.

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

ForUDP sockets, you must use STREAM_SERVER_BIND as the flagsparameter.

arraystream_get_transports ( void )
Returnsan indexed array containing the name of all socket transportsavailable on the running system.

resourcestream_socket_accept ( resource $server_socket [, float $timeout [,string &$peername]] )
Accepta connection on a socket previously created bystream_socket_server(). If timeout is specified, the default socketaccept timeout will be overridden with the time specified in seconds.The name (address) of the client which connected will be passed backin peername if included and available from the selectedtransport.

peernamecan also be determined later using stream_socket_get_name().

arraystream_get_wrappers ( void )
Retrievelist of registered streams
Returns an indexed array containing thename of all stream wrappers available on the running system.

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

resourcestream_socket_client ( string $remote_socket [, int &$errno [,string &$errstr [, float $timeout [, int $flags [, resource$context]]]]] )

stringstream_socket_get_name ( resource $handle, bool $want_peer )
Retrievethe name of the local or remote sockets
Returns the local orremote name of a given socket connection. If
want_peeris set to TRUEthe remote socket name will be returned, if it is set to FALSEthe local socket name will be returned.

boolstream_filter_register ( string $filtername, string $classname)
Register a stream filterimplemented as a PHP class derived from
php_user_filter
makereference to
http://cn.php.net/manual/en/function.stream-filter-register.php

resourcestream_filter_prepend ( resource $stream, string $filtername [, int$read_write [, mixed $params]] )
resourcestream_filter_append ( resource $stream, string $filtername [, int$read_write [, mixed $params]] )

posted @ 2010-06-29 17:24  DavidHHuan  阅读(508)  评论(0编辑  收藏  举报