php cookie安全javascript

I am using html and javascript for client, php for server. Each user, after signing up, will have a userID generated by server, and stored in database. In server I am using setcookie so that user don't have to log in every time he goes to another page.

  1. My first question is, should I just store the userID in the user's cookie for validation? How secure is that?

  2. My second question is how do I check for cookie every time a user open a page. Do I make a 'invisible' ajax call (sending its cookie by using getCookie("userID") in javascript) to server every time user open a page?

Ever since I finished school, I never know if I am doing things the right way, or if my codes are crap. How do you guys determine if your code is the 'right' way to do it, or is it just base purely on experience?

  1. No, it would not be secure at all - cookies can be set and modified by the user.
  2. If you're using PHP (I think you are as there's a tag "PHP"), you should use SESSIONS.

Check the documentation: http://www.php.net/manual/en/book.session.php

Quick example:

<?php
session_start();
var_dump($_SESSION['user_id']);
$_SESSION['user_id'] = 123;

On first request it would print something like null, on other request - 123. It works by generating random value and setting to cookie, that is not easy to guess, then stores all session data to files or other storage by that generated key.