user3188159
user3188159

Reputation:

PHP require_once fails?

So, I'm trying to build a template-loader system with PHP. Here's what I got so far:

config.php:

<?php
    $style_assets_path = "/includes/styles/";

    if ($_GET['page_id'] !== '1'){
        header('Location: /template.php?pageid=1');
        exit(0);
    }

    if ($_GET['page_id'] <= 100) {
        $template = "/main/main.php";
    }

    function loadTemplate() {
        require_once dirname(__FILE__) . "$style_assets_path" . "templates" . "$template";
        // This should output: /includes/styles/templates/main/main.php
    }
?>

home.php:

<?php
    require_once dirname(__FILE__) . "/config.php";
    loadTemplate($template);
?>

So I get the following error when I open home.php:

Warning: require_once(/home/xxxxxxx/public_htmltemplates/) [function.require-once]: failed to open stream: No such file or directory...

What am I doing wrong?

Upvotes: 0

Views: 74

Answers (2)

T.Todua
T.Todua

Reputation: 56555

HERE CORRECT ANSWER !!!!! Look carefully at your ERROR MESSAGE! that's because, that $style_assets_path is not determined in function. you should make those variables global in function:

 function loadTemplate() {
        global $style_assets_path;
        global $template;
        require_once dirname(__FILE__) . "$style_assets_path" . "templates" . "$template";
        // This should output: /includes/styles/templates/main/main.php
    }

Upvotes: 0

scragar
scragar

Reputation: 6824

Functions are in different scope to your global variables, you can't access them unless you either pass them in as arguments or use the global keyword(mentioned only for completeness).

If your values aren't going to change though declare them as constants, much prettier:

declare('STYLE_ASSETS_PATH', "/includes/styles/");

if ($_GET['page_id'] !== '1'){
    header('Location: /template.php?pageid=1');
    exit(0);
}

if ($_GET['page_id'] <= 100) {
    $template = "/main/main.php";
}

loadTemplate($template);

function loadTemplate($template) {
    require_once dirname(__FILE__) . STYLE_ASSETS_PATH . "templates" . "$template";
}

Upvotes: 1

Related Questions