-3

I understand the functionality and differences of include(), require(), include_once(), require_once().

Please can someone tell me some real world practical usage of them in projects. I know that common functions can be stored in a separate file and can be imported to improve manageability.

What are other common usage of them, for example, when database accessing, etc? Can they be used to improve security, etc.?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Kasuni
  • 83
  • 8
  • 3
    The answer to this question can be found in general search in google. http://www.w3schools.com/php/php_includes.asp http://php.net/manual/en/function.require.php and more sources. – Omari Victor Omosa Mar 17 '16 at 14:23

1 Answers1

2

It's mainly for code re-usability - this page sums it up rather well:

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

It's used in many many PHP based platorms (Wordpress, Magento etc) and one of the common uses is for headers and footers.

UPDATE

Regarding Security

They can lower or higher security depending on how you use them. Remote file inclusion is an example of how it can lower page security. Something like:

<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
require $page . '.php';
?>

Imagine that at example.com/malice.php a file exists and our script is located at site.com/index.php. The attacker will do this request: site.com/index.php?page=www.example.com/malice. This file will get executed when it is included and it could write a new file to the disk.

An example where security could be improved:

<?php
// This script from your servers webroot
require '../public_index.php';
?>

This will access a file from outside you webroot. Default apache web users do not have premissions to view anything outside the webroot therefore they should never be able to access public_index.php (unless they obtained credentials of a user that was able to access - root for example).

A real world application of this kind of measure would be Wordpress' wp-config.php file which can be placed outside the servers webroot.

Source

A brief description outlining the difference between using require & require_once

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).

So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

Source

I hope this helps.

Community
  • 1
  • 1
Chris Rogers
  • 1,525
  • 2
  • 20
  • 40