Search code examples
phpformssecuritysql-injectionprestashop

Secure all inputs in PHP form


My form has several types of inputs including text, checkbox and radio. I'd like to make sure the form is secure. I used the Prestashop functions isGenericname and isCleanHTML to check the text and comment fields by ensuring the fields are valid.

Prestashop Validate.php

public static function isGenericName($name)
  {
    return empty($name) || preg_match('/^[^<>={}]*$/u', $name);
  }

public static function isCleanHtml($html, $allow_iframe = false)
  {
    $events = 'onmousedown|onmousemove|onmmouseup|onmouseover|onmouseout|onload|onunload|onfocus|onblur|onchange';

    if (preg_match('/<[\s]*script/ims', $html) || preg_match('/('.$events.')[\s]*=/ims', $html) || preg_match('/.*script\:/ims', $html))
        return false;

    if (!$allow_iframe && preg_match('/<[\s]*(i?frame|form|input|embed|object)/ims', $html))
        return false;

    return true;
  }

This is how the function is called in the form PHP file.

if (!Validate::isCleanHtml($message))
    $this->errors[] = Tools::displayError('Invalid message');
elseif (!Validate::isGenericName($fname))
    $this->errors[] = Tools::displayError('Invalid First Name.');

So my question are. Is it ok to not produce an error message for inputs such as check boxes and radio box that are not valid? The only reason they'd be invalid was if someone hacked he code before sending. Or is there a better way to strip and secure the inputs?

$checkbox = Tools::getValue('checkbox ');
 if (!Validate::isGenericName($checkbox ))
    $validCheckbox = $checkbox;

I have 68 inputs I want to make sure are secure. Is there a good PHP function that can strip out and stop any sort of SQL injection? Prestashop documents state "getValue() does not protect your code from hacking attempts (SQL injections, XSS flaws and CRSF breaches). You still have to secure your data yourself." I'm thinking I'll need to scrub it all through trim(), stripslashes(), htmlspecialchars() but I didn't know of the most efficient way.


Solution

  • To prevent first order SQL injection you can use PDO with mysql prepared statement. And when you want to display it to the html page use

    htmlspecialchars(trim($value), ENT_QUOTES, "UTF-8")`
    

    Make sure you set the appropriate character encoding in your response header correctly and use the meta tag to indicate character encoding of your HTML.

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    

    If you ever need to update back the html output into the database. Use

    htmlspecialchars_decode(trim($value))
    

    This should give you some protection.