PHP에서 내 웹 사이트의 모든 쿠키를 삭제하는 방법
사용자가 로그 아웃을 클릭 할 때 내 웹 사이트의 모든 쿠키를 삭제할 수 있는지 궁금합니다.이 기능을 사용하여 쿠키를 삭제했지만 제대로 작동하지 않기 때문입니다.
setcookie("user",false);
PHP에서 한 도메인의 쿠키를 삭제하는 방법이 있습니까?
해당 페이지에서 가져 오면 도메인에 대한 모든 쿠키가 설정 해제됩니다.
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
http://www.php.net/manual/en/function.setcookie.php#73484
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past, '/' );
}
그러나 더 좋은 방법은 도메인에서 응용 프로그램과 함께 설정된 쿠키를 기억 (또는 어딘가에 저장)하고 모든 쿠키를 직접 삭제하는 것입니다.
이렇게하면 모든 값을 올바르게 삭제할 수 있습니다.
위 답변 중 일부에 동의합니다. "time ()-1000"을 "1"로 바꾸는 것이 좋습니다. 값 "1"은 1970 년 1 월 1 일을 의미하며 100 % 만기를 보장합니다. 따라서:
setcookie($name, '', 1);
setcookie($name, '', 1, '/');
사이트에서 출력이 발생하기 전에 setcookie 함수를 호출해야합니다.
또한 사용자가 로그 아웃하는 경우 세션 변수도 삭제 / 무효화해야합니다.
쿠키의 이름을 변경할 때 모든 쿠키를 삭제하고 하나는 보존 할 수도 있습니다.
if (isset($_COOKIE)) {
foreach($_COOKIE as $name => $value) {
if ($name != "preservecookie") // Name of the cookie you want to preserve
{
setcookie($name, '', 1); // Better use 1 to avoid time problems, like timezones
setcookie($name, '', 1, '/');
}
}
}
또한이 PHP-Answer를 기반으로
이 질문이 오래되었다는 것을 알고 있지만 이것은 훨씬 더 쉬운 대안입니다.
header_remove();
하지만 조심하세요! 문서에 설명 된대로 쿠키, 세션 등을 포함한 모든 헤더를 지 웁니다 .
제공된 답변으로 문제가 해결되지 않았습니다.
그렇지 않았습니다.
- 부모 도메인 쿠키 제거 (abc에서, bc 제거, 쿠키),
- 루트가 아닌 상위 경로에서 쿠키를 제거하십시오.
내 스크립트는 그렇습니다.
<?php function unset_cookie($name)
{
$host = $_SERVER['HTTP_HOST'];
$domain = explode(':', $host)[0];
$uri = $_SERVER['REQUEST_URI'];
$uri = rtrim(explode('?', $uri)[0], '/');
if ($uri && !filter_var('file://' . $uri, FILTER_VALIDATE_URL)) {
throw new Exception('invalid uri: ' . $uri);
}
$parts = explode('/', $uri);
$cookiePath = '';
foreach ($parts as $part) {
$cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//');
setcookie($name, '', 1, $cookiePath);
$_domain = $domain;
do {
setcookie($name, '', 1, $cookiePath, $_domain);
} while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.')));
}
}
It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain's. Or use the idea in order to create your version.
You should be aware of various tracking tools like Google Analytics also use cookies on your domain and you don't want to delete them, if you want to have correct data in GA.
The only solution I could get working was to set the existing cookies to null. I couldn't delete the cookies from the client.
So for logging a user out I use the following:
setcookie("username", null, time()+$this->seconds, "/", $this->domain, 0);
setcookie("password", null, time()+$this->seconds, "/", $this->domain, 0);
Of course this doesn't delete ALL cookies.
All previous answers have overlooked that the setcookie
could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com
domain, there might be a cookie set on tar.com
. Therefore, you want to unset cookies for all domains that might have dropped the cookie:
$host = explode('.', $_SERVER['HTTP_HOST']);
while ($host) {
$domain = '.' . implode('.', $host);
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1, '/', $domain);
}
array_shift($host);
}
Use the function to clear cookies:
function clearCookies($clearSession = false)
{
$past = time() - 3600;
if ($clearSession === false)
$sessionId = session_id();
foreach ($_COOKIE as $key => $value)
{
if ($clearSession !== false || $value !== $sessionId)
setcookie($key, $value, $past, '/');
}
}
If you pass true
then it clears session
data, otherwise session data is preserved.
<?php
parse_str(http_build_query($_COOKIE),$arr);
foreach ($arr as $k=>$v) {
setCookie("$k","",1000,"/");
}
참고URL : https://stackoverflow.com/questions/2310558/how-to-delete-all-cookies-of-my-website-in-php
'Programing' 카테고리의 다른 글
메타 프로그래밍을위한 Python 대 Ruby (0) | 2020.09.07 |
---|---|
편집기에 기본 유형이 없습니다. (0) | 2020.09.07 |
왜“우리”와“자신”의 의미가 git-svn으로 바뀌 었습니까? (0) | 2020.09.07 |
예외에서 전체 스택 추적을 인쇄하는 방법은 무엇입니까? (0) | 2020.09.07 |
명령 줄에서 mysql 데이터베이스를 일반 텍스트 (CSV) 백업으로 덤프 (0) | 2020.09.07 |