Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Filter in PHP

Filter in PHP

? Filters in PHP

PHP has a built-in filter extension that provides a simple and powerful way to validate and sanitize external input (like from forms, URLs, and cookies). This helps prevent security vulnerabilities such as XSS and SQL injection.


? Why Use Filters?

? Clean data before saving to DB
? Validate email, IP, integers, URLs
? Remove unwanted characters
? Prevent malicious input


? 1. Sanitizing Data

Used to clean input by removing undesired characters.

$name = "<h1>John</h1>";$clean = filter_var($name, FILTER_SANITIZE_STRING); // Old PHP versions$clean = strip_tags($name); // Newer preferred methodecho $clean; // Output: John

Common Sanitizers:

FilterPurpose
FILTER_SANITIZE_STRINGRemoves tags (deprecated)
FILTER_SANITIZE_EMAILRemoves illegal characters from email
FILTER_SANITIZE_URLRemoves illegal characters from URL
FILTER_SANITIZE_NUMBER_INTKeeps digits and +/-

? 2. Validating Data

Checks if data is in a valid format (returns true or false).

$email = "test@example.com";if (filter_var($email, FILTER_VALIDATE_EMAIL)) {    echo "Valid email";} else {    echo "Invalid email";}

Common Validators:

FilterDescription
FILTER_VALIDATE_INTValidates integer
FILTER_VALIDATE_FLOATValidates float
FILTER_VALIDATE_EMAILValidates email
FILTER_VALIDATE_URLValidates URL
FILTER_VALIDATE_IPValidates IP address
FILTER_VALIDATE_BOOLEANValidates true/false

? 3. With Options

$age = "25";if (filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 30]])) {    echo "Age is valid.";} else {    echo "Age is not in range.";}

? 4. filter_input() Example

// Validating input from a GET form$number = filter_input(INPUT_GET, "num", FILTER_VALIDATE_INT);if ($number !== false) {    echo "Valid number: $number";} else {    echo "Invalid input.";}

? Best Practices

  • Use filters to clean all user inputs.

  • Validate before saving or processing.

  • Combine sanitization + validation where necessary.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql