使用 PHP 获取原始 URL 引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1864583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get original URL referer with PHP?
提问by Keith Donegan
I am using $_SERVER['HTTP_REFERER'];to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page.
我正在使用$_SERVER['HTTP_REFERER'];获取引荐网址。它按预期工作,直到用户单击另一个页面并且引用者更改为最后一个页面。
How do I store the original referring Url?
如何存储原始引用 URL?
回答by Sampson
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
将其存储在 cookie(如果它适合您的情况)或会话变量中。
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
回答by Tyler Carter
As Johnathan Suggested, you would either want to save it in a cookie or a session.
正如 Johnathan 建议的那样,您可能希望将其保存在 cookie 或会话中。
The easier way would be to use a Session variable.
更简单的方法是使用 Session 变量。
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
将其放在页面顶部,您将始终能够访问网站访问者所指向的第一个引用者。
回答by Kainax
Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.
在大多数情况下,使用 Cookie 作为参考页面的存储库要好得多,因为 cookie 会保留引用直到浏览器关闭(即使浏览器选项卡关闭也会保留它),所以如果用户将页面保持打开状态,让我们说在周末之前,几天后返回它,您的会话可能会过期,但 cookie 仍然会存在。
Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):
将该代码放在页面的开头(在任何 html 输出之前,因为 cookie 只会在任何回显/打印之前正确设置):
if(!isset($_COOKIE['origin_ref']))
{
setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}
Then you can access it later:
然后您可以稍后访问它:
$var = $_COOKIE['origin_ref'];
And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.
除了@pcp 建议的转义 $_SERVER['HTTP_REFERER'] 之外,在使用 cookie 时,您可能还想在每个请求中转义 $_COOKIE['origin_ref']。
回答by Matt
Store it in a cookie that only lasts for the current browsing session
将其存储在仅持续当前浏览会话的 cookie 中
回答by user11688571
try this
尝试这个
(isset ($_SERVER['HTTP_CLIENT_IP']) ?
$_SERVER['HTTP_CLIENT_IP'] :
(isset ($_SERVER['HTTP_X_FORWARDED_FOR']) ?
$_SERVER['HTTP_X_FORWARDED_FOR'] :
$_SERVER['REMOTE_ADDR']
)
)

