what is difference between header and include, where which one should be used

1 tells PHP to send a Location header to the HTTP client, forcing a redirect to "homepage.php".

2 tells PHP to include "homepage.php" inline to execution of the current page.


As a note about your question, your confusion might be over the term "header". It is overloaded sometimes to refer to the top part of a page in reference to code separation. Code separation is a common practice where one puts PHP code/HTML used in multiple pages into a separate file, and then included in the top (header) of each page.

HTH,

-aj


Header forwards the user to a new page, so PHP reinitializes, it's like a HTML meta redirection, but faster.

Include just includes the file where you call it, and it executes it as PHP, just like if the code from homepage.php was written where you write <?php include('homepage.php'); ?>.


The header function is used to send raw HTTP headers back to the client: PHP header function

<?php
header("HTTP/1.0 404 Not Found");
?>

The above (taken from the PHP documentation) sends a 404 header back to the client.

The include function is used to include files into the current PHP script (the same as require) PHP include function

vars.php

<?php
$color = 'green';
$fruit = 'apple';
?>

test.php

<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>

This example (again from the PHP documentation) includes the vars.php script in the test.php script and, after the include, allows the test.php script to access the variables declared in the vars.php script.

Tags:

Php