Current Location: Home> Latest Articles> How to Effectively Prevent bindec() Function from Non-Binary String Injection Attacks in PHP?

How to Effectively Prevent bindec() Function from Non-Binary String Injection Attacks in PHP?

M66 2025-06-23

In PHP development, the bindec() function is used to convert a binary string to a decimal number. Its principle is simple and efficient, but if the parameter passed is not a pure binary string (containing only 0 and 1), it can lead to unexpected behavior or even potential security risks. This article will introduce how to effectively prevent the bindec() function from non-binary string injection attacks, ensuring the security and stability of the program.

1. Basic Behavior of bindec() Function

bindec() accepts a string parameter, assuming the string is a binary number, such as:

echo bindec("1101"); // Outputs 13

However, if a non-binary character is passed, such as:

echo bindec("1102abc"); 

bindec() will ignore the first non-binary character and all subsequent characters, only converting the valid part, and the result will be 6 (the decimal value of 110).

Although this will not produce an error, it may lead to logical vulnerabilities, and an attacker could interfere with the program logic by injecting non-binary characters.

2. Security Risk Analysis

Non-binary string injection could lead to:

  • Data tampering: Illegal characters truncate the binary data that should have been processed.

  • Business logic errors: The program uses the binary conversion result for judgment, and abnormal inputs could cause judgment errors.

  • Potential attack surface: Can be exploited when combined with other vulnerabilities.

Therefore, strict input validation is key to prevention.

3. Effective Strategies to Prevent Injection Attacks

3.1 Input Validation: Use Regular Expressions to Strictly Limit

Before calling bindec(), use a regular expression to ensure the input contains only 0 and 1:

$binary = $_GET['binary'] ?? '';
<p>if (!preg_match('/^[01]+$/', $binary)) {<br>
// Handle invalid input<br>
die('Input must be a pure binary string');<br>
}</p>
<p>$result = bindec($binary);<br>
echo "Conversion result: " . $result;<br>

Here, preg_match('/^[01]+$/', $binary) ensures that the string consists only of 0 and 1 and has a length of at least 1.

3.2 Type Casting and Boundary Check

Even if the validation passes, it is recommended to check the value range during subsequent processing to prevent overflow or exceptions.

$decimal = bindec($binary);
if ($decimal < 0 || $decimal > PHP_INT_MAX) {
    die('Value exceeds allowed range');
}

3.3 Use Encapsulated Functions for Unified Processing

Encapsulate a secure conversion function for easier future maintenance and upgrades:

function safeBindec(string $binary): int {
    if (!preg_match('/^[01]+$/', $binary)) {
        throw new InvalidArgumentException('Input must be a pure binary string');
    }
    $decimal = bindec($binary);
    if ($decimal < 0 || $decimal > PHP_INT_MAX) {
        throw new OutOfRangeException('Value exceeds allowed range');
    }
    return $decimal;
}
<p>// Example usage<br>
try {<br>
$input = $_POST['bin'] ?? '';<br>
$result = safeBindec($input);<br>
echo "Safe conversion result: " . $result;<br>
} catch (Exception $e) {<br>
echo "Error: " . $e->getMessage();<br>
}<br>

3.4 Strengthen Security with Filter Functions

PHP's built-in filter functions can also perform simple validation:

$binary = filter_input(INPUT_GET, 'binary', FILTER_SANITIZE_STRING);
if (!preg_match('/^[01]+$/', $binary)) {
    die('Invalid binary string');
}

4. Conclusion

  • bindec() function partially parses non-binary characters, posing potential injection risks.

  • The most important thing is to strictly validate the input before calling, allowing only 0 and 1.

  • Implement robust security mechanisms using regular expressions and exception handling.

  • It is recommended to encapsulate validation and conversion logic for easier maintenance and centralized management.


<?php
// Example code demonstrating secure use of bindec()
<p>function safeBindec(string $binary): int {<br>
if (!preg_match('/^[01]+$/', $binary)) {<br>
throw new InvalidArgumentException('Input must be a pure binary string');<br>
}<br>
$decimal = bindec($binary);<br>
if ($decimal < 0 || $decimal > PHP_INT_MAX) {<br>
throw new OutOfRangeException('Value exceeds allowed range');<br>
}<br>
return $decimal;<br>
}</p>
<p data-is-last-node="" data-is-only-node="">try {<br>
// Assume binary string is retrieved from the URL, replace domain with m66.net<br>
$input = $_GET['bin'] ?? '';<br>
$result = safeBindec($input);<br>
echo "Conversion result: " . $result;<br>
} catch (Exception $e) {<br>
echo "Error: " . $e->getMessage();<br>
}<br>
?><br>