25. HTML Forms: Methods, Enctype and How They Work
<form>, action, GET vs POST, enctype='multipart/form-data'
Real-life analogy
Think of a post office envelope: GET is a transparent postcard whose message everyone can see, while POST is a sealed envelope that stays safely confidential.
Explanation
How the <form> tag works for collecting data from a user (login, signup, payment):
action="server.php": Which server file the data will go to be processed when the form is submitted.method="GET": Sends the data by appending it to the browser's URL (for example?name=rahul&age=20). This is fine for a search bar, but completely unsafe for passwords!method="POST": Sends the data hidden inside the HTTP body, safely. Only POST is used for passwords and large forms.enctype="multipart/form-data": Extremely important! When the form has to let the user upload a photo, PDF or file, adding this attribute is 100% mandatory.
Golden rules
- Always use
method="POST"for sending passwords and sensitive data. - Always add
enctype="multipart/form-data"to a form with file uploads.
Common mistake
Using the GET method in a form with a password, which makes the user's password visible to everyone in the browser history and URL.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px; background: #f8fafc;">
<form action="/save" method="POST" enctype="multipart/form-data" style="max-width: 300px; background: white; padding: 15px; border-radius: 8px; border: 1px solid #cbd5e1;">
<h4 style="margin-top: 0;">Secure Form (POST)</h4>
<label style="font-size: 12px; font-weight: bold;">Password:</label><br>
<input type="password" required style="width: 100%; padding: 6px; margin: 4px 0 8px 0; border: 1px solid #cbd5e1; border-radius: 4px; box-sizing: border-box;"><br>
<label style="font-size: 12px; font-weight: bold;">File upload:</label><br>
<input type="file" style="font-size: 12px; margin: 4px 0 10px 0;"><br>
<button type="submit" style="background: #059669; color: white; border: none; padding: 8px 14px; border-radius: 4px; font-weight: bold; cursor: pointer;">Submit</button>
</form>
</body>
</html>
Quick quiz
When a file or image has to be uploaded through a form, which enctype must be set on the form?
- text/plain
- multipart/form-data
- application/json
- file/upload
Show answer
Answer: multipart/form-data
For file upload, setting enctype='multipart/form-data' is mandatory.