Solved

Help with stripslashes and preg_replace

Posted on 2007-04-09
14
659 Views
Last Modified: 2010-05-18
glcummins helped me with this earlier -- I needed to loop through all $_POST variables in order to trim() and addslashes() -- but I also need to remove all double quotes.  For some reason, adding preg_replace to this function doesn't work correctly.  The function escapes double-quotes even though I've removed them with the preg_replace first.

$myVars = array();
foreach($_POST as $field=>$value)
{
$myVars[$field] = preg_replace('/\"/','',$myVars[$field]);
$myVars[$field] = trim(addslashes($value));
print $myVars[$field]; // to test
}
0
Comment
Question by:marcparillo
  • 4
  • 3
  • 2
  • +3
14 Comments
 
LVL 29

Expert Comment

by:TeRReF
ID: 18878147
You don't need preg_replace for such a simple task, use str_replace()
$myVars[$field] = str_replace('"','',$myVars[$field]);

You should flip these lines:
$myVars[$field] = preg_replace('/\"/','',$myVars[$field]);
$myVars[$field] = trim(addslashes($value));

to

$myVars[$field] = trim(addslashes($value));
$myVars[$field] = preg_replace('/\"/','',$myVars[$field]);
0
 
LVL 29

Expert Comment

by:TeRReF
ID: 18878159
Oh, and add the str_replace()   :)

$myVars[$field] = trim(addslashes($value));
$myVars[$field] = str_replace('"','',$myVars[$field]);
0
 
LVL 50

Expert Comment

by:Steve Bink
ID: 18878161
Try removing them before the addslashes():

$myVars[$field] = str_replace('"','',$value);
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
LVL 15

Expert Comment

by:Tomeeboy
ID: 18878164
You're removing double quotes from $myVars[$field], but trimming and adding slashes to $value.  I think you have a variable mixup there :)
0
 
LVL 4

Expert Comment

by:secondv
ID: 18878167
Try:

$myVars = array();

foreach ($_POST AS $field => $value)
{
      $myVars[$field] = stripslashes($myVars[$field]);
      $myVars[$field] = str_replace('"', '', $myVars[$field]);
      $myVars[$field] = trim(addslashes($value));
      print $myVars[$field]; // to test
}
0
 
LVL 4

Expert Comment

by:secondv
ID: 18878171
dang, 3-4 posted at the same time =)
0
 
LVL 24

Accepted Solution

by:
glcummins earned 100 total points
ID: 18878179
Here is the problem:

$myVars[$field] = preg_replace('/\"/','',$myVars[$field]);
$myVars[$field] = trim(addslashes($value));

In the first line, you are settings the value of $myVars[$field] to the result of the preg_replace() function. However, on the second line, you are completely replacing that value with 'trim(addslashes($value))'. The end result is that the first line is completely ignored.

You can do something like this:

$value = preg_replace('/\"/','',$myVars[$field]);
$myVars[$field] = trim(addslashes($value));

That will ensure that the second line operates on the result of the first line, rather than overwritting those results.
0
 
LVL 15

Assisted Solution

by:Tomeeboy
Tomeeboy earned 100 total points
ID: 18878252
Geez what a mess :)

Everyone but glcummins and myself seemed to overlook the variable mixup, but I do agree that str_replace would be better to use here (although that is not the solution to your problem).  To hopefully save you some confusion after reading all of these responses.  Here's what you should have in the end:

$myVars = array();
foreach($_POST as $field=>$value) {
     $myVars[$field] = str_replace('"', '', $value);
     $myVars[$field] = trim(addslashes($myVars[$field]));
     print $myVars[$field]; // to test
}
0
 
LVL 3

Author Comment

by:marcparillo
ID: 18879222
Thank you very much!

As a follow-up question, is it possible to drop the foreach() into an include .php file that can be accessed from an page as a function?

I tried this -- but it didn't work:

//include.php
function trim_and_slash() {
global $POST;
$POST = array();
foreach($_POST as $field=>$value) {
     $POST[$field] = str_replace('"', '', $value);
     $POST[$field] = trim(addslashes($POST[$field]));

}
return $POST;
}
0
 
LVL 3

Author Comment

by:marcparillo
ID: 18879255
I think I figured it out -- is this the best way to handle it?

//php file
$POST = trim_and_slash($_POST);

//include file
function trim_and_slash($POST) {
global $POST;
$POST = array();
foreach($_POST as $field=>$value) {
     $POST[$field] = str_replace('"', '', $value);
     $POST[$field] = trim(addslashes($POST[$field]));

}
return $POST;
}
0
 
LVL 50

Assisted Solution

by:Steve Bink
Steve Bink earned 100 total points
ID: 18879381
That looks good.  Some minor adjustment, and you have a general function you can use for anything:

<?
// in library/include
function trim_and_slash($a = false) {
  if ($a === false) { return false; }
  if (!(is_array($a))) {
    $ret = trim(addslashes(str_replace('"','',(string)$a)));
  } else {
    $ret = array();
    foreach($a as $key=>$val) {
      $ret[$key] = trim(addslashes(str_replace('"', '', (string)$val)));
    }
  }
  return $ret;
}

// in php file
$POST = trim_and_slash($_POST);
?>
0
 
LVL 3

Author Comment

by:marcparillo
ID: 18879397
Thank you...
But what is the purpose of ($a = false)?    I've never seen a function written that way, with a boolean value as one of the incoming parameters.

0
 
LVL 50

Expert Comment

by:Steve Bink
ID: 18879443
It provides $a with a default value should it not be passed in the function call.  I normally use it for error-checking or parameter validation.  For example:

$strip = trim_and_slash();  //$strip = false;
$strip = trim_and_slash("bur\"p'");  //$strip = "burp\'";
$strip = trim_and_slash(array(false, "bur\"p'"));  // $strip = array('0', "burp\'")

Note the last example show the value false returning '0'.  This is because of the forced-typing to string.  This also would allow me to detect a function failure:

$strip = trim_and_slash();
if ($strip === false) { error_log('AN ERROR!'); }

I guess a little unnecessary in this context, but I'm used to typing it now...hehehe
0
 
LVL 3

Author Comment

by:marcparillo
ID: 18886679
Excellent!
Thanks for everyone's help.
I'll split the points among the best, most complete answers.
$marc
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question