Current Location: Home> Latest Articles> PHP Function Security Enhancement Guide: Protecting Against SQL Injection and XSS

PHP Function Security Enhancement Guide: Protecting Against SQL Injection and XSS

M66 2025-10-20

PHP Function Security Improvement Directions

In PHP development, ensuring the security of functions is crucial. This article introduces key improvement measures to help developers write safer and more reliable PHP code.

Use Type Hints

Type hints ensure that the parameters passed to functions are of the correct type, preventing errors from unexpected data types and reducing potential security risks.

function add($a, $b): int
{
    return $a + $b;
}

// This will trigger a TypeError
add('1', 2);

Prevent SQL Injection

SQL injection is a common security issue, where attackers can inject malicious SQL statements to access sensitive data. Using parameterized queries effectively prevents SQL injection.

$statement = $conn->prepare("SELECT * FROM users WHERE username = ?");
$statement->bind_param("s", $username);

Prevent Cross-Site Scripting (XSS)

XSS attacks inject malicious scripts into webpages. Using HTML encoding safely outputs user data and prevents scripts from being executed.

function echoHtml($html)
{
    echo htmlspecialchars($html);
}

Validate User Input

User input may contain malicious code or other attack vectors. It should always be validated before use to prevent illegal data from entering the system.

if (!preg_match('/^[a-zA-Z0-9]+$/', $input)) {
    throw new InvalidArgumentException();
}

Use Security Libraries

PHP offers several security libraries, such as PasswordHash and Crypto, to securely generate hashes, encrypt, and decrypt sensitive data.

$hash = password_hash($password, PASSWORD_DEFAULT);

Practical Example: Enhancing Function Security

Consider a function that processes user input to generate SQL statements:

function generateSql($id)
{
    return "SELECT * FROM users WHERE id = $id";
}

To improve security, the following adjustments can be made:

  • Use type hints to ensure $id is an integer
  • Use parameterized queries to prevent SQL injection
function generateSql($id): string
{
    $statement = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $statement->bind_param("i", $id);
    
    return $statement;
}

By implementing these measures, the security of PHP functions can be significantly enhanced, reducing the risk of attacks on the application.