Search code examples
phphtmlformsvalidationsecurity

When making a form, what's the difference between required in html and checking it later in php?


I'm new to web development and I don't know whether it's better to check that user filled out all the fields in a form by using "required" or to check it later using php with empty() and then return user to the front page. What are the upsides and downsides of each method?

I tried both of them and the only difference I could think of is the "Please fill out this field" box when using the html way.


Solution

  • The bottom line here is that your server-side code cannot cannot trust anything it receives from the client-side.

    A web application receiving a HTTP request has no way of knowing whether that request came through a user-interface where some validation was applied to the data before sending, or if someone modified that user interface to remove some checks (which is easy in a browser if you have a little knowledge of the Developer Tools), or if (for example) it came from some sort of bot firing requests directly at your server, or if someone simply opened up PostMan and made the HTTP request by hand.

    Therefore, in terms of security and validation, you must implement server-side validation and security procedures if you want to ensure the security and validity of your application and its data.

    Client-side validation is great for improving the user experience and performance of your application (so that the user doesn't have to wait for a round-trip to the server before they get feedback on the validity of data they are trying to submit), but since it easily can be bypassed or disabled you cannot rely on that alone to protect your application.