Latest web development tutorials

PHP include and require

PHP include and require statements

In PHP, you can insert the contents of a file in the file before the server executes PHP file.

include and require statements for inserting written in other documents useful in the implementation of the code stream.

In addition to include and require different treatment than the wrong way, in other respects it is the same:

  • require generates a fatal error (E_COMPILE_ERROR), after the error script stops execution.
  • include generating a warning (E_WARNING), the script will continue execution after an error occurred.

So, if you want to continue, the output to the user, even if it contains a file is missing, then please use include. Otherwise, in the framework, CMS or complex application programming in PHP, always use require a reference to the execution flow of critical files. This helps to improve the safety and integrity of the application, in an unexpected critical file loss situations.

Save a document that contains a lot of work. This means you can create a standard header for all pages, footer, or menu file. Then, when you need to update the page header, you can simply update the page header contains files.

grammar

include 'filename';

或者

require 'filename';

PHP include and require statements

BASE CASE

Suppose you have a standard header file, called "header.php". To refer to this header file in a page, use the include / require:

<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>

<?php include 'header.php'; ?>
<h1>欢迎来到我的主页!</h1>
<p>一些文本。</p>

</body>
</html>

Example 2

Suppose we have a standard menu file used in all pages.

"Menu.php":

echo '<a href="/">主页</a>
<a href="/html">HTML 教程</a>
<a href="/php">PHP 教程</a>';

All site pages should reference the file menu. The following are the specific practices:

<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>

<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>欢迎来到我的主页!</h1>
<p>一些文本。</p>

</body>
</html>

Example 3

Suppose we have a variable that contains the definition file ( "vars.php"):

<?php
$color='red';
$car='BMW';
?>

These variables can be used in the call file:

<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>

<h1>欢迎来到我的主页!</h1>
<?php 
include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>

</body>
</html>