2012-02-01 156 views
5

作爲Adding Values to a Query String in a URL的延續,我有一個搜索框,將添加額外的參數到當前的URL。通過表單提交當前URL

http://example.com/?s=original+new+arguments&fq=category 

形式的代碼如下所示:

<form id="FilterSearch" method="get" action="http://example.com/search_result.php"> 

哪裏search_result.php就是我創建解析提交,並使用新的URL重定向了新的一頁。

如何將原始URL傳遞給search_result.php以便我可以操縱URL?

編輯#1:我添加了一個隱藏輸入:

<?php $current_url = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; ?> 
<input type="hidden" name="current_url" value="<?php $current_url; ?>" /> 
<input name="send" id="send" type="submit" value="Search" /> 

我的輸出僅添加參數提交頁面(search_result.php),而不是預期的查詢頁面。

<?php 
if (isset($_GET['send'])){ 
       $searchField = urlencode($_GET['SearchField']); 
       $location = $_GET['current_url']; 
       $location = preg_replace($location, '/([?&]s=)([^&]+)/', '$1$2+'.$searchField); 
       header('Location: '.$location); 
       } 
?> 

我要麼通過他們錯誤或讓他們錯了或兩個!

編輯#2:輸出URL是這樣的:

http://example.com/wp-content/themes/child_theme/search_result.php?SearchField=newTerm&current_url=www.example.com%2F%3Fs%3DoldTerm%26searchsubmit%3D&send=Search 

編輯#3 我附和輸出URL,它是正確的。我擺脫了preg_match,看看我是否可以在處理表單時獲得相同的URL。有趣的是,我找不到一個頁面。我決定增加HTTP://頭和它的工作:

header('Location: http://'.$location); 

因此,因此,我認爲,錯在這裏的唯一事情是preg_replace函數。

+0

它看起來像你需要做value =「<?php echo $ current_url;?>」。你也可以使用$ _SERVER ['HTTP_REFERER']像dfsq建議的那樣替代這種方法,但它並不總是可靠的。 – 2012-02-01 19:53:33

+0

既沒有工作:/ – AlxVallejo 2012-02-01 20:01:40

+0

你是否在你的$ location變量中獲得任何值? – 2012-02-01 20:04:47

回答

8

我認爲你正在尋找隱藏的輸入。

事情是這樣的:

<input type="hidden" name="current_url" value="(Current URL here)" /> 

然後訪問它,就像使用任何其他$ _GET或$ _POST參數。


編輯迴應編輯:

莫非你echo $location; die;此行之後:

$location = $_GET['current_url']; 

,讓我知道的輸出是什麼?這會告訴我們它是否被錯誤地傳遞或處理不正確。

+0

看到我的輸出URL – AlxVallejo 2012-02-02 14:29:04

+0

編輯我的答案進行故障排除。 – 2012-02-02 15:26:56

+0

請參閱編輯#3(我爲所有編輯道歉!) – AlxVallejo 2012-02-02 15:34:07

1

只需在您的search_result.php中使用$_SERVER['HTTP_REFERER']即可。另一種選擇是使用隱藏的輸入,但我會選擇第一個。

+0

我不同意,在某些環境中,引用者可能不穩定。如果使用隱藏輸入的代價很小,請改用該方法。 – 2012-02-01 20:58:53

0

獲得當前URl的更好方法是創建一個隱藏的輸入,並且您傳遞當前URL並在服務器端捕獲。即

<input type="hidden" name="cur_url" value="(your Current URL here)" />