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.

136 Chapter 5 Reusing Code <strong>and</strong> Writing Functions<br />

A file is needed to use a require() statement. In the preceding example, you used the<br />

file named reusable.php.When you run the script, the require() statement<br />

require( ‘reusable.php’ );<br />

is replaced by the contents of the requested file, <strong>and</strong> the script is then executed.This<br />

means that when you load main.php, it runs as though the script were written as<br />

follows:<br />

<br />

When using require(), you need to note the different ways filename extensions <strong>and</strong><br />

<strong>PHP</strong> tags are h<strong>and</strong>led.<br />

<strong>PHP</strong> does not look at the filename extension on the required file.This means that<br />

you can name your file whatever you choose as long as you do not plan to call it directly.When<br />

you use require() to load the file, it effectively becomes part of a <strong>PHP</strong> file<br />

<strong>and</strong> is executed as such.<br />

Normally, <strong>PHP</strong> statements would not be processed if they were in a file called, for<br />

example, page.html. <strong>PHP</strong> is usually called upon to parse only files with defined extensions<br />

such as .php. (This may be changed in your web server configuration file.)<br />

However, if you load page.html via a require() statement, any <strong>PHP</strong> inside it will be<br />

processed.Therefore, you can use any extension you prefer for include files, but sticking<br />

to a sensible convention such as .inc or .php would be a good idea.<br />

One issue to be aware of is that if files ending in .inc or some other nonst<strong>and</strong>ard<br />

extension are stored in the web document tree <strong>and</strong> users directly load them in the<br />

browser, they will be able to see the code in plain text, including any passwords. It is<br />

therefore important to either store included files outside the document tree or use the<br />

st<strong>and</strong>ard extensions.<br />

Note<br />

In the example, the reusable file (reusable.php) was written as follows:<br />

<br />

The <strong>PHP</strong> code was placed within the file in <strong>PHP</strong> tags.You need to follow this convention<br />

if you want <strong>PHP</strong> code within a required file treated as <strong>PHP</strong> code. If you do not<br />

open a <strong>PHP</strong> tag, your code will just be treated as text or HTML <strong>and</strong> will not be<br />

executed.

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

Saved successfully!

Ooh no, something went wrong!