Home > database >  Including file in head using PHP string replace
Including file in head using PHP string replace

Time:12-29

I am trying to include a head.php file in index.php using PHP string replace.

My Code (index.php) :

$headin = include "head.php";

$context = stream_context_create(
    array(
        "http" => array(
            "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
        )
    )
);

$homepage = file_get_contents("https://www.example.com/", false, $context);
$homepage = str_replace("<head>", "<head>". $headin, $homepage);
echo $homepage;

The problem is, the content of head.php displaying above the <html> instead of displaying inside <head>.

Edited (Solution) :

$headin = file_get_contents('head.php');

Thanks everyone for help.

CodePudding user response:

Solution :

Using of file_get_contents instead of include.

My problem got fixed by replace my code from $headin = include "head.php"; to $headin = file_get_contents('head.php');

Thanks to @RiggsFolly

CodePudding user response:

If your goal to reuse page components - there are many possibilities ...

require_once

You can use require_once to include the content

index.php

<!doctype html>
<html>
    <?php require_once 'head.php'; ?>
<body>
</body>
</html>

head.php

<head>
<meta charset="utf-8">
<title><?= basename($_SERVER['REQUEST_URI'],'.php') ?></title>
</head>

RewriteRule

Another approach would be to use a rewrite rule that routes all traffic through index.php and then include the relevant content

<Directory "/">
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php [L]
</Directory>

Test it out with

index.php

<?php
header('Content-Type: text/plain');
var_dump($_SERVER);

pre/post pend

You can also use Apache to add head and tail content

<Directory "/">
php_value auto_prepend_file head.php
php_value auto_append_file tail.php
</Directory>

head.php

This could include navigation

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= basename($_SERVER['SCRIPT_FILENAME'],'.php') ?></title>
</head>
<body>

tail.php

This could include a page footer.

</body>
</html>

CodePudding user response:

If file head.php is echoing some thing , then the content of that file will be echoed as soon as it is included . so you can either shift the content in head.php into a function and call that function inside this file

If moving content to function is not possible then you can use php's output buffering https://www.php.net/manual/en/function.ob-start.php

  • Related