Cookies security

How secure is cookies?

I am building a website where there a few data options that are based on the cookie value e.g

SELECT * FROM users WHERE id = $_COOKIE[‘id’]
INSERT INTO users VALUES ‘text’ WHERE id = $_COOKIE[‘id’]

is it possible for a user to manipulate the cookies so they can view/insert data as another user?

I don’t know where to start to explain the security holes you open up with that 2 lines of code.

To answer your question: Yes, cookies can be manipulated, because it’s stored on the user’s computer.
A hacker can easily change the cookie and even delete your whole database if you don’t escape whatever value you’re expecting from the cookie.

Whatever user input (cookies, textbox, forms, etc.) should/must be validated.
Read up on this:

strip_tags() removes HTML / PHP / Javascript tags from your input. If you don’t need it you should escape it, if you do then use a library such as HTML Purifier

Then, you should validate the data against what you’re expecting.
For example: If you’re expecting an integer then allow only integers.

Hello thank you for your response. I presume script_tags() prevents SQL Injection. How can I make cookies more secure? Should I use sessions instead?

Like feketegy said, all user inputs (including cookie data), regardless of source, must be validated on the server before inserting them into any database queries. Whether you use sessions or not is irrelevent. Probably the quickest and easiest method to sanitise user input data is to use php’s mysql_real_escape_string(). A better option is to use prepared statements.

What I would recommend you first do at the top of your server side script is validate all user inputs by using a regular expression and/or a white list of characters to validate a user input against. eg…if a valid field value is not meant to have a ; or " or ’ or <> or whatever, then reject the input if it contains any of those characters before you do anything else with it.

fyi: this is a popular reference to sql injection and how damaging it can be.

To make cookies more secure try to encrypt it.
I’m guessing you need cookies for session / maintaining state between requests. For this you can use sessions and store these sessions in a database. This way you now have to store the session id only in cookies, all other sensitive info will be stored in the database which is somewhat more secure.

Extending off what feketegy said in his last post:

The method i have been trying out is creating a randomly generated hash() that corresponds to a user in the database, every 30 days this hash will be forced to change for all users regardless whether they have been active within those past 30 days.