PHP: Sanitize User Input Using Filters & Regex

In this article I share my recent experience implementing the sanitization of user input in a PHP web application using PHP filters and regular expressions.

In this article I share my recent experience implementing the sanitization of user input in a PHP web application using PHP filters and regular expressions.

For background, I was recently troubleshooting a production PHP application and needed to create a form that takes in an ID parameter from the URL and uses it to retrieve a specific record from a table then sends an email using that data.

To keep this as simple as possible, the example below shows how to sanitize user input by not allowing a value based on a PHP filter rule using a regular expression. You’ll need to get comfortable with a little dependency injection as that is how we get our filter options in to PHP at runtime.

If you want to validate that an ID value passed through the URL is exactly two digits, you can use the filter_input() function with a custom regular expression through the FILTER_VALIDATE_REGEXP filter. This approach allows you to specify a pattern that the input must match to be considered valid.

For an ID that consists of exactly two digits (i.e., from 00 to 99), you can use the following code snippet:

$options = array(
    "options" => array(
        // Regular expression for exactly two digits
        "regexp" => "/^\d{2}$/"
    )
);

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_REGEXP, $options);

if ($id !== false) {
    echo "The ID '$id' is valid.";
} else {
    echo "The ID is not valid. Please provide a two-digit ID.";
}

Here’s a breakdown of how this works:

  • INPUT_GET specifies that the input is expected to come from the query parameters in the URL.
  • 'id' is the name of the parameter you’re trying to validate.
  • FILTER_VALIDATE_REGEXP is the filter used for validating against a regular expression.
  • $options is an associative array that specifies the options for the filter. In this case, it contains a regular expression defined by the regexp key. The expression /^\d{2}$/ ensures that the input consists of exactly two digits:
    • ^ asserts the start of the string.
    • \d{2} matches exactly two digits (\d is a digit, and {2} specifies exactly two occurrences).
    • $ asserts the end of the string.

This code validates that the user input is exactly two digits. If the input meets the criteria, it is considered valid; otherwise, the script returns an error message indicating the input is not valid. This is a straightforward way to enforce specific formats for input values in PHP.

Lastly, the example above focuses on getting a parameter from the URL using the GET HTTP method. If you’re using a form, replace INPUT_GET with INPUT_POST.

I hope this example helps you secure your PHP applications.

~Cyber Abyss

PowerShell: Copy Folder from Server to Server Using UNC Path

Below is a simple PowerShell script example that copies a folder from one server to another using a UNC (Universal Naming Convention) path. This script uses the Copy-Item cmdlet to copy the folder and its contents. Ensure you have the necessary permissions to access both the source and destination paths.

Before you run the script, replace \\SourceServer\SharedFolder with the UNC path of the source folder you want to copy and \\DestinationServer\DestinationFolder with the UNC path of the destination where you want the folder to be copied.

powershellCopy code# PowerShell script to copy a folder from one server to another using UNC paths

# Define the source and destination UNC paths
$sourcePath = "\\SourceServer\SharedFolder"
$destinationPath = "\\DestinationServer\DestinationFolder"

# Check if the source folder exists
if (Test-Path -Path $sourcePath) {
    # Copy the folder from source to destination, including all subfolders and files
    Copy-Item -Path $sourcePath -Destination $destinationPath -Recurse -Force
    Write-Host "Folder copied successfully from $sourcePath to $destinationPath."
} else {
    Write-Host "Source folder does not exist: $sourcePath"
}

This script copies all contents from the source folder to the destination, including subfolders and files. The -Recurse parameter is used to ensure that all subdirectories and files are copied, and -Force is used to overwrite files in the destination if they already exist.

Important considerations:

  • Permissions: Make sure the account running the script has read access to the source path and write access to the destination path.
  • Network Latency and Bandwidth: Copying large folders over a network can be time-consuming and may impact network performance. Consider running such operations during off-peak hours.
  • Error Handling: The above script is basic and does not include detailed error handling. You may want to add try-catch blocks or additional checks to handle potential errors more gracefully.

Always test scripts in a safe environment before using them in production to ensure they work as expected and do not cause unintended effects.