使用url传递php变量

che*_*tan 16 php url

我想使用url传递一些php变量...我尝试了以下代码.

link.php

<html>
<body>
<?php
$a='Link1';
$b='Link2';
echo '<a href="pass.php?link=$a">Link 1</a>';
echo '<br/>';
echo '<a href="pass.php?link=$b">Link 2</a>';
?></body></html>
Run Code Online (Sandbox Code Playgroud)

pass.php

<html>
<body>
<?php
if ($_GET['link']==$a)
{
echo "Link 1 Clicked";
} else {
echo "Link 2 Clicked";
}
?></body></html>
Run Code Online (Sandbox Code Playgroud)

点击链接(即Link1和Link2)我点击链接2 ....你能找出问题吗?

ace*_*ace 22

在你的link.php中,你的echo语句必须是这样的.

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Run Code Online (Sandbox Code Playgroud)

然后在你的pass.php中你不能使用$ a,因为它没有用你想要的字符串值初始化.

虽然你可以直接将它与这样的字符串进行比较.

if($_GET['link'] == 'Link1')
Run Code Online (Sandbox Code Playgroud)

另一种方法是首先将变量初始化为与link.php相同的变量.更好的方法是在单个php文件中包含$ a和$ b变量.然后包括在你将要使用该变量的所有页面中,Tim Cooper在他的帖子中提到.您也可以在会话中包含此内容.


Tim*_*per 6

你传递link=$alink=$b分别在HREF中的A和B.它们被视为字符串,而不是变量.以下内容应该为您解决:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

// and

echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Run Code Online (Sandbox Code Playgroud)

价值$a也不包括在内pass.php.我建议制作一个公共变量文件并将其包含在所有必要的页面上.