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

  1. filter_var() Function:

    • FILTER_VALIDATE_EMAIL → Checks valid email format

    • FILTER_VALIDATE_URL → Checks valid URL format

  2. Empty vs Optional Fields:

    • Email is usually required → use empty()

    • Website can be optional → only validate if not empty

  3. Sanitization Before Validation:
    Always use trim(), 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *