Escaping Characters Such as $ and % | MySQL and PHP

前端 未结 3 666
长发绾君心
长发绾君心 2021-01-20 21:54

So basically I’ve been digging deep into the realm of MySQL and PHP…specifically the security measures I should take when dealing with a database and form inputs. So far I’

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-20 22:12

    Am I doing something horrendously wrong?

    Yes.

    First on your research.

    Prepared Statements is the only great thing you have found.

    While use of mysqli_real_escape_string (assuming you are using prepared statements) would be useless and harmful (producing the outcome you have noted yourself: “You\’re name isn\’t….”).

    And Magic Quotes has been removed from the language long time ago already - thus, nothing to concern actually.

    So, even most of your initial premises are plainly wrong.

    Now to your question.

    Couldn’t the query interpret the dollar sign as a PHP variable perhaps?

    No.

    What about LIKE syntax I’ve heard that uses the % symbol or even the wildcard sign?

    Yes, you've heard it right. That's exact purpose of LIKE operator - to perform a wildcard search. Disabling these symbols in LIKE would make not a slightest sense.

    Means every time you are going to use LIKE operator, you have to decide which particular symbol to use and which to disallow. NO one-for-all solution can be used. Not to mention that in all other mysql interactions % sign has no special meaning at all.

    Prepared statements should technically take care of all of this

    Prepared statements has nothing to do neither with $ nor with % signs. Prepared statements deal with SQL injections, but neither symbol could cause it (wouldn't you call "injection" a proper intended use of LIKE operator, would you?).

    Finally, to the most horrendous part.

    In the case you forget to use prepared statements or just neglect to do them,

    nothing can save you.

    And least help would be from the function you developed.

    To sum it all up.

    1. Get rid of this function.
    2. Use placeholders* to represent every single variable in the query.
    3. Escape % and _ symbols in the input data only if it's going to be used in LIKE operator and you don't want them to be interpreted.
    4. Use htmlspecialchars() for output, not mysql input.

    *read on prepared statements if the term is unfamiliar to you.

提交回复
热议问题