Learning PHP by David Sklar

Learning PHP by David Sklar

Author:David Sklar
Language: eng
Format: epub
Publisher: O'Reilly Media
Published: 2016-04-06T16:00:00+00:00


Example 9-7. Opening a file on Windows

$fh = fopen('c:/windows/system32/settings.txt','rb');

Because backslashes have a special meaning (escaping, which you saw in “Defining Text Strings”) inside strings, it’s easier to use forward slashes in filenames. The PHP engine does the right thing in Windows and loads the correct file.

The second argument to fopen() is the file mode. This controls what you’re allowed to do with the file once it’s opened: reading, writing, or both. The file mode also affects where the PHP engine’s file position bookmark starts, whether the file’s contents are cleared out when it’s opened, and how the PHP engine should react if the file doesn’t exist. Table 9-1 lists the different modes that fopen() understands.

Table 9-1. File modes for fopen() Mode Allowable actions Position bookmark starting point Clear contents? If the file doesn’t exist?

rb Reading Beginning of file No Issue a warning, return false.

rb+ Reading, Writing Beginning of file No Issue a warning, return false.

wb Writing Beginning of file Yes Try to create it.

wb+ Reading, writing Beginning of file Yes Try to create it.

ab Writing End of file No Try to create it.

ab+ Reading, writing End of file No Try to create it.

xb Writing Beginning of file No Try to create it; if the file does exist, issue a warning and return false.

xb+ Reading, writing Beginning of file No Try to create it; if the file does exist, issue a warning and return false.

cb Writing Beginning of file No Try to create it.

cb+ Reading, writing Beginning of file No Try to create it.

Once you’ve opened a file in a mode that allows writing, use the fwrite() function to write something to the file. Example 9-8 uses the wb mode with fopen() and uses fwrite() to write information retrieved from a database table to the file dishes.txt.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.