PHP variables not passed in single quotations [clo

2019-09-17 11:20发布

问题:

I am trying to pass a variable $user which is defined as the name of the directory the page is in to an iframe on the page.

The variable $user is supposed to pass the username to the iframe so the iframe can download the user's minecraft skin and display it. This code works when I replace the variable in the iframe with a username but the iframe recognizes $user as $user...

The main page:

<link rel="stylesheet" type="text/css" href="/css/index.css" />
<?php
    $path = DIRNAME($_SERVER['PHP_SELF']);
    $position = STRRPOS($path,'/') + 1;
    $user= SUBSTR($path,$position);
    $root="/";

include ($_SERVER['DOCUMENT_ROOT'].'/menu/nav.php');

echo '<iframe src="skin.php?user=$user" width="200" height="400" align="left"/>'
?>

The iframe:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php  $user = $_GET['user']; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="/js/excanvas.js" type="text/javascript"></script>
<script src="/js/minecraftskin.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function() {
        $(".mc-skin").minecraftSkin();
    });
</script>
</head>
<style>
* {
    margin:0;
    padding:0;
}
div {
    display:inline-block;
}
.minecraft_head .head {
    display:none;
}
.minecraft_head:hover .hat {
    display:none;
}
.minecraft_head:hover .head {
    display:inline-block;
}
.scratch {
    display:none;
}
</style>
<body>

<span class="mc-skin" data-minecraft-username="<?php echo $user; ?>"></span>
</body>
</html>

How can I correct this?

回答1:

PHP doesn't parse variables within single quotation marks, change this line:

echo '<iframe src="skin.php?user=$user" width="200" height="400" align="left"/>'

to this (concantenated string style):

echo '<iframe src="skin.php?user=' .$user. '" width="200" height="400" align="left"/>'

or this (in-line variable style using double quotations):

echo "<iframe src='skin.php?user=$user' width='200' height='400' align='left'/>"


回答2:

Variables are not interpolated inside single quotes. Either put them in double quotes or outside quotes

echo '<iframe src="skin.php?user=$user" width="200" height="400" align="left"/>'

should be

echo '<iframe src="skin.php?user='.$user.'" width="200" height="400" align="left"/>';


回答3:

This wont work.

Sincel quotes' , don't support inline variables.

Double quotes, " do.

This will work:

echo "<iframe src=\"skin.php?user=$user\" width=\"200\" height=\"400\" align=\"left\"/>";