包含在 PHP 中无效

Include in PHP is ineffective

我创建了一个名为 index.php 的文件,在与 index.php 相同的文件夹中有名为 "includes".

的文件夹

里面有两个PHP文件,head.phpheader.php。问题是这两个文件没有包含在 index.php 中。现在,我搜索了整个 Stack Overflow,似乎找不到答案。

<!doctype html>
<html>
    <?php include 'includes/head.php'; ?>

    <body>
        <?php include 'includes/header.php'; ?>
        <div id="container">
            <aside>
                <div class="widget">
                    <h2>Widget Header</h2>
                    <div class="inner">
                        Widget contents
                    </div>
                </div>
            </aside>
        </div>
    </body>

</html>

尝试使用

include("includes/head.php");

根据我对 OP 的评论:

@canthandlehtml question is now, if you have a webserver/PHP installed, if it's properly configured, and how you're accessing this. As http://localhost/file.php or as c://file.php in your web browser? Those are 2 different animals altogether. – Fred -ii-

根据您的评论:

I am indeed accessing it as c://file.php, I was not aware this might be a problem, forgive for the inadequacy, php is something completely new for me

您正在以 c://file.php 而不是 http://localhost/file.php 的身份访问它,这就是为什么您的包含不起作用的原因。

Web 浏览器不会以这种方式 parse/execute PHP 指令。它需要 运行 通过安装了 Web server/PHP、运行 并正确配置的主机。

旁注:

要包含的代码应该 "echo" 一些东西,以便 "show" 一些东西,如果这是意图的话;回显 HTML 等

看到<?php include 'includes/header.php'; ?>,我认为您有一种导航菜单形式。

如果它包含如下内容:

<?php
    $var = "Hello world";

它不是 "echo'd",那么它不会出现在你的渲染中 HTML,它需要回显。

<?php
    echo $var = "Hello world"; // this is a valid directive
                               // it both echo's and assigns

不确定 <?php include 'includes/head.php'; ?> 是否包含元数据,或是否包含 CSS 等,以及它是否包含 <head></head> 标签。如果没有,那么你将需要添加那些(如果你包含),或者需要在 head 标签中的 JS 等。


error reporting 添加到您的文件的顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:显示错误只应在试运行中进行,绝不能在生产中进行。

假设网页是通过网络服务器而不是直接从文件系统访问的,那么使用/设置 include_path 应该有助于缓解这个问题(也就是说,在包含的文件中使用 echo是更常用的方法!)

您可以使用文件系统路径包含文件,但您不能在没有网络服务器的浏览器中 运行/执行 php。

<?php
    /* Once the include path is set it is easy to include the file by name alone */
    set_include_path( __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR );
?>
<!doctype html>
<html>
    <head>
        <?php 
            include('head.php');
        ?>
    </head>
    <body>
        <?php 
            include('header.php');
        ?>
        <div id='container'>
            <aside>
                <div class='widget'>
                    <h2>Widget Header</h2>
                    <div class='inner'>
                        Widget contents
                    </div>
                </div>
            </aside>
        </div>
    </body>
</html>