简体   繁体   English

PHP设置cookie重定向

[英]php set cookie redirect

I need a domain example.com redirects to sub-domain a.example.com when I type on the address bar. 当我在地址栏上键入内容时,我需要一个域example.com重定向到子域a.example.com。

<script type="text/javascript">
$(function(){
    var city = readCookie('city');
    if(city==null && city==''){
    window.location.href = 'http://' + city + '.example.com';
}
$('#citygo').change(function(){
    var city = $(this).val();
    createCookie('city', city, 28);
    window.location.href = 'http://' + city + '.example.com';
});
});
</script>

<body>
<select id="citygo">
    <option value="0">Select City</option>
    <option value="amsterdam">Amsterdam</option>
    <option value="newyork">New York</option>
    <option value="london">London</option>
    <option value="cardiff">Cardiff</option>
    </select>
</body>

The cookie on the server side is not holding so the domain cannot remember sub-domain. 服务器端的cookie没有保存,因此域无法记住子域。 What am i doing wrong? 我究竟做错了什么? Any help will be very much appreciated. 任何帮助将不胜感激。

<?php 
$hour = time() + 50400; 
setcookie(My_Site_Location, $_POST['citygo'], $hour); 

$Loc=$_COOKIE["city"]; 
if(isset($_POST['city'])) 
$Loc=$_POST['city']; 

if (empty($Loc)) { 
    header("Location: http://{$_COOKIE["city"]}.example.com");  
    } else { 
    header("Location: example.com/$Loc.php");  
} 
?>

By default setcookie() will use the current host as the domain; 默认情况下, setcookie()将使用当前主机作为域; to override this, you must explicitly specify it: 要覆盖它,必须显式指定它:

setcookie(My_Site_Location, $_POST['citygo'], $hour, '/', 'example.com');

About the domain value, the manual says this: 关于域值,该手册说:

Older browsers still implementing the deprecated RFC 2109 may require a leading . 仍在实施不推荐使用的RFC 2109的较旧的浏览器可能需要加引号 . to match all subdomains. 匹配所有子域。

I have faced same issue but i solved my problem using the below code in PHP You are not setting the path and expiration on the cookie. 我遇到了同样的问题,但是我使用PHP中的以下代码解决了我的问题,您没有在cookie上设置路径和到期时间。 If you have subdirectories it is normally good to set a master cookie that is the root path '/'. 如果您有子目录,通常最好将主cookie设置为根路径“ /”。

To read your cookie using PHP, try this... 要使用PHP读取Cookie,请尝试以下操作...

$cookies = explode(';', $_SERVER['HTTP_COOKIE']);

...and search the array for your "city" cookie. ...并在数组中搜索您的“城市” Cookie。 Further docs on setting and reading cookies using entirely PHP, check here. 有关使用完全PHP设置和读取Cookie的更多文档,请点击此处。

You must call this function before any other code is echoed to the page. 您必须先调用此函数,然后才能在页面上回显任何其他代码。 (before headers) (在标题之前)

This will help you 这对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM