
Are You New Here? than get More Blogging Tips Subscribe to this blog today!
Hi, Friends! In this I am going to explain you How to Set Cookies in PHP? First of all Cookies are small pieces of text, stored by a user’s web browser, that contain the user’s settings, shopping cart contents, or other data used by websites.
In PHP we can set cookies by inbuilt function setcookie().
It is very easy to use and understand. First parameter is the name of the cookie and second one is the value you want to store in cookie.
By above code you can set simple cookie and this cookie will be deleted when user close their browser.
We can also set the time how long we want the cookie.
Above example create cookie for 1 year. Yes 31536000 seconds means 1 year.Remember, cookies must be deleted with the same parameters they were set with.If users clear their history from browser then cookies will be deleted.
We can also use a forth parameter, the fourth parameter is the cookie path.
The fourth parameter defines a path from which the cookie can be accessed. In the above example only scripts inside /folder/ will be able to access the cookie ($username), in scripts outside this folder the cookie will be unavailable.
There’s also a fifth parameter, the fifth parameter defines a hostname that can retrieve the cookie.
The fifth parameter is the domain which can retrieve this cookie. Normally a cookie can only be accessed by the domain that set it, otherwise sites would be able to get private information from cookies set by other sites. With this parameter we can define another domain which can retrieve the cookie we are setting.
Click on below links for more:
Now How to Retrive Cookie ?
Once you have set a cookie on a user’s system, it is only avialable when they load the next page. The cookie can be accessed very easily:
When the cookie is set the value is automatically URL encoded, when the script retrieves a cookie, it automatically decodes the value, so you don’t have to worry about that.
Always remember, a limitation of cookies is that you have to set it before you can send the HTTP headers. In other words, always do all your cookie setting BEFORE you output any HTML, otherwise the cookie will not be set and your page will have an ugly error stuck on it.
Also Read: 45+ Greatest Adobe Photoshop Keyboard Shortcuts & 5 Useful Code Snippets for Web Developers
If you have any suggestions and question than feel free to ask me i will response you.
Related posts:
If you would like to make a comment, please fill out the form below.
Recent Comments