Fatal error: require_once():

Fatal error: require_once():

我收到以下错误:

Warning: require_once(D:/xampp/htdocs/inc/head.php): failed to open stream: No such file or directory in D:\xampp\htdocs\ecommerce1\index.php on line 3

Fatal error: require_once(): Failed opening required 'D:/xampp/htdocs/inc/head.php' (include_path='.;D:\xampp\php\PEAR') in D:\xampp\htdocs\ecommerce1\index.php on line 3

我有以下代码:位于 D:\xampp\htdocs\ecommerce1 Index.php

<!--head-->
<?php $title="Gamer"?>
<?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/head.php';?>
<?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/menu.php';?>
<!--body of the page-->
<!--footer of the page-->
<?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/footer.php';?>
`

这是位于 D:\xampp\htdocs\ecommerce1\inc

head.php
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php print $title ?> </title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
    <script type="text/javascript" src="/jquery/jquery-1.12.3.min.js"></script>

</head>
<body>

在您的 index.php 中执行此操作。

<?php $title="Gamer"?>
<?php require_once 'inc/head.php';?>
<?php require_once 'inc/menu.php';?>
<!--body of the page-->
<!--footer of the page-->
<?php require_once 'inc/footer.php';?>

希望这对您有所帮助。

除非您明确更改 Apache httpd.conf 中的 DocumentRoot 设置,否则文档根默认位于 D:/xampp/htdocs 中。

所以你需要调用:

<?php require_once $_SERVER["DOCUMENT_ROOT"]. 'ecommerce1/inc/head.php';?>

而不是

<?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/head.php';?>

有两种方法可以在 php

中包含文件

方法一:include()

<?php $title= "Gamer"; ?>
<?php include('inc/head.php');?>
<?php include('inc/menu.php');?>
<!--body of the page-->
<!--footer of the page-->
<?php include('inc/footer.php');?>

方法二:require_once()

<?php $title= "Gamer"; ?>
<?php require_once('inc/head.php');?>
<?php require_once('inc/menu.php');?>
<!--body of the page-->
<!--footer of the page-->
<?php require_once('inc/footer.php');?>

作为初学者,您应该知道何时使用 include() 以及何时使用 require()

在您的情况下,请使用 include() 而不是 require_once()

这背后的原因是,如果require_once()加载文件失败,那么脚本执行将立即停止。如果你使用 include() 它只会抛出一个错误并继续执行。

那么,什么时候使用 require_once() 而不是 include()

在包含 PHP(或重要的服务器端)脚本时使用 require_once(),在包含类似模板的文件时使用 include()

看看这个例子:

<?php include_once('inc/head.php');?>
<?php include_once('inc/menu.php');?>

<!--if including a script-->
<?php require_once('inc/footer.php');?>

注意:最好使用括号并将这些函数视为函数。