Jump to content

Confused about cleaning special characters in PHP strings for use in queries


Recommended Posts

Hi,

Please can you advise a rusty PHP noob on the following? I'm trying to make sure I do this correctly.

I'm trying to use a function to clean and make safe my URL or Post strings, for use in a query on the next PHP page.

<?php
function cleanString($string)
{

// remove any HTML tags from the string that is invalid or not allowed

  $name = filter_var($string, FILTER_SANITIZE_STRING);
  
        
// HTML-encode special characters like quotes, ampersands, and brackets (in addition to characters with ASCII value less than 32).   
  
  $name = filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS);
  
  return $name;
} 
?>

I'm using Mysqli procedural queries (switching over to them from Mysql existing queries).

The second page is receiving the person's name and displays the relevant information for that person from the database.

(I'm using $request instead of $GET or $POST in case the string is received via URL or Form)

Say I have a persons name "Homer Simpson" in a URL on page 1:

<a href=\"actor_profile.php?name=Homer Simpson\" title=\"View ".$row['name']."'s Actor Profile.\" ></a>

 

This is my code on actor_profile.php to get the cleaning function and pass the name to it:

# Start - Get the function to clean url form variables and strings for security
include("../includes/clean_url_name.html");

# Use REQUEST instead of GET or POST in case string is received by url or form so I only have to do this once for either.
$name = cleanString($_REQUEST['name']);

$sql = "SELECT name FROM people WHERE name = '".$name."'";
	$result = $con->query($sql);
	
	if(!$result = $con->query($sql)){
		die('There was an error running the query [' . $con->error . ']');
	}
	$row = $result->fetch_assoc();

echo "<h1>".$row['name']."</h1>";

My code works!

The page is able to run the query on the database and display my web page correctly.

I think this is okay and its stripped out any nasty HTML tags and encoded any special characters, but I'm probably missing something.

However, if I have a person's name that contains an apostrophe, like Homer O'Quinn it doesn't work.

Then I can't use the cleaned string in my Query as the page just breaks.

I thought the idea of HTML encoding special characters was to make sure queries could run if the query contains a special character like an apostrophe.

Can anyone please advise me what I'm doing wrong, and how to fix it, so the query is safely cleaned and able to use names with apostrophes in?

Many thanks!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...