Page 1 of 1

PHP: Include and Require

Posted: Tue Jul 15, 2014 12:31 pm
by smashapps
Hello everyone,

This is a quick tutorial on two functions known as include and require.

All that include and require do is grab all the text out of the file you've included/required and puts it into your document. The difference with include and require is that if there is an error with include i.e. can't find the file you've specified then your php code will just keep running. If there is an error with require your file will stop executing anymore code.

Two use include or require we need two files, the file we are including and our file we are calling include or require from. This example would connect to a database, we have our file that connects to the database and the file that stores our database details.

Our database details:
Code: Select all
<?php
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "password";
$dbDatabase = "someDatabase";
and here is the file we use to connect:
Code: Select all
<?php

require 'pathToFile/databaseDetails.php';

$connection= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbDatabase);

//Check our connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
Include:
Code: Select all
<?php

include 'pathToFile/databaseDetails.php';

$connection= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbDatabase);

//Check our connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
If we have a lot of files that connect to the database then this can be used to save time, one line instead of five, but also if you change your database details you only have to change one files. Of course also, you can use this for many other things.

I hope you all liked my quick tutorial and if you learnt anything give me a +rep :) thanks

#Birthday

Re: PHP: Include and Require

Posted: Wed Jul 16, 2014 9:33 pm
by Dummy1912
maybe we are wrong but
where is the include part :)

#Birthday

Re: PHP: Include and Require

Posted: Wed Jul 16, 2014 11:16 pm
by smashapps
Oops,

It's the same syntax as require though, so just use:
Code: Select all
<?php

include 'somefile.php';

?>
#Birthday

Re: PHP: Include and Require

Posted: Thu Jul 17, 2014 6:20 am
by Dummy1912
hi,
so what the different then between them?
what does require
and does include

#Birthday

Re: PHP: Include and Require

Posted: Thu Jul 17, 2014 1:28 pm
by smashapps
require and include both use text from a seperate file in your code but if require has an error the code will stop executing, if include has an error it will continue to execute but without the file you wanted to include.

#Birthday