클릭 및 방문자 체크 할때 사용하는 쿠키관리
중복된 처리를 제외하고자 할때 일정 부분 쿠키로 가지고 있다가 비교해서 동일한 것은 처리 하지 않기 위한것입니다.
이것을 쿠키를 이용하는 방법이 있고 요즘은 로컬스토리지를 이용하는 방법도 있겠습니다.
특정 게시물의 번호나.
방문자의 로그를 저장하여 처리 하는 경우는 중복 처리 방지를 위한 간단한 방식 입니다.
게시물의 경우 중복제외 처리를 하지 않으면 들쑥 날쑥 하지만 최고 30% 넘게 차이나는 경우도 있었습니다.
<!DOCTYPE html>
<html>
<head>
<title>Click Event Test</title>
</head>
<body>
<button onclick="clickHandler(2)">Click Me! 2 </button> <br> <br>
<button onclick="clickHandler(12)">Click Me! 12 </button> <br> <br>
<button onclick="clickHandler(22)">Click Me! 22 </button>
<button onclick="clickHandler(35)">Click Me! 35 </button> <br> <br>
<button onclick="clickHandler(62)">Click Me! 62 </button>
<button onclick="clickHandler(62)">Click Me! 62 </button> <br> <br>
<script>
// 쿠키 가져오기
function getCookie(cookieName) {
const cookieValue = `; ${document.cookie}`;
const aParts = cookieValue.split(`; ${cookieName}=`);
if (aParts.length === 2) return aParts.pop().split(';').shift();
return '';
}
// 쿠키 설정
function setCookie(cookieName, cookieValue, days) {
let oDate = new Date();
oDate.setTime(oDate.getTime() + (days*24*60*60*1000));
const oExpires = "expires="+ oDate.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + oExpires + ";path=/";
}
// 클릭 이벤트 핸들러
function clickHandler(cookieValue) {
let aValues = getCookie('clickNumbers') ? getCookie('clickNumbers').split(',') : [];
// if (!aValues.includes(String(cookieValue)) && aValues.length < 8 ) {
// aValues.push(cookieValue);
// setCookie('clickNumbers', aValues.join(','), 1);
// }
if (!aValues.includes(String(cookieValue))) {
// 배열의 길이가 이미 8이면, 가장 오래된 (첫 번째) 요소를 제거
// 배열의 첫 번째 요소를 제거
if (aValues.length >= 8) {
aValues.shift();
}
// 새로운 클릭 번호를 배열 끝에 추가
aValues.push(cookieValue);
setCookie('clickNumbers', aValues.join(','), 1);
}
saveClick(cookieValue); // 클릭 번호 서버로 전송
}
// 서버로 클릭 번호 전송
function saveClick(number) {
console.log(number);
// // GET 방식으로 변경된 부분 - 주석을 풀면 이 부분도 잘 작동한다.
// fetch(`<?=$_SERVER["PHP_SELF"]?>?c=1&number=${number}`, {
// method: 'GET'
// })
// .then(response => response.json())
// .then(data => {
// console.log('Success:', data);
// })
// .catch((error) => {
// console.error('Error:', error);
// });
var oData = {'number': number};
// console.log(oData);
// console.log(document.cookie);
console.log(getCookie('clickNumbers'));
fetch('<?=$_SERVER["PHP_SELF"]?>?c=1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: Object.keys(oData).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(oData[key])).join('&')
})
// .then(response => response.text())
// .then(response => console.log("Server response:", response))
// .catch(error => console.log('Error:', error));
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
</body>
</html>
아래는 백엔드에서 처리해서 돌려주는 부분입니다.
그리고 쿠키 부분은 클라이언트가 아니라 백엔드에서도 동일한 방법으로 체크가 필요한 경우 이렇게 하면 됩니다.
<?php
ini_set("display_errors", 1);
$_COOKIE['clickNumbers'] = '1,2,3,4,5,6,7,8,9';
// echo '111111<pre>' . print_r($_COOKIE, true) . '</pre>';
// exit;
function clickHandler($cookieValue) {
echo $cookieValue . "<br>" . PHP_EOL;
// echo '<pre>' . print_r($_COOKIE, true) . '</pre>';
$aValues = array();
if (isset($_COOKIE['clickNumbers'])) {
$aValues = explode(',', $_COOKIE['clickNumbers']);
}
// echo '<pre>' . print_r($aValues, true) . '</pre>';
if (!in_array($cookieValue, $aValues)) {
// 배열의 길이가 8 이상이면, 가장 오래된 (첫 번째) 요소 제거
if (count($aValues) >= 8) {
array_shift($aValues);
}
// 새로운 클릭 번호를 배열 끝에 추가
array_push($aValues, $cookieValue);
// setCookie('clickNumbers', implode(',', $aValues), 1);
echo '<pre>' . print_r($aValues, true) . '</pre>';
}
}
$cookieValue = 15;
clickHandler($cookieValue);
exit;
if ( $_GET['c'] == 1 ) {
$aTest = array();
$aTest['asdf'] = 12;
echo json_encode($aTest, JSON_UNESCAPED_UNICODE);
exit;
}
?>
아래는 로컬 스토리지 이용하는 방법으로 확인은 안해본것인데 아래처럼 하면 된다고 합니다.
<script>
// 클릭 이벤트 핸들러
function clickHandler(cookieValue) {
let aValues = localStorage.getItem('clickNumbers') ? localStorage.getItem('clickNumbers').split(',') : [];
if (!aValues.includes(String(cookieValue))) {
if (aValues.length >= 8) {
aValues.shift();
}
aValues.push(cookieValue);
localStorage.setItem('clickNumbers', aValues.join(','));
}
saveClick(cookieValue); // 클릭 번호 서버로 전송
}
// 서버로 클릭 번호 전송
function saveClick(number) {
console.log(number);
var oData = {'number': number};
console.log(localStorage.getItem('clickNumbers'));
fetch('<?=$_SERVER["PHP_SELF"]?>?c=1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: Object.keys(oData).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(oData[key])).join('&')
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>