13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Writing to a File<br />

67<br />

Figure 2.3<br />

Using your own error messages instead of <strong>PHP</strong>’s can be more<br />

user friendly.<br />

Writing to a File<br />

Writing to a file in <strong>PHP</strong> is relatively simple.You can use either of the functions<br />

fwrite() (file write) or fputs() (file put string); fputs() is an alias to fwrite().You<br />

call fwrite() in the following way:<br />

fwrite($fp, $outputstring);<br />

This function call tells <strong>PHP</strong> to write the string stored in $outputstring to the file<br />

pointed to by $fp.<br />

An alternative to fwrite() is the file_put_contents() function. It has the following<br />

prototype:<br />

int file_put_contents ( string filename,<br />

string data<br />

[, int flags<br />

[, resource context]])<br />

This function writes the string contained in data to the file named in filename without<br />

any need for an fopen() (or fclose()) function call. This function is new in<br />

<strong>PHP</strong>5, <strong>and</strong> is a matched pair for file_get_contents(), which we discuss shortly.You<br />

most commonly use the flags <strong>and</strong> context optional parameters when writing to<br />

remote files using, for example, HTTP or FTP. (We discuss these function in Chapter 20,<br />

“Using Network <strong>and</strong> Protocol Functions.”)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!