FEATUREDLatestSecurity Guides

Dangerous PHP Functions

PHP is one of the most popular scripting languages in the world, powering millions of websites and web applications. However, like any programming language, it has its scale of vulnerabilities and weaknesses that can be exploited by hackers and cybercriminals. One area of concern when it comes to PHP security is the use of dangerous functions. These functions present a significant risk to the security and integrity of your code, making it easier for attackers to infiltrate and compromise your website. In this guide, we’ll take a closer look at some of the most common PHP dangerous functions and what you can do to avoid them.

What are Dangerous PHP Functions?

In PHP, dangerous functions refer to functions piece of the code that can pose a security risk if not used properly. These functions can allow an attacker to execute arbitrary code, read or write files, access system resources, or manipulate data in unintended ways. Some examples of dangerous PHP functions include eval(), system(), exec(), shell_exec(), passthru(), popen(), and proc_open(). These functions are often used to execute shell commands or to interact with the operating system, making them vulnerable to code injection attacks if user input is not properly sanitized. Therefore, it is important to be aware of the potential dangers of these functions and to use them with caution, or avoid them altogether, when building PHP applications.

Below you can see almost all PHP Dangerous Functions Vulnerable and fixed code Examples

Examples:

1.eval():

Explanation: eval() is a function that allows you to execute arbitrary code as a string. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary code on the server.

$user_input = $_GET['data'];
eval($user_input);

Fix: Instead of using eval(), use a safer method of executing code, such as using json_decode() to parse and validate JSON input.

Also

Instead of using eval() with user-defined input, use a safer method of executing dynamic code, such as using a switch statement or a callback function.

$user_input = $_GET['code'];
switch ($user_input) {
    case 'function1':
        function1();
        break;
    case 'function2':
        function2();
        break;
    default:
        // handle error
}
2.exec():

Explanation: exec() is a function that allows you to execute a command as a string. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server.

Example:

$user_input = $_GET['argument'];
exec("/path/to/command " . $user_input);

Fix: Instead of using exec(), use escapeshellarg() to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
system($command);
3.system():

Explanation: system() is a function that allows you to execute a command as a string. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server.

Example:

$user_input = $_GET['argument'];
system("/path/to/command " . $user_input);

Fix: Instead of using system(), use ‘escapeshellarg()’ to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
system($command);
4.passthru():

Explanation: passthru() is a function that allows you to execute a command and output the results directly to the browser. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server and output sensitive information to the browser.

Example:

$user_input = $_GET['argument'];
passthru("/path/to/command " . $user_input);

Fix: Instead of using passthru(), use ‘escapeshellarg()’ to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
passthru($command);
5.”shell_exec():

Explanation: shell_exec() is a function that allows you to execute a command and capture the output as a string. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server.

Example:

$user_input = $_GET['argument'];
shell_exec("/path/to/command " . $user_input);

Fix: Instead of using shell_exec(), use ‘escapeshellarg()’ to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
shell_exec($command);
6.popen():

Explanation: popen() is a function that allows you to execute a command and capture the output as a readable stream. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server.

Example:

$user_input = $_GET['argument'];
$handle = popen("/path/to/command " . $user_input, 'r');
while (!feof($handle)) {
    $buffer = fread($handle, 4096);
    echo $buffer;
}
pclose($handle);

Fix: Instead of using popen(), use ‘escapeshellarg()’ to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
$handle = popen($command, 'r');
while (!feof($handle)) {
    $buffer = fread($handle, 4096);
    echo $buffer;
}
pclose($handle);
7.proc_open():

Explanation: proc_open() is a function that allows you to execute a command and communicate with it through pipes. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary commands on the server.

Example:

$user_input = $_GET['argument'];
$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("pipe", "w")
);
$process = proc_open("/path/to/command " . $user_input, $descriptorspec, $pipes);
$output = stream_get_contents($pipes[1]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

Fix: Instead of using ‘proc_open()’, use ‘escapeshellarg()‘ to sanitize the input and ensure that it is safe to use as a command argument.

$user_input = $_GET['argument'];
$command = "/path/to/command " . escapeshellarg($user_input);
$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("pipe", "w")
);
$process = proc_open($command, $descriptorspec, $pipes);
$output = stream_get_contents($pipes[1]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
8.assert():

Explanation: assert() is a function that allows you to evaluate a string as PHP code and return a boolean result. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary code on the server.

Example:

$user_input = $_GET['condition'];
assert($user_input);

Fix: Instead of using assert(), use a safer method of evaluating code, such as using ‘eval()’ in combination with a conditional statement.

$user_input = $_GET['condition'];
if (eval("return " . $user_input . ";")) {
    // code to execute if condition is true
}
9.’extract()’:

Explanation: ‘extract()’ is a function that allows you to import variables into the current symbol table from an array. This can be dangerous if the input is not properly validated, as it can allow an attacker to overwrite existing variables and execute arbitrary code.

Example:

$user_input = $_GET['data'];
extract($user_input);

Fix: Instead of using extract(), use a safer method of importing variables, such as using array keys as variable names.

$user_input = $_GET['data'];
$var1 = $user_input['var1'];
$var2 = $user_input['var2'];
10.parse_str():

Explanation: parse_str() is a function that parses a query string into variables. This can be dangerous if the input is not properly validated, as it can allow an attacker to overwrite existing variables and execute arbitrary code.

Example:

$user_input = $_SERVER['QUERY_STRING'];
parse_str($user_input);

Fix: Instead of using parse_str(), use a safer method of parsing query strings, such as using parse_url() to extract the query string and parse_str() with an array to store the parsed variables.

$user_input = $_SERVER['QUERY_STRING'];
$query = parse_url($user_input, PHP_URL_QUERY);
parse_str($query, $parsed_vars);
11.array_map():

Explanation: array_map() is a function that applies a callback function to each element of an array. This can be dangerous if the callback function is not properly validated, as it can allow an attacker to execute arbitrary code.

Example:

$user_input = $_GET['callback_function'];
$my_array = array('one', 'two', 'three');
$result = array_map($user_input, $my_array);

Fix: Instead of using array_map() with a user-defined callback function, use a safer method of iterating through an array, such as using a foreach loop.

$user_input = $_GET['callback_function'];
$my_array = array('one', 'two', 'three');
$result = array();
foreach ($my_array as $element) {
    $result[] = $user_input($element);
}
12.preg_replace():

Explanation: preg_replace() is a function that performs a regular expression search and replace on a string. This can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary code.

Example:

$user_input = $_GET['pattern'];
$string = $_GET['string'];
$result = preg_replace($user_input, 'replacement', $string);

Fix: Instead of using preg_replace() with a user-defined regular expression pattern, use a safer method of performing string manipulations, such as using str_replace() or substr().

$user_input = $_GET['pattern'];
$string = $_GET['string'];
if (preg_match('/^[a-zA-Z0-9]+$/', $user_input)) {
    $result = preg_replace($user_input, 'replacement', $string);
}
13.include() and require():

Explanation: include() and require() are functions that include and evaluate a specified file. This can be dangerous if the input is not properly validated, as it can allow an attacker to include and execute arbitrary files.

Example:

$user_input = $_GET['file'];
include($user_input);

Fix: Instead of using include() or require() with user-defined input, use a safer method of including files, such as using a whitelist of allowed file names.

$user_input = $_GET['file'];
$allowed_files = array('file1.php', 'file2.php', 'file3.php');
if (in_array($user_input, $allowed_files)) {
    include($user_input);
}
14.header():

Explanation: header() is a function that sends a HTTP header to the client. This can be dangerous if the input is not properly validated, as it can allow an attacker to inject arbitrary headers and conduct a range of attacks, including cross-site scripting and injection attacks.

Example:

$user_input = $_GET['header_value'];
header('Content-Type: ' . $user_input);

Fix: Instead of using header() with user defined input, use a safer method of setting HTTP headers, such as using a whitelist of allowed header values.

$user_input = $_GET['header_value'];
$allowed_headers = array('text/html', 'text/plain', 'application/json');
if (in_array($user_input, $allowed_headers)) {
    header('Content-Type: ' . $user_input);
}
15.mysqli_query():

Explanation: mysqli_query() is a function that sends a query to the MySQL database. This can be dangerous if the input is not properly validated, as it can allow an attacker to inject SQL commands and conduct a range of attacks, including SQL injection attacks.

Example:

$user_input = $_GET['query'];
mysqli_query($db_connection, $user_input);

Fix: Instead of using mysqli_query() with user-defined input, use a safer method of querying the database, such as using prepared statements.

$user_input = $_GET['query'];
$stmt = mysqli_prepare($db_connection, $user_input);
mysqli_stmt_execute($stmt);
16.unserialize():

Explanation: unserialize() is a function that deserializes a PHP string into an object. This can be dangerous if the input is not properly validated, as it can allow an attacker to inject arbitrary code and execute it within the context of the application.

Example:

$user_input = $_GET['data'];
$object = unserialize($user_input);

Fix: Instead of using unserialize() with user-defined input, use a safer method of handling serialized data, such as using a whitelist of allowed object types.

$user_input = $_GET['data'];
$allowed_types = array('my_object_type', 'another_object_type');
if (in_array(get_class($object), $allowed_types)) {
    $object = unserialize($user_input);
}
17.putenv() and getenv():

Explanation: putenv() is a function that sets an environment variable, and getenv() is a function that retrieves the value of an environment variable. This can be dangerous if the input is not properly validated, as it can allow an attacker to modify or read sensitive system variables.

Example:

$user_input = $_GET['var_value'];
putenv('MY_VAR=' . $user_input);
echo getenv('MY_VAR');

Fix: Instead of using putenv() and getenv() with user-defined input, use a safer method of setting and retrieving environment variables, such as using predefined variables.

$my_var = 'default_value';
putenv('MY_VAR=' . $my_var);
echo getenv('MY_VAR');
18.highlight_file():

Explanation: highlight_file() is a function that displays the highlighted syntax of a file. It can be dangerous if the input is not properly validated, as it can allow an attacker to view the source code of a file that they should not have access to.

Example:

$user_input = $_GET['file'];
highlight_file($user_input);

Fix: Instead of using highlight_file() with user-defined input, use a safer method of displaying files, such as using a predefined list of allowed files.

$user_input = $_GET['file'];
$allowed_files = array('file1.php', 'file2.php', 'file3.php');
if (in_array($user_input, $allowed_files)) {
    highlight_file($user_input);
}
19.file_put_contents():

Explanation: file_put_contents() is a function that writes data to a file. It can be dangerous if the input is not properly validated, as it can allow an attacker to write arbitrary data to any file on the server.

Example:

$user_input = $_POST['data'];
$file_name = $_POST['file_name'];
file_put_contents($file_name, $user_input);

Fix: Instead of using file_put_contents() with user-defined input, use a safer method of writing data to files, such as using a predefined list of allowed file names.

$user_input = $_POST['data'];
$file_name = $_POST['file_name'];
$allowed_files = array('file1.txt', 'file2.txt', 'file3.txt');
if (in_array($file_name, $allowed_files)) {
    file_put_contents($file_name, $user_input);
}
20.mb_send_mail(), mail(), imap_mail():

Explanation: These functions are used to send email messages. They can be dangerous if the input is not properly validated, as it can allow an attacker to send spam, phishing emails, or even execute code on the server if the email message contains malicious content.

Example:

$to = $_GET['to'];
$subject = $_GET['subject'];
$message = $_GET['message'];
$headers = 'From: ' . $_GET['from'];
mail($to, $subject, $message, $headers);

Fix: Instead of using these functions with user-defined input, use a safer method of sending email messages, such as using a dedicated email sending service or validating the email content before sending.

$to = $_GET['to'];
$subject = $_GET['subject'];
$message = $_GET['message'];
$headers = 'From: ' . $_GET['from'];
$allowed_domains = array('example.com', 'example.org');
$to_domain = explode('@', $to)[1];
if (in_array($to_domain, $allowed_domains) && filter_var($to, FILTER_VALIDATE_EMAIL) && filter_var($headers, FILTER_VALIDATE_EMAIL)) {
    mail($to, $subject, $message, $headers);
}
21.ldap_bind(), ldap_search(), ldap_compare(), ldap_delete(), ldap_add(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_mod_del():

Explanation: These functions are used to interact with LDAP servers. They can be dangerous if the input is not properly validated, as it can allow an attacker to execute arbitrary LDAP commands on the server.

Example:

$ldap_conn = ldap_connect('ldap://example.com');
$ldap_bind = ldap_bind($ldap_conn, $_GET['username'], $_GET['password']);

Fix: Instead of using these functions with user-defined input, use a safer method of interacting with LDAP servers, such as hard-coding the LDAP server information or using a predefined list of allowed LDAP commands.

$ldap_conn = ldap_connect('ldap://example.com');
$allowed_commands = array('bind', 'search');
if (in_array($_GET['command'], $allowed_commands)) {
    switch ($_GET['command']) {
        case 'bind':
            $ldap_bind = ldap_bind($ldap_conn, $_GET['username'], $_GET['password']);
            break;
        case 'search':
            $result = ldap_search($ldap_conn, $_GET['base'], $_GET['filter']);
            break;
    }
}

Note: This is not an exhaustive list of all dangerous functions in PHP, as new vulnerabilities can be discovered and added over time. It’s important to stay up-to-date on the latest security issues and best practices for secure coding.

Importance of PHP Secure Coding

The advent of PHP(Server-side scripting language), has enabled developers to create dynamic and interactive web applications. However, with the increasing number of vulnerabilities and cyberattacks, secure coding in PHP has become more critical than ever. Secure coding practices ensure the confidentiality, integrity, and availability of data, protecting against unauthorized access, data breaches, and other malicious activities. It is crucial for developers to have a good understanding of secure coding in PHP to prevent security threats and create applications that are not only functional but also secure. By implementing secure coding practices, developers can help secure user data.

Conclusion

PHP is a powerful and wen programming language that can help you create robust and dynamic web applications. However, it’s also important to be aware of the potential vulnerabilities and risks that come with it. By avoiding dangerous functions and following best practices for code security, you can help ensure that your website or application stays safe and secure. Take the time to learn about the various functions and features of PHP and how they can be used securely, and you’ll be able to build amazing applications that are both powerful and secure.