Note that there are some explanatory texts on larger screens.

plurals
  1. POphp regex or string check to make sure a variable contains specific characters
    text
    copied!<p>I need to make sure a variable that holds <code>product id</code> contains only specific characters.</p> <p>For integer-only variables I'm using <code>is_numeric</code> to check.</p> <p>But for a product id, the variable can contain only the following characters: </p> <ul> <li>many numbers [0-9]</li> <li>the characters - (dash) AND/OR _ (underscore)</li> <li>it can contain the letters "s" or "c" (but not together)</li> </ul> <p>For example, this is valid: <code>c23_2308724208_9873208</code>, this is valid: <code>12-c53_09872807342</code>, this is valid: <code>s23_208320720</code>. But this is not valid: <code>12-2352'; SELECT * FROM administrators;</code>.</p> <p>I could go into what the format of the variable is but I don't think I need that as long as I make sure that the variables consists of ONLY the above. All I want to do is put a check that would protect from SQL injections. So I don't think I need to care about the format, do I? I only want to make sure that the given characters <code>s,c,[0-9],[-,_]</code> can be found in the variable, and nothing outside of this range of valid characters.</p> <h2>Edit</h2> <p>Based on someone's comment that the format be strictly followed, then the exact format is as follows:</p> <ul> <li>optional prefix of numbers and a dash (eg. 132-)</li> <li>necessary letter (either s or c) followed by some numbers, then an underscore, then some more numbers (eg. s234_23872084732)</li> <li>optional suffix of an underscore followed by yet more numbers (so the complete example for this case would be <code>s234_23872084732_201874018743</code>).</li> </ul> <p>so if all optional things were there, it would be like <code>132-s234_23872084732_201874018743</code>, and if only necessary components were there, then <code>s234_23872084732</code>.</p> <p>but as a technical point, why is it necessary to follow a strict regex? as long as I make sure only required characters are there, a SQL injection is impossible, right?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload