0

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?

5
  • Your path is just wrong, try it in a browser. Commented Jul 4, 2014 at 13:54
  • 1
    Pay attention to the require_once thing it's showing you. public_htmltemplates probably isn't right! Commented Jul 4, 2014 at 13:54
  • shouldn't it be public_html/templates? Commented Jul 4, 2014 at 13:55
  • remove the dbl quotes from "$style_assets_path" like $style_assets_path. And "$template" as well Commented Jul 4, 2014 at 13:57
  • Also, everything should be in parens. Try this: require_once( dirname(FILE) . "/config.php"); Commented Jul 4, 2014 at 14:00

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
    }

1 Comment

$template would still be out of scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.