PHP Forms Validate E-mail and URL
📧 PHP Forms – Validate E-mail and URL
Validating email addresses and URLs is essential to ensure users provide properly formatted and safe data. PHP provides built-in functions and filters to handle this efficiently.
1️⃣ HTML Form Example
2️⃣ PHP Script to Validate Email and URL
3️⃣ Display Validated Data
4️⃣ Key Points
-
filter_var()Function:-
FILTER_VALIDATE_EMAIL→ Checks valid email format -
FILTER_VALIDATE_URL→ Checks valid URL format
-
-
Empty vs Optional Fields:
-
Email is usually required → use
empty() -
Website can be optional → only validate if not empty
-
-
Sanitization Before Validation:
Always usetrim(),stripslashes(),htmlspecialchars()to clean input.
5️⃣ Example Input & Output
| Input Email | Input Website | Output |
|---|---|---|
| test@example.com | https://example.com | Valid |
| invalid-email | example | Invalid email & URL |
| blank | https://site.com | Email required |
| user@mail.com | Valid (website optional) |
🏁 Summary
-
Use
filter_var()for validating email and URL. -
Always sanitize input before validating.
-
Optional fields should only be validated if filled.
-
Always combine HTML form validation (optional) with server-side PHP validation.
