如何'添加'和'减去'$变量到URL字符串?

时间:2011-07-27 17:54:46

标签: php global-variables

在这里遇到问题....

我似乎无法找到一个很好的方法来'添加'和'减去'$变量到URL字符串....

以下是我的例子:

在网址中我有http://mywebsite.com/index.php?y=2011

对于源代码,我有:

$currentPage = $_SERVER['PHP_SELF'];

然后,如果我想在url字符串中添加不同的$变量,我一直在尝试这个......:

    echo '<a href="$currentPage.&t=col">College</a>';

但它没有保留当前网址的价值......?

显示:http://mywebsite.com/index.php?&t=col

而不是:http://mywebsite.com/index.php?y=2011&t=col(不保留$ y变量)

我还需要找到一种通过任何链接更改$ y和$ t变量的方法,因此我可以轻松地将其更改为2010或2009,同时保留当前的$ t变量.. ???

提前致谢!

这是我从伟大的帮助中得到的结果!!!

$url = "http://www.mywebsite/index.php?";
foreach($_GET as $key=>$val){
$url.="$key=$val&"; }
echo '<a href="' . htmlspecialchars($url . 't=col') . '">College</a>';

4 个答案:

答案 0 :(得分:3)

您可能知道,通过URL传递的所有变量都可以在$ _GET数组中找到。 因此,您可以使用以下内容设置链接:

$url = "http://site.com/index.php?";
foreach($_GET as $key=>$val){
$url.="$key=$val&"; }

这样,您还可以检查某些变量并删除某些可能被恶意添加的变量。它还允许您相应地更改变量,因为$ key将包含t或y

答案 1 :(得分:1)

我认为您的问题实际上与URL操作无关。它主要是一个基本的PHP语法问题。在PHP中,单引号和双引号字符串的处理方式不同。在双引号中你会得到变量插值,而在其他类型中则没有:

$foo = 'world!';
echo "Hello, $foo"; // Prints «Hello, world!»
echo 'Hello, $foo'; // Prints «Hello, $foo»

但是,所有双引号字符串都有特别之处。您不能在字符串中插入任意PHP代码并执行它:

echo "Size: strlen($foo) . 'chars'"; // Will *not* print «Size: 6 chars»

您可以在PHP手册的Strings章节中获得完整的参考。

此外,您可以使用.运算符连接字符串(请参阅String Operators):

echo 'Hello, ' . $foo; // Prints «Hello, world!»

熟悉这些概念后,您会发现它很容易。

答案 2 :(得分:1)

您可以使用http_build_query()功能重建查询,添加所需的额外参数。

// build the query data
$queryData = array(
     'y' => $_GET['y'],
     't' => 'col',
);
// get the query string
$queryString = http_build_query($queryData);

// ... somewhere later in the script
// we remember to escape HTML characters. as long as $currentPage has characters
// and cannot be manipulated by the client (which, if it is coming from PHP_SELF, it
// cannot be afaik), we should be safe
echo '<a href="' . htmlspecialchars($currentPage . $queryString) . '">College</a>';

答案 3 :(得分:0)

echo '<a href="$currentPage.?y=$_GET[\'y\'].&t=col">College</a>';