I am doing something very simple, and would like some insight as to why some file path references work and others don't. My test code is as follows:
<?php
$menu1 = 'c:/xampp/htdocs/data/sc01/includes/menu.php';
$menu2 = 'http://localhost/data/sc01/includes/menu.php';
$test1 = 'http://localhost/data/sc01/css/style.css';
$test2 = 'c:/xampp/htdocs/data/sc01/css/style.css';
$test3 = 'css/style.css';
echo $test1; echo "<br>";
echo $test2; echo "<br>";
echo $test3; echo "<br>";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="<?php echo $test2; ?>">
<link rel="stylesheet" href="css/font-awesome.min.css">
<title>Index</title>
</head>
<body>
<div id="container">
<?php include "$menu1"; ?>
<h1>Welcome to our site!</h1>
<p>This is a test coment</p>
</div>
</body>
<div class="footer-container">
<?php include "c:/xampp/htdocs/data/sc01/includes/footer.php"; ?>
</div>
</html>
My questions:
Thanks in advance!
None of the strings beginning with c:
are valid URLs, so you can't use them in href
or src
attributes in HTML. You can use them in PHP include
lines because those are processed by the server, and it allows the argument to be local filenames.
<?php include '$menu1' ?>
doesn't work because PHP only expands variables inside doublequoted strings, not inside singlequoted strings. It's just like the difference between:
echo "$menu1";
and
echo '$menu1';
The first will echo the value of the variable, the second will echo $menu1
literally.
Including via http://
vs via file system path are two significantly different things – the first one will only get you the output of the script¹, whereas the second one includes the code of the file, and then runs it within the scope the main script afterwards.
In the include menu code,
<?php include "$menu1"; ?>
<?php include "$menu1"; ?>
, double quotes work. But single quotes '$menu1' does not work, but I thought single or double quotes should yield the same results. WHY IS THIS?
Because you “think” instead of reading up on the very basics of the syntax. So go fix that now: http://www.php.net/manual/en/language.types.string.php
¹ Assuming of course, that requesting the file via HTTP means that it is put through the PHP interpreter by the web server first, but that is usually the case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.