setcookie () 직후 $ _COOKIE 액세스
PHP $_COOKIE
에서 setcookie()
함수를 호출 한 후 즉시 쿠키 값에 액세스하려고합니다 (사용 ) . 그렇게하면 $_COOKIE['uname']
설정되지 않습니다. 왜?
그러나 $_COOKIE['uname']
이는 페이지 새로 고침 후와 같이 다음에 스크립트를 실행할 때 예상대로 설정됩니다.
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];
$_COOKIE
웹의 상태 비 저장 특성으로 인해 페이지가로드 될 때 설정됩니다. 즉시 액세스하려면 $_COOKIE['uname']
직접 설정 하거나 중간 변수를 사용할 수 있습니다 .
예를 들면 :
if (isset($_COOKIE['uname'])) {
// get data from cookie for local use
$uname = $_COOKIE['uname'];
}
else {
// set cookie, local $uname already set
setcookie('uname', $uname, time() + 1800);
}
쿠키는 응답이 클라이언트로 다시 전송 될 때까지 설정되지 않으며 이후 클라이언트에서 다음 요청이있을 때까지 PHP에서 사용할 수 없습니다.
그러나 스크립트에 쿠키를 설정하면 다음을 수행 할 수 있습니다.
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
를 호출 한 직후 쿠키 값에 액세스하려면 setcookie()
을 사용할 수 없습니다 $_COOKIE
. 그 이유는 프로토콜의 특성 때문입니다 ( https://tools.ietf.org/html/rfc6265 참조 ). 사용할 때 setcookie()
나머지 HTTP 헤더와 함께 클라이언트에 보낼 쿠키를 정의합니다 ( http://php.net/manual/en/function.setcookie.php 참조 ). 그러나 $_COOKIE
반면 에 클라이언트 ( http://php.net/manual/en/reserved.variables.cookies.php ) 에서 HTTP 쿠키 를 통해 현재 스크립트로 전달 된 변수가 포함되어 있습니다 .
$_COOKIE
전화 후 변경하면 setcookie()
-여기에 일부 답변이 권장되는 것처럼-더 이상 클라이언트의 쿠키 만 포함되지 않습니다. 이로 인해 애플리케이션에 사용 된 제 3 자 코드의 가정을 방해 할 수 있으며 원치 않는 사이트 효과가 발생할 수 있습니다. 따라서 일반적으로 좋은 습관이 아니며 호출이 setcookie()
자체 코드의 일부인 경우에만 옵션 입니다.
setcookie()
동일한 요청 내에서 값을 설정하는 깨끗하고 투명한 방법 은 다음을 사용하는 것입니다 headers_list()
( http://php.net/manual/en/function.headers-list.php 참조 ) .
function getcookie($name) {
$cookies = [];
$headers = headers_list();
// see http://tools.ietf.org/html/rfc6265#section-4.1.1
foreach($headers as $header) {
if (strpos($header, 'Set-Cookie: ') === 0) {
$value = str_replace('&', urlencode('&'), substr($header, 12));
parse_str(current(explode(';', $value, 1)), $pair);
$cookies = array_merge_recursive($cookies, $pair);
}
}
return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');
그러나 이것은 PHP CLI (예 : PHPUnit)에서는 작동하지 않습니다. 이러한 경우 XDebug와 같은 타사 확장을 사용할 수 있습니다 ( http://xdebug.org/docs/all_functions#xdebug_get_headers 참조 ).
즉시 필요한 경우 쿠키 변수를 직접 설정해야합니다. 다른 페이지를로드 할 때 실제 쿠키는 setcookie 메서드의 결과로 설정되었을 것입니다.
setcookie('name', $value, time()+60*30);
$_COOKIE ['name'] = $value;
포함 된 파일의 함수를 사용하고 쿠키 값을 반환하고 쿠키를 설정하는 함수로 해결하는 비슷한 문제가 있습니다.
function setCookie($input) {
setcookie('uname', $input, time() + 60 * 30);
return $input;
}
if(!isset($_COOKIE['uname'])) {
$uname = setCookie($whatever);
} else {
$uname = $_COOKIE['uname'];
}
echo "Cookie value: " . $uname;
사용하기 위한 ob_start () 와 ob_flush 것은 () 는 클라이언트에 쿠키를 전송할 수 있으며, 동일한 런타임에 검색 할 수 있습니다. 이 시도:
ob_start();
setcookie('uname', $uname, time() + 60 * 30);
ob_flush();
echo "Cookie value: " . $_COOKIE['uname'];
setcookie()
웹 브라우저가 처음으로 페이지를 요청할 때 스크립트의 기능이 실행됩니다. 이 쿠키는 사용자 브라우저에 저장되며 다음 요청이있을 때까지 또는 다음 번에 다시로드 할 때까지 서버에서 실행되는 스크립트에서 사용할 수 없습니다.
Upon the next request the browser sends that cookie to the server and the array $_COOKIE
will have the value that you initially set and the browser sent back upon the second request.
I set a constant at the same time the cookie was created
define('CONSTANT', true);
return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');
I can then immediately do something by:
if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)
We can do this using AJAX calling.
If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.
function saveCookie() {
var base_url = $('#base_url').val();
var url = base_url + '/index/cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (data) {
if (data) {
var url = base_url + '/index/get_cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (response) {
var container = $('#show');
if (response) {
container.html(response);
}
}
});
}
}
});
}
<button type="button" onclick="saveCookie()">Save Cookie</button>
<div id="show"></div>
참고URL : https://stackoverflow.com/questions/3230133/accessing-cookie-immediately-after-setcookie
'developer tip' 카테고리의 다른 글
Selenium Webdriver를 사용하여 전체 페이지가 아닌 특정 요소의 스크린 샷을 캡처하는 방법은 무엇입니까? (0) | 2020.11.04 |
---|---|
마크 다운으로 밑줄이 그어진 텍스트 얻기 (0) | 2020.11.03 |
R에서 행렬을 열 벡터 목록으로 변환하는 방법은 무엇입니까? (0) | 2020.11.03 |
디스플레이가있는 div : inline-block margin 0 auto not center (0) | 2020.11.03 |
jQuery 재정의 기본 유효성 검사 오류 메시지 표시 (Css) Popup / Tooltip like (0) | 2020.11.03 |