【问题标题】:PHP Header adding multiple timesPHP Header 多次添加
【发布时间】:2017-12-05 11:28:54
【问题描述】:

我有这个问题:

$get_ids = "SELECT unique_id FROM products GROUP BY unique_id LIMIT 10";
$id_results = mysql_query($get_ids);
while($id_row = mysql_fetch_array($id_results))
{
    extract($id_row);
    $all_prods_link[] = $id_row['unique_id']; 
}

这将创建一个整数数组。对于数组中的每个项目,我将其附加到一个字符串,后跟一个逗号:

foreach($all_prods_link as $all_prods)
{
    $query_string .= $all_prods.',';
}

结果类似于:1,2,3,4,5,6,按预期工作。

我遇到的问题是我试图将它添加到当前 URI 的末尾,然后重定向到这个 URI,例如:

$link = $_SERVER['REQUEST_URI'] . '&product_options=' . $query_string;

$link 变量看起来不错:

sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,

这正是我想要的,但是当我尝试重定向到此链接时,例如:

header("Location: $link");

我最终得到的实际 URI 有 $query_string,多次附加到它上面,如下所示:

sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,

如您所见,“&product_options”出现多次,后面是整数列表!

header() 函数可以这样使用吗?还是我做错了什么!

【问题讨论】:

  • 这不是 header 函数的错...在此之前对您的 $link 变量进行调试输出,并检查它包含的内容。
  • “我遇到的问题是我试图将其添加到当前 URI 的末尾” - 这个当前 URL 是否已经包含 &product_options=... ?如果你只是追加到它的末尾,那么你不应该对多次获取它感到惊讶。
  • foreach($all_prods_link as $all_prods) { $query_string .= $all_prods.','; } err,您应该为此使用implode()
  • @CBroe $link 变量实际上包含我需要的内容,请参阅我的帖子中以“$link 变量看起来不错:”开头的部分,你能告诉我为什么 header("Location: $链接");没有准确地转到 $link?

标签: php


【解决方案1】:

这是因为每次加载页面时多次重定向,php 会追加 product_options 而不是替换它。

<?php

// Parse all request components
$request = parse_url($_SERVER['REQUEST_URI']);

// Parse incoming query sting to array
parse_str($request['query'], $queryArray);

// replace or add product_options
$queryArray['product_options'] = $query_string;

// rebuild the query
$newQueryString = http_build_query($queryArray);

$link = $request['path']. '?' . $newQueryString;

header("Location: $link");

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 2014-03-14
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2012-07-06
    • 2014-03-03
    相关资源
    最近更新 更多