Cheerio
Cheerio

Reputation: 1240

Check string in PHP

I want to check some string before sending an email. I have 3 fields: name + email + text

I'm wondering if mysql_escape_string is good even If I'll not insert the values into a sql table. So I used:

PHP code:


  $name = trim($name);
  $name = strip_tags($name);
   # etc 


Question:
It's enough?

EDIT: I want to remove HTML Tags (Expet <p> & <br /> from the Text Field) + Trim the strings

Upvotes: 1

Views: 213

Answers (4)

Sarfraz
Sarfraz

Reputation: 382881

If you want to remove all HTML Tags except <p> & <br />:

$name = strip_tags(trim($name), '<p><br>');

Second argument to strip_tags­Docs is the allowed tags. But you can not specify which attributes to preserve or drop for the tags with that function.

I'm pretty sure how to do that has been already asked on this site, so you should take a search or look at this duplicate:

Upvotes: 1

user1130272
user1130272

Reputation:

Actually you can pass strip_tags what you want to allow

example:

<?php
$text = '<p>Test paragraph.</p><br><br>';
// Allow <p> and <br>
echo strip_tags($text, '<p><br>');
?>

Upvotes: 2

Jens Kohl
Jens Kohl

Reputation: 5969

You really want to read the documentation of filter_var, filter_var_array, filter_input and filter_input_array. That's the modern way to go, with this you're able to compose complex filtering and sanatizing.

Upvotes: 1

Tieson T.
Tieson T.

Reputation: 21236

I didn't create this snippet, and I've misplaced the source, but this function seems to do a decent job of sanitizing for me and my low-traffic sites:

#   Sanitizer function - removes forbidden tags, including script tags
function strip_tags_attributes( $str, 
    $allowedTags = array('<a>','<b>','<blockquote>','<br>','<cite>','<code>','<del>','<div>','<em>','<ul>','<ol>','<li>','<dl>','<dt>','<dd>','<img>','<ins>','<u>','<q>','<h3>','<h4>','<h5>','<h6>','<samp>','<strong>','<sub>','<sup>','<p>','<table>','<tr>','<td>','<th>','<pre>','<span>'), 
    $disabledEvents = array('onclick','ondblclick','onkeydown','onkeypress','onkeyup','onload','onmousedown','onmousemove','onmouseout','onmouseover','onmouseup','onunload') )
{       
    if( empty($disabledEvents) ) {
        return strip_tags($str, implode('', $allowedTags));
    }
    return preg_replace('/<(.*?)>/ies', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabledEvents) . ")=[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($str, implode('', $allowedTags)));
}

HTH.

Upvotes: 0

Related Questions