hello everybody,

i want to pass directory name as a variable in include function like this,

$page = 'test';
include('$page/test.php');

i know this a wrong way, but i don't know how to do it.
please anybody help in this regard.

Thank in advance....

Dani AI

Generated

The approach suggested by resolved the immediate issue for , but when an include built from a variable appears to "not work" there are a few common causes and safer practices to follow.

  • Verify the target file actually exists and uses the exact filename (case matters on Linux). Use filesystem checks and server logs rather than guessing.
  • Confirm the script’s working directory and PHP include_path — relative includes can fail when the current directory is different than expected.
  • Check file permissions and any open_basedir restrictions imposed by PHP or the host.
  • Make sure errors are visible while debugging (logs or display_errors) so you see warnings instead of silent failures.
  • Never include a file based on unvalidated user input. Whitelist allowed names or map keys to paths to avoid directory traversal and remote-file-inclusion risks.

A simple, safer pattern uses a whitelist, absolute paths and runtime checks before including:

$allowed = ['test','home'];
$dir = in_array($page, $allowed, true) ? $page : 'home';
$base = realpath(__DIR__ . '/pages');
$file = realpath($base . '/' . $dir . '/index.php');

if ($file && strpos($file, $base) === 0 && is_file($file) && is_readable($file)) {
    require_once $file;
} else {
    http_response_code(404);
}

For details on include behavior and the helper functions used above, see the PHP manual for include(), realpath(), and is_file(). Also review open_basedir restrictions if the environment blocks access to certain paths.

Recommended Answers

All 4 Replies

Use double quotes. Single quoted strings aren't parsed.

$page = 'test';
include("$page/test.php");

# this will also work
include($page . '/test.php');

but this code is not working, some else solution please....

Member Avatar for Member #117553

The proposed code works 100%, but maybe you have not explained precisely what do you want to do, or what errors you have, etc.

What pritaeas proposed is a 100% working solution to what you have described in your first post as a requirement.

yes, it was my mistake. this code is working fine......
Thank you very much Pritaeas and Rhyan......

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.