I'm having trouble getting this to function properly with the PHP sanitization filters

Can anyone provide guidance on my issue? I am attempting to sanitize and validate user input from a form using PHP filters. The input will be stored in a MySQL database and displayed on an HTML page, so it is essential to remove all HTML tags and ensure security for MySQL.

Thank you in advance.

      /*
 * BEGIN Sanitize and validate
 */

  // Define fields to be sanitized.
$filters = array(
   'author'  => FILTER_SANITIZE_SPECIAL_CHARS,
   'title'  => FILTER_SANITIZE_SPECIAL_CHARS,
   'description'  => FILTER_SANITIZE_SPECIAL_CHARS,
);


/*** Apply the filters to the POST array ***/
$filtered = filter_input_array(INPUT_POST, $filters);

// Filter out anything that is not an email address
    $sanitized_email = filter_var(($_POST["email"]), FILTER_SANITIZE_EMAIL);
    if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)  == TRUE) {
        echo '';
    } else {
        echo 'Invalid Email Address. Please go back.';
        exit;
    }

    /*
 * BEGIN sanitize and validate
 */

I have made some updates to the code, but it is still not functioning correctly. The data is still showing HTML in the database, and the error handling is not working as intended.

      /*
 * BEGIN Sanitize and validate
 */

  // Define fields to be sanitized.
$filters = array(
   'author'  => FILTER_SANITIZE_STRING,
   'title'  => FILTER_SANITIZE_STRING,
   'description'  => FILTER_SANITIZE_STRING,
);


/*** Apply the filters to the POST array ***/
$filtered = filter_input_array(INPUT_POST, $filters);
$filters = array_map('mysql_real_escape_string',$filters);
$filters = array_map('htmlspecialchars',$filters);
    if (filter_var_array($filtered, FILTER_SANITIZE_STRING)) {
        echo '';
    } else {
        echo 'Invalid Input. Please go back.';
        exit;
    }

// Filter out anything that is not an email address
    $sanitized_email = filter_var(($_POST['email']), FILTER_SANITIZE_EMAIL);
    if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) {
        echo '';
    } else {
        echo 'Invalid Email Address. Please go back.';
        exit;
    }

    /*
 * BEGIN sanitize and validate
 */

2nd Edit below:

To display sanitized data in the database, I included the sanitizing code in the script section that handles data insertion into the database.

 $_POST['author'] = mysql_real_escape_string(trim($_POST['author']));
      $author=filter_var($_POST['author'], FILTER_SANITIZE_STRING);

      $_POST['email'] = mysql_real_escape_string(trim($_POST['email']));
      $email=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

Now, I need to focus on properly validating the email.

Answer №1

One important thing to note is that the filter module does not provide security for your queries. It primarily focuses on sanitizing and validating user input, rather than handling interactions with the database. This means that even after using the filter module, certain characters like quotes or apostrophes that could potentially break an SQL query may still be present in the input. It is crucial for you to escape these characters before saving them in the database, particularly if you are working with systems that do not offer parameter binding like PDO.

In order to ensure the security of your queries, it is recommended to utilize PDO. Alternatively, if you are constrained to other systems, you can resort to methods such as escaping input with mysql_real_escape_string when utilizing functions from the mysql_* family.

If you also need to sanitize and remove HTML tags from user input, it is advisable to use the FILTER_SANITIZE_STRING flag instead of FILTER_SANITIZE_SPECIAL_CHARS.

A script like this one has worked effectively for me in removing HTML tags from input.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...

What is the best way to manage the back button using jQuery?

I'm currently facing a challenge when it comes to managing the Browser's History. While plugins like History.js can be helpful for smaller tasks, I find myself struggling with more complex scenarios. Let me provide an example: Imagine I have a m ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

Verifying dynamic number inputs generated using JavaScript values and calculating the total with a MutationObserver

Preamble: I've referenced Diego's answer on dynamic field JS creation and Anthony Awuley's answer on MutationObserver for the created fields. After extensive searching, I found a solution that meets my needs, but it feels somewhat bulky des ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

The JQUERY code for refreshing a div requires a timeout delay

I'm looking for a way to refresh a specific div on my website that's used for chat. Here's the code I currently have: var refreshId = setInterval(function() { $('#chat_grab').load('chat_grab.php?randval=' + Math.rand ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...