Aaranihlus
Aaranihlus

Reputation: 149

PHP Header adding multiple times

I have this query:

$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']; 
}

This will create an array of integers. For each item in the array, I append this to a string, following by a comma:

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

The result is like: 1,2,3,4,5,6, which is working as intended.

The problem I am having is I am trying to add this to the end of the current URI, and then redirect to this URI eg:

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

The $link variable looks good:

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,

This is exactly what I want, however when I then try to redirect to this link, eg:

header("Location: $link");

The actual URI I end up with has the $query_string, appended to it multiple times, like so:

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,

As you can see, "&product_options" appears multiple times, followed by the list of integers!

Can the header() function be used this way? or am I doing something horribly wrong!

Upvotes: 2

Views: 308

Answers (1)

anwerj
anwerj

Reputation: 2488

This is because of multiple redirect each time you load the page, php will append product_options rather than replacing it.

<?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");

Upvotes: 1

Related Questions