开发者

Recommended method to pass variables in HTML/PHP?

Hi I just have a simple question: What is the开发者_JS百科 recommended way to pass variables when working on your site. - get, post, session, cookies, hidden fields, ...


  • GET when showing data
  • POST when modifying data
  • session when storing data between requests that doesn't need to stay after the session expires
  • database (or other persistent storage) for data that needs to hang around between sessions

Cookies; more or less never. Anything that you would put there could almost always be better stored in the session. Perhaps for persistent logins, only.

Hidden fields; again, almost never, use a session and keep the data safe on the server. Sometimes used as storage points for data collected via javascript, but that's it.


I prefer Sessions. It is the only option you mention above that is server side.

If you want to transfer information from your client to your server you could use either POST or GET. Remember that a hidden field in the end will become a post of get variable.

Get, Post, Cookies and hidden fields can all be manipulated relatively simple. Which option you choose, make sure you always check your variables to be valid. User input values can never be trusted!


All of those things have different, sometimes overlapping uses. Choosing one and using only that in the development of a complete application would lead to ridiculously bad mis-usage. You need a more specific question.


I usually stick to some simple rules:

GET - for getting information.

For example:

  • site.com/articles/category/2 or site.com/articles.php?category=2 shows me all articles for second category

  • site.com/search/mike or site.com/search.php?q=mike searches for mike on site

POST - for updating or inserting data

Hidden fields used in POST/GET forms for various reasons, often for IDs or something like this

Session - for data for one session. Storing some user preferences, user data.

Cookies - for "remember me" functionality and some JS stuff (because JS can't reach Session data)

P.S. There are also PUT and DELETE methods, but some shared hosters don't allow them...


Depends on the site and when you need to pass the data.

If its on page load a cookie, if you have sessions a session, if your submitting a form (which is HTTP POST or GET), if submitting and you dont want the user to see use a hidden field with a form (which is HTTP POST or GET), via the URL (GET) and lastly if its a AJAX eg web app you have several options and methods open to use (HTTP GET, PUT, POST and DELETE - see RESTful APIS for a good example).

Note with all HTTP GET, PUT, POST and DELETE methods you can still use cookies and sessions as well


Session is the most appropriate way to pass spacific values. But if you want to send number of variables in a single time then post is the best method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜