In this section I will cover:
Opening and closing files
Reading from and writing to files
Getting information about a file
Copying, renaming, deleting files
File permissions
File locks
Sending e-mail
MIME
HTML E-mails
Multipart E-mails
- Files — Opening and Closing
- Files are open using the fopen() function:
fopen ($filename, $mode)
returns a file resource (not a pointer!)
The $mode parameter indicates how the file should be open:
r — read only
r+ — read/write
w — write only and create the file
w+ — read/write and create the file
a — write only and position at end of file
a+ — read/write and position at end of tile
x — write only, fail if file already exists
- Files — Opening and Closing
- If your PHP has been compiled with URL wrappers support, fopen() works both on local and “remote” files via any of the supported protocols:
fopen (“http://www.phparch.com”, “r”);
Files can be closed using fclose()
This is not necessary , because PHP closes all open handles at the end of cript
However, it’s a good idea in some cases - Files — Reading & Writing
- Data is read from a file through a number of functions. The most common one is fread():
$data = fread ($file, $qty);
Returns the maximum data available, up to $qty bytes
The fgets() function reads data one line at a time:
$data = fgets ($file, $maxLen);
Returns data up to (and including) the next newline character or $maxLen - 1;
May or may not work depending on how the file has been encoded
auto_detect_line_endings PHP.INI setting - Files — Reading and Writing
- Writing works in a similar way:
fwrite ($file, $data)
Writes as much of $data as possible, returns amount written
You can also use fputs(), which is effectively an alias for fwrite() - Files — File Position
- The file position is updated as your read from or write to a file
ftell ($file) — Returns the current offset (in bytes) from the beginning of the file
You can manually alter the current position using fseek():
fseek ($file, $position, $from)
$from can be one of three constants:
SEEK_SET (beginning of file)
SEEK_CUR (current offset)
SEEK_END (end of file — $from should be < 0) - Files — File Information
- The fstat() function returns several pieces of information about a file:
var_dump (fstat ($file))
[dev] => 5633 // device
[ino] => 1059816 // inode
[mode] => 33188 // permissions
[nlink] => 1 // number of hard links
[uid] => 1000 // user id of owner
[gid] => 102 // group id of owner
[rdev] => -1 // device type
[size] => 106 // size of file
[atime] => 1092665414 // time of last access
[mtime] => 1092665412 // time of last modification
[ctime] => 1092665412 // time of last change
[blksize] => -1 // blocksize for filesystem I/O
[blocks] => -1 // number of blocks allocated
- Files — File Information
- The stat() function is a version of fstat() that does not require you to open the file
var_dump (stat ($fileName))
Several functions provide only portions of the info returned by stat() and fstat()
file_exists ($fileName)
fileatime ($fileName) — Last access time
fileowner ($fileName)
filegroup ($fileName)
The results of these functions are cached. This can lead to confusing results if you make changes to a file in the same after you’ve run one of these convenience functions - Files — File Information
- File permissions can be determined using either the bitmask from fstat() or some more convenience functions
is_readable ($fileName);
is_writable ($fileName);
is_executable ($fileName);
is_uploaded_file ($fileName);
They can also be changed:
chmod ($fileName, 0777);
Note use of octal number
The filesize() function returns the size of a file
echo filesize ($fileName) - Copying, Renaming & Deleting
- Files can be copied using the copy() function:
copy ($sourcePath, $destPath)
• Renaming is done through rename():
rename ($sourcePath, $destPath);
Guaranteed to be atomic across the same partition
• Files are deleted using unlink():
unlink ($fileName);
NOT delete()!
• Files can also be “touched”:
touch ($fileName);
• All these functions report success/failure via a
Boolean value - Directories
- Directories cannot be removed using unlink:
$success = rmdir ($dirName);
The directory must be empty. This means that you must write your own code to
empty the directory and any subdirectories - File Locking
- File locking ensures ordered access to a file. PHP’s locking module is collaborative. Every application that accesses the file must use it. Locks can be shared or exclusive
$lock = ($file, $lockType, &$wouldBlock);
$lockType: LOCK_SH, LOCK_EX
To release a lock: LOCK_UN
To prevent blocking, OR with LOCK_NB
Several limitations: Doesn’t work on most networked filesystems, or on FAT (Win98). Sometimes implemented per-process - More File Fun
- Some useful file functions
• file():
Reads an entire file in memory, splits it along newlines
• readfile():
Reads an entire file, outputs it
• fpassthru():
Same as readfile(), but works on file pointer and
supports partial output
• file_get_contents():
Reads entire file in memory. Remember that file_put_contents() is a PHP 5-only function! - PHP and E-mail
- PHP supports sending of e-mail through the mail() function. Contrary to popular belief, it’s not always available. Relies on sendmail in UNIX, implements its own wrappers in Windows and Netware. Built-in wrappers do not support authentication. The from address is set automatically under Linux
(php_user@serverdomain), must be set in PHP.ini under Windows - E-mail — The mail() Function
- The mail() function accepts five parameters:
mail ($to, $subject, $body, $headers, $extra)
mail() provides a raw interface to sending mail
No support for attachments
No support for MIME
No support for HTML mail
Extra headers can be set, including overriding the default From:
On UNIX machines, this may require setting -f in $extra
This may not work if PHP user is not “trusted” by sendmail - E-mail — MIME
- E-mail only supports 7-bit ASCII. Good for anglophones, not so good for the rest of the world. MIME provides support for sending arbitrary data over e-mail
MIME is supported by most MUAs, although often the target of spam filters
MIME headers also define the type of data that is being sent as part of an e-mail: For example, HTML:
"MIME-Version: 1.0\r\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\r\n" .
"Content-Transfer-Encoding: 7bit\r\n" - E-mail — MIME and Multipart
- Multipart e-mails make it possible to send an e-mail that contains more than one “part”
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/alternative;\r\n" .
" boundary=\"{$boundary}\"\r\n";
Examples:
HTML and Text bodies (plain-text should go first)
Attachments
Most clients support multipart—but for those who don’t, you always provide a plain-text message at the beginning
“If you are reading this, your client is too old!” - E-mail — MIME and Multipart
- The different parts are separated by a unique boundary
$message .= "--" . $boundary . "\r\n" .
"Content-Type: text/plain; charset=us-ascii\r\n" .
“Content-Transfer-Encoding: 7bit\r\n\r\n" .
"Plain text" .
"\r\n\r\n--" . $boundary . "--\r\n";
Note the two dashes before each boundary, and after the last boundary
Binary attachments must be encoded:
"Content-Transfer-Encoding: base64\r\n" .
‘Content-disposition: attachment; file="l.gif"\r\n\r\n"
base64_encode ($file); - E-mail — Getting a handle
- It’s impossible to know whether an e-mail was successfully sent mail() only returns a success/failure Boolean for its end of the deal. E-mail can get lost at pretty much any point in the tranmission process. The mail protocol does not have a thoroughly-respected feedback mechanism
»
- 1766 reads












