Securing PHP forms for beginners? Resources?

2020-04-16 18:04发布

问题:

I successfully built my first html/PHP form that passes variables between multiple pages using the _POST global variable and then emails me the results using the mail() function.

I'm sure this form is incredibly insecure as it is now and vulnerable to all matter of exploits and I want to know how to patch up the holes, however I'm pretty much a beginner to PHP.

Can you recommend any simple-to-follow tutorials for securing PHP forms?

回答1:

The first, second and third most important thing you need to do when securing your code is to assume ALL data your code handles is somehow meant to steal your data and sabotage your server. Even data you have personally hard-coded into the scripts! :P

Make sure every piece of data is validated and verified before you use it. Use the intval and floatval functions to verify numbers, regular expressions to verify text fields (usernames, passwords, etc...), and always try to use Parameterized Statements when doing SQL queries.

And keep user input away from includes and shell commands altogether. If you need to do includes and shell commands based on use input, use switch and/or if statements on the actual user input and execute static commands based on them. And if that doesn't work either; validate, verify and sanitize the input extremely thoroughly before using it... then cross your fingers and hope all the good exploiters are looking the other way :)

Most importantly; be very very very paranoid. People ARE out to get you! :)

... then find yourself a relaxing hobby, so you don't go crazy xD



回答2:

I would recommend using PHP Sessions instead of passing variables between forms -- that's one way of securing your input data.

check out this for a start



回答3:

If you are new to forms with php, this site might be interesting for you: myphpform.com
Another site that gives an overview about possible attacks: phpsec.org



回答4:

Some small security tips that helped me with my first PHP apps:

  1. If you receive data on one web page and access it on other pages of the same site, throw them in $_SESSION[]. Never pass them in hidden form fields via POST or GET.
  2. If textual data received from the user is displayed as part of a web page or mailed as a HTML mail, always strip_tags() the data before showing/mailing it (to counter XSS attacks).
  3. All data that is received from the user and then needs to be stored in a SQL database, needs to be escaped to counter SQL injection attacks (i.e. mysql_real_escape_string for mysql or use a DB abstraction).