meda meda - 3 months ago 11
PHP Question

How to add content to PHP include files?

Ok I may not have the best title , but I will try to give a better explanation.

Let's assume you are using PHP include() to structure your website:

Header.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name=keywords content="somthiefn"/>
<title>Website</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
<script src="Scripts/jquery-1.8.3.min.js"></script>
<link rel="icon" type="image/png" href="/images/favicon.ico" />
</head>
<body>


Footer.php

</body>
</html>


Then a sample page:

Index.php

<!--Header-->
<?php include ('includes/header.php'); ?>

<div class="content">
<!-- some content-->
</div>

<!--Footer-->
<?php include ('includes/footer.php'); ?>


Basically I just want to know if there is a way to load some script into my header section.

I would like to achieve something like ASP.NET and its master Page, where I can just add content the header. for example

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="Scripts/somescript.js"></script>
</asp:Content>

Answer

In index.php, before you include header.php, you could set an array for your scripts like:

header.php

<?php if(!isset($scripts)) $scripts = array(); ?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name=keywords content="somthiefn"/>
        <title>Website</title>
        <link rel="stylesheet" href="css/style.css" type="text/css">
        <script src="Scripts/jquery-1.8.3.min.js"></script>
        <link rel="icon" type="image/png" href="/images/favicon.ico" />

        <!-- Include dynamic scripts-->
        <?php foreach($scripts in $script): ?>
        <script src="<?php echo $script; ?>"></script>
        <?php endforeach;?>

    </head>
    <body>

index.php

<?php
$scripts = array('Scripts/somescript.js', 'http://server.com/path/anoterscript.js);
?>

<!--Header-->
<?php include ('includes/header.php'); ?>

   <div class="content">
       <!-- some content-->
   </div>

<!--Footer-->
<?php include ('includes/footer.php'); ?>