如何使用 URL 传递 PHP 变量 [英] How to pass a PHP variable using the URL

查看:34
本文介绍了如何使用 URL 传递 PHP 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 URL 传递一些 PHP 变量.

I want to pass some PHP variables using the URL.

我尝试了以下代码:

链接.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>`</pre></code>

pass.php
<pre><code>`<html>
<body>
<?php
if ($_GET['link']==$a)
{
echo "Link 1 Clicked";
} else {
echo "Link 2 Clicked";
}
?></body></html>

点击链接 Link1Link2 后,我得到点击链接 2".为什么?

Upon clicking the links Link1 and Link2, I get "Link 2 clicked". Why?

推荐答案

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

In your link.php your echo statement must be like this:

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

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

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

您可以直接将其与这样的字符串进行比较:

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

另一种方法是首先将变量初始化为您对 link.php 所做的相同操作.而且,更好的方法是将 $a$b 变量包含在单个 PHP 文件中,然后将其包含在要使用这些变量的所有页面中正如蒂姆库珀在他的帖子中提到的那样.您也可以将其包含在会话中.

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

这篇关于如何使用 URL 传递 PHP 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆