Updating Unique Views with Cookies

I have a thread.php forum thread file that gets thread thread.php information.

Example:

thread.php?id=781

I am trying to create a unique view setting, but I have no idea if this is really real:

thread.php :

 topicId = <?php echo $_GET['id']; ?>; if ($.cookie("unique"+topicId)!=="1") { $.cookie("unique"+topicId,1,{expires: 1000, path: '/'}); // create cookie if it doesn't exist $.post('unique.php',{id:topicId}); // update thread unique views } 

unique.php

 // connection stuff $id = mysqli_real_escape_string($conn,$_POST['id']); mysqli_query($conn,"UPDATE topics SET unique_views=unique_views+1 WHERE id='$id'"); 

This will create a new cookie for each stream. Therefore, if a user views 100 streams, they will have 100 cookies saved. I worry if creating a new cookie for each stream is too much. Is this good or is there a better way to do this?

+5
source share
2 answers

It’s even possible, it’s a waste of resources. For example, you should serialize your data into a single cookie using JSON.

In Javascript, you can encode an array of topics into a JSON string using JSON.stringify :

 $.cookie("cookie_name", JSON.stringify(topicsId_array)); 

Then you can get the data using JSON.parse :

 var topicsId_array = JSON.parse($.cookie("cookie_name")); 

Remember that you can use the JS push method to add items to the array ( http://www.w3schools.com/jsref/jsref_push.asp ), so you can get the data from the cookie to add a new identifier with a click, and then save it using stringify.

To finish, you have to take care of duplicates. If you do not want to use them when pressing push, you can use https://api.jquery.com/jQuery.unique/ to clear the array or use your own JS function, such as:

 function unique(array_source) { var array_destination = []; var found = false; var x, y; for (x=0; x<array_source.length; x++) { found = false; for (y=0; y<array_destination.length; y++) { if (array_source[x] === array_destination[y]) { found = true; break; } } if (!found) { array_destination.push(array_source[x]); } } return array_destination; } var topicsId_array = ['aaa', 'bbb', 'ccc', 'aaa']; topicsId_array = unique(topicsId_array); 

And in the end, something like this should work:

 var topicsId_array = JSON.parse($.cookie("cookie_name")) topicsId_array.push("your_new_id"); topicsId_array = $.unique(topicsId_array); $.cookie("cookie_name", JSON.stringify(topicsId_array));; 
+3
source

In any case, cookies are part of the HTTP protocol and are sent by cable with each HTTP request, and since the request has a size limit, at some point it will exceed this size and lead to inconsistent browser behavior, regardless of whether you use a lot of small cookies or one large cookie.

I would choose a solution other than a cookie - most likely I will save it on the server side

0
source

All Articles