Rookie Vee
Rookie Vee

Reputation: 113

Get directory of HTML page in PHP file that is called by the HTML page

I have an HTML page that uses a php file as a script file, like this:

<!doctype html>
<html lang="en">
<head>
...
<script src="../script.js.php"></script>
</head>
...

The script.js.php file has something like this:

<?php
  header('Content-type:text/javascript; charset=utf-8');
  $someVar = [];
  foreach (glob('*.txt') as $filename) {
    $someVar[] = $filename;
  }
?>
... here starts the javascript code

As can be seen, script.js.php is in a parent folder of the HTML file so what happens is that the PHP glob() function sees the parent folder, not the folder where the HTML page is, so it will list all text files inside that folder.

Is there a way to modify this code so that I can have $someVar with the list of the text files inside the folder of the HTML file?

Thank you.

EDIT: I think it needs a clarification. The same PHP file will be used by some other HTML files, different HTML files, located in different folders, using the same PHP/Javascript file. This is the problem, the PHP file should be ideally able to know the directory of its "caller", the HTML page that uses it. If I hard-code a solution into the PHP file for a certain HTML file, then the PHP file would not be useful anymore for the others. I could then simply use the PHP file inside the folder of each HTML file but then I would have theh same file repeated many times, which is very bad for maintenance purposes.

EDIT 2: I may have found a way to solve the problem. My HTML file becomes:

...
<script src="script.js.php"></script>
...

script.js.php becomes:

<?php
header('Content-type:text/javascript; charset=utf-8');
$curDir = getcwd();
include('../newfile.js.php');
echo file_get_contents("../rest.of.js.code.js");
?>

and newfile.js.php is:

<?php
$someVar = [];
foreach (glob($curDir . '/*.txt') as $filename) {
    $someVar[] = basename($filename);
}

echo "var someVar = " . json_encode($someVar) . ";\r\n";
?>

rest.of.js.code.js will now contain the Javascript code that existed before in script.js.php. This file and newfile.js.php stay in the parent directory; script.js.php will exist repeated (and with the path to newfile.js.php adjusted as needed) inside any of the HTML directories needed.

Upvotes: 0

Views: 817

Answers (1)

Madbreaks
Madbreaks

Reputation: 19539

You can use dirname:

$parentDir = dirname(dirname(__FILE__));

__FILE__ is a reference to the current PHP script (script.js.php). So you're getting the parent directory of the file, then you're getting the parent directory of that directory.

Upvotes: 1

Related Questions