Why check if stripslashes function exists?

262 Views Asked by At

I've found the following code that checks if the stripslashes() function exists.

if ( function_exists( 'stripslashes' ) ) {
    // Do something
} else {
    // Do something
}

The stripslashes() function works on PHP4 and PHP5, so I wonder why it needs a conditional statement to check if the function exists. I don't get it.

It's not a subjective question. Just tell me what is the difference between the usage of this statement and not using it. Thanks in advance!

Here are related links as to where they were used:

2

There are 2 best solutions below

1
Alexander O'Mara On BEST ANSWER

There used to be a feature in PHP known as magic quotes, which while well-intentioned, has caused endless confusion.

Most likely this code is intended to detect magic quotes, however this is not the correct way to do this, especially since it does not work.

The correct way to detect if magic quotes are enabled is to use the fuction made for the purpoes, get_magic_quotes_gpc like so.

if (get_magic_quotes_gpc()) {

Or perhaps the following, if you are concerned this will be removed.

if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {

That being said, the whole magic quotes feature was removed back in PHP 5.4, so unless you need to support obsolete versions of PHP, you can just forget the whole thing ever existed (unless you use WordPress that is...).

On a side note, I suppose it's possible the stripslashes function may be removed in the future, and may not have existed at one point, but in this context that's probably not the reason.

2
Funk Forty Niner On

Sidenote: Transcribed from some of my comments (slightly modified) to supply the question with a complimentary answer to that of Alexander's.


This is probably to check if some coder went and created a custom function called the same (a method to someone's madness?), or somebody hacked the PHP core and removed it; I'm speculating of course, it's not impossible.

However, the same thing goes for if ( function_exists( 'mysql_real_escape_string' ) ).

If a server doesn't support those old and deprecated mysql_ functions, then the conditional statement is needed and would prove to be effective/useful for something of that nature to be used.

References: (mysql_ removed as of PHP 7, and other deprecation notices)

Personally, function_exists() should only be used against probable deprecated functions; mysql_ being one of them and session_register() - I'm sure there are more.

It's listed in the manual from contributed notes http://php.net/manual/en/function.stripslashes.php and it seems to have something to do with magic_quotes_gpc as per what Alexander (O'Mara) said in comments.


N.B.:

I am by no means looking to gain anything from this, but for others visiting the question.