6

I have index.html in the root and all supporting files in /HTML. I have Google analytics code in a file in the HTML directory. It works from my index.html with this code in between the head tags...

<?php
require('HTML/GoogleAnalytics.html');
?>

but not in any of the supporting files in the HTML directory, same directory as the file i'm trying to require/include with this code...

<?php
require('GoogleAnalytics.html');
?>

from PHP.net "...include will finally check in the calling script's own directory and the current working directory before failing"

What am I doing wrong?

3 Answers 3

15

From PHP 5.3 (which is at this time after end of life cycle) and later you can use also __DIR__ constant , http://php.net/manual/en/language.constants.predefined.php

require(__DIR__ . '/GoogleAnalytics.html');
Sign up to request clarification or add additional context in comments.

1 Comment

replacing it with that line of code caused the page not to load at all. from the google site"PHP Implementation optional Create a PHP file named "analyticstracking.php" with the code above and include it on each PHP template page. Then, add the following line to each template page immediately after the opening <body> tag: <?php include_once("analyticstracking.php") ?>" What am I doing wrong?
6

To make it relative to the current file, you can prepend dirname(__FILE__) like so:

require(dirname(__FILE__) . '/GoogleAnalytics.html');

By default, paths are relative to the file that the request originated from.

1 Comment

I replaced my line of code with yours, and it didn't work. And I don't understand, it IS in the same place as the calling page/script. So I tried bumping it down one directory, so the file I want to include was in HTML/google/GoogleAnalytics.html. So it would have the same relationship as the index, where it worked. No luck. Index still worked when I added google to the path.
0

Try using this:

require('/HTML/GoogleAnalytics.html');

3 Comments

You may be new to PHP? ... Anyway, PHP says: Because include is a special language construct, parentheses are not needed around its argument. The same is true for include_once, require, and require_once. Yes, it is common to find them used with parenthesis, but not needed. Look at some of the examples at PHP.net. It's not a problem if used, but you could get "tripped up" by some interviewers about the use, and some coding standards wherever you work may not allow them. See this too.
@PaulT. Every example in this page is using parenthesis.
@T30 yes, I know, I was only mentioning PHPs info. One of those personal style matters, I guess.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.