08 Jul PHP require Statement
Use the PHP require statement to include a file into your PHP code. The script execution stops if the file to be included isn’t found. Let’s say you need to add a section on the website, which is repeated on every page, for example, the footer or sidebar. For that, add it using the PHP require() statement and eliminate the need of adding separate Lines of Code again and again.
The following is the syntax of require() statement,
1 2 3 |
require 'filename'; |
Now, we will learn with an example. We have two files, credits.php, and index.php.
The following is the code for index.php. Here, we are using require to include file credits.php,
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <body> <h1>Studyopedia</h1> <p>One stop destination for learning!.</p> <?php require 'credits.php';?> </body> </html> |
The following is the code for credits.php. This file gets added to the index.php file since we included it using require previously in index.php,
1 2 3 4 5 |
<?php echo "<p>Copyright @2016 </p>"; ?> |
The following is the output,
Now, we will see another example, where a file powered.php isn’t part of our website is included. Here, you can see, nothing gets displayed in the output, only an error is visible since we’re using require(),
The following is the code for new.php. This file includes a file powered.php using require,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <body> <h1>Studyopedia</h1> <p>One stop destination for learning!.</p> <?php require 'powered.php';?> <p>This won’t get printed, since we’re trying to access a file that do not exist.</p> </body> </html> |
As shown above, we do not have a file, “powered.php”, so the text, “This won’t get printed, since we’re trying to access a file that does not exist” won’t get printed. Only an error can be seen as shown below,
No Comments