Include and path problem
<?php
// This is index.php
ob_start();
include 'tem/u.html';
ob_end_flush();
?>
<html>
<!-- This is u.html -->
<link rel="stylesheet" href="style.css" media="screen" />
<body>
<p> abc </p>
</body>
</html>
Now my problem is when i run h.html -> Ok with style.
But when i run index.php -> Ok without style (because now the index.php include style.css, not tem/style.css开发者_如何学Go) Need a fixIf possible, refer to a domain relative path to the style.css
, for example
<link rel="stylesheet" href="/style.css" media="screen" />
If that is not possible, you need to keep track on the page base in some way, which I cannot tell because I do not know enough about your application. But anyway, like
<link rel="stylesheet" href="<?php echo $pageBase; ?>/style.css" media="screen" />
where $pageBase is a variable containing the url to the root of your application.
I'm assuming that the tem
directory is supposed to be for some sort of template, and so you don't want it to be directly exposed to the user; rather, you want to be able to include the files so that they're accessible via index.php
, possibly with the option of later changing what files are included.
You could create another PHP file called style.php
(in the root directory) which would include tem/style.css
. You could do this for any other files that your templates used as well — the idea being that each PHP file in the root directory would correspond to a "role" in the template, not a particular template file, so that the template could later be changed without everything needing to be rewritten.
This might get a bit cumbersome if you had a lot of files required by your template, so it might be better to have a single script that could be instructed which file to load (through a $_GET
variable). But in that case, you need to be very careful not to allow the user to specify arbitrary files. I'd suggest avoiding this approach until you're more proficient in PHP.
EDIT: On second thought, I'd suggest using a <base>
tag in your template HTML file, as suggested in my comment on @gnud's answer.
This has nothing to do with PHP or include
. This has to do with your browser, and how URLs are interpreted.
When your browser is pointed at http://xyz.abc/tem/h.html
and asked to load "style.css", it tries to load http://xyz.abc/tem/style.css
- this is known as a relative url, relative to the current document location.
When your browser is at http://xyz.abc/index.php
and is asked to load the stylesheet in the same way, it tries http://xyz.abc/style.css
. Maybe you see the problem?
As for a solution, you might use a domain-relative path for the stylesheet ("/tem/style.css").
just always use absolute path to your css file
<link rel="stylesheet" href="/tem/style.css" media="screen" />
that's all
精彩评论