Why check if stripslashes function exists? - php

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:
http://trevordavis.net/blog/wordpress-jquery-contact-form-without-a-plugin/
PHP contact form will not submit

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.

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)
https://wiki.php.net/rfc/mysql_deprecation
https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7
https://wiki.php.net/rfc
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.

Related

PHP 7.4 deprecated get_magic_quotes_gpc function alternative

I am encountered with the situation where one of my old code is using get_magic_quotes_gpc() which is deprecated in the latest PHP version 7.4.*
Currently, I have something like this.
Add Slashes
return get_magic_quotes_gpc() ? addslashes($string) : $string;
Remove Slashes
return get_magic_quotes_gpc() ? stripslashes($string) : $string;
Which is obviously giving error
Deprecated: Function get_magic_quotes_gpc() is deprecated
Question:
How can I fix it? So can work the same without using get_magic_quotes_gpc() function?
You need to remove every mention of this function from your code and do not replace it with anything else.
get_magic_quotes_gpc() has been useless ever since PHP 5.4.0. It would tell you whether you have magic quotes switched on in the configuration or not. Magic quotes were a terrible idea and this feature was removed for security reasons (PHP developers believed in magic & superstitions and wrote unsecure code).
Most likely even you yourself do not know why you had this line of code in your project. I know I was fooled by it when I was learning PHP. The reality is you do not need it at all. This function has nothing to do with security and the concept of input sanitization is preposterous.
Instead, rely on good security guidelines.
Use parameterized prepared statements for interactions with the database. PHP has a very good library called PDO, which can be used with many DB drivers including MySQL.
If you produce output, then escape the output taking into consideration the rules of that medium. For example when outputting to HTML use htmlspecialchars() to prevent XSS.
Never sanitize input. There is no magical solution that would protect you against everything. Instead, you as a developer must be aware of dangers and you need to know how to protect your code. Don’t try to sanitize input. Escape output.
Replace get_magic_quotes_gpc() with false.
Then simplify complex expressions by removing the unreachable branches. E.g.
return get_magic_quotes_gpc() ? addslashes($string) : $string;
becomes simply
return $string;

Add removed/deprecated functions to PHP5

Is it possible to add a removed/deprecated function to PHP5? Like session_is_registered, ereg, etc.
[update] solved for session_is_registered:
<?php
function session_is_registered($name) {
return isset($_SESSION[$name]);
}
thanks.
Of course you can do it by modifying and recompiling the PHP source code, however the first question you have to answer is Do I really need to this or I might be better to go for my IDE's find-and-replace function?
If there is a real need for this -- for whatever reason, maybe you can redefine those functions. I haven't test it yet, as I agree with others that functions and features get removed or deprecated for a good and mostly important reasons, so I'm not sure if it does work in a situation that the function is removed or depreciated, but you can try to redefine them either using runkit_function_redefine or
override_function.
In that case you have to simulate the functionality again -- probably with their good-to-go replacements, so again think twice before start doing that.

Confusion about mysql_real_escape_string and strip_slashes

I have users entering their name, as in: O'riley.
Before I enter this data into the MySQL DB, I run mysql_real_escape_string.
Problem is, when I then select this data for display and use later, it comes out as: O\'riley.
Obviously, this is the intended operation. What I'm wondering is if there's someway to be sure I can store it in the DB (still safely escaping possible malicious code), so that I don't have to use strip_slashes() on the output EVERY time I call the data throughout the entire web app? Or, am I missing something here?
Thanks.
UPDATE
Please refer to the comments in Deceze's answer.
No, it's not the intended operation to store the string as "O\'riley"; it should only be escaped in the query, but not stored this way. I'll guess that PHP puts in the backslash through Magic Quotes, and you escape it again to make it stick.
Disable Magic Quotes.
I personally always turn off magic quotes because it is doing something I haven't told it to do. If you dont have the ability to turn it off, consider including this code at the top of all of your pages.
if (get_magic_quotes_gpc()) {
function strip_array($var) {
return is_array($var)? array_map("strip_array", $var):stripslashes($var);
}
$_POST = strip_array($_POST);
$_SESSION = strip_array($_SESSION);
$_GET = strip_array($_GET);
}
If you have magic quotes disabled, and in the case that get_magic_quotes_gpc returned 1 and you did something like #Michael shows and this still occurs, magic quotes runtime may be enabled.
Magic quotes runtime will add slashes to strings when doing database queries and even when writing to files. To disable this in the currently executing script, do:
if(function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime())
{
set_magic_quotes_runtime(false);
}
You can also disable this configuration option through php.ini as well, if you can do so. However, if you can't disable it through php.ini permanently, you may need to add # before get_magic_quotes_runtime and set_magic_quotes_runtime as PHP may through E_DEPRECATED errors if error_reporting is set to log such errors (and this will get fairly annoying).
Alright, here's what you need to do. First, based on the comments, from other questions:
ISOLATE
You need to determine what is causing the problem. Is it the server? Is it some hidden code somewhere? What? Some programmers may include code like this on a configuration page:
<?php if (isset($_POST))
foreach ($_POST as $key => $value) $_POST[$key] = addslashes($value);
?>
So here are some checks to see if it is the server. This is about as solid a way of checking as possible. Create a NEW page. Leave it entirely blank and add this code:
<?php print_r($_POST); ?>
<form action="" method="POST">
<input type="text" name="test" value="O'riley" />
<input type="submit" name="submit" value="submit" />
</form>
Save it and load it in the browser. Hit submit. See if the slash is added still.
If it is still adding it, you need to troubleshoot your server / configuration. If it's a server you're paying for, you need to tell them to fix it or shove it. If it's your own server, then you're going to need to do some messing / googling to figure out how to turn off magic quotes.
If there are no quotes showing up, then there is definitely some code adding slashes to your post variables. It might not be as obvious as the code above, however. You need to run a search on your code for "addslashes", "mysql_real_escape_string", and possibly "str_replace". If you find one of these, you need to disable it. But be advised this may break other parts of your site that are assuming this action is taking place. You're other option for storing it in the database is to do a function similar to the code above, but instead, run stripslashes on it. Then you can run mysql_real_escape_string on it later. (A bit more unneeded overhead.)
Use
var_dump(get_magic_quotes_gpc());
somewhere near the actual use of the posted data to see if the Magic Quotes are really off.
Also some weird frameworks may add said quotes for you so grep your code for addslashes and other escape_string-like functions.
I would honestly suggest the use of PDO.
PDO employs the use of prepare and execute statements, which in turn adds security and removes some extra headache.
$pdo = new PDO();
$stm = $pdo->prepare('INSERT... (LastName) VALUES (:LastName)');
$stm->execute(array(':LastName' => "O'Rily"));
$stm->fetchAssoc(PDO::FETCH_ASSOC);
You no longer will need to worry about removing the escaping slashes as well as securing basic sql injection tactics.
It's possible magic quotes are turned on in your httpd.conf or in a virtual host declaration.
The exact location and file will depend on OS and distro. I'd check Apache configuration files for the php_flag setting.
Just use clean the data before inserting in to database,
function check_input($value)
{
if( get_magic_quotes_gpc() )
{
$value = stripslashes( $value );
}
//check if this function exists
if( function_exists( "mysql_real_escape_string" ) )
{
$value = mysql_real_escape_string( $value );
}
//for PHP version < 4.3.0 use addslashes
else
{
$value = addslashes( $value );
}
return $value;
}
$cleandata = check_input($value);
$sql = "INSERT INTO `table_name` SET `field_name`='".$cleandata."'";
While fetching the data and show into it use stripslashes($val)
Thank you everyone for the answers. I will award the +50 out, but I wanted to tell my real solution here, all which people did help with...
I was performing mysql_real_escape_string on all of the data AS SOON as it posted (before any processing). So, a slash was added to escape the ' character that was submitted. This, we know is normal.
However, there was no reason that the backslash \ should show up in the DB entry, right? The escape was there to be sure the ' was entered.
Turns out, AFTER escaping, I would then save the variable to be reloaded to the page in the session, in case the user had an error that PHP found while validating all of the form fields. In this case, the user's input (formerly O'riley was now printed to their screen as O\'riley. Then, the user didn't catch this - so they would often just fix their error that PHP caught during validation (unrelated to the name field), and thus the O\'riley would land in the database because mysql_real_escape_string would escape the characters.
Lesson:
When processing a form, FIRST save data for form-refill use. SECOND validate form fields. THIRD escape the data for processing into the database.
Or better yet, use PDO and avoid this =).
Comments welcome. THANKS ALL!

PHP extracting without extract()

I have something like:
if(isset($_POST['submit']))
{
$linktitle=strtolower(str_replace(" ","-",$title));
etc.
$linktitle and $title are actually variables from $_POST - ie $_POST['linktitle'] and $_POST['title'].
Somehow, even though (as far as I can see!) I haven't extract()ed $_POST at this stage in the code, it is still working - PHP is understanding that $title is referring to $_POST['title']. Could anyone please explain why this might be?
Thanks!
ps. Sorry, but I really can't get this inline code quote formatting thing to work...!
register_globals is enabled in your PHP instance. See here for more info.
This is behaviour that should be relied upon as it's use is now deprecated. You will find that you can still use $_POST['keyname'] as well as $keyname, and that is what you should refer to in your code.
Your php.ini file must have register_globals enabled, so GPC variables are being added to the symbol table. This is why you see this behaviour. See the security risks of such a feature here
You have register globals activated in your webserver (php.ini), so PHP replace the unknoe variables with the corresponding GET or POST value. This option is deprecated and dangerous! Disable it if you can!

"slash before every quote" problem [duplicate]

This question already has answers here:
Why are $_POST variables getting escaped in PHP?
(6 answers)
Closed 7 years ago.
I have a php page which contains a form.
Sometimes this page is submitted to itself (like when pics are uploaded).
I wouldn't want users to have to fill in every field again and again, so I use this as a value of a text-input inside the form:
value="<?php echo htmlentities(#$_POST['annonsera_headline'],ENT_COMPAT,'UTF-8');?>">
This works, except it adds a "\" sign before every double-quote...
For instance writing 19" wheels gives after page is submitted to itself:
19\" wheels
And if I don't even use htmlentities then everything after the quotes dissappears.
What is the problem here?
UPDATE:
Okay, so the prob is magic_quotes... This is enabled on my server...
Should I disable it? I have root access and it is my server :)
Whats the harm in disabling it?
Looks like you have magic quotes turned on. Use below condition using stripslashes with whatever text you want to process:
if(get_magic_quotes_gpc())
{
$your_text = stripslashes($your_text);
}
Now you can process $your_text variable normally.
Update:
Magic quotes are exaplained here. For well written code there is normally no harm in disabling it.
You likely have magic quotes turned on. You need to stripslashes() it as well.
Nicest way would be to wrap this in a function:
function get_string($array, $index, $default = null) {
if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
return get_magic_quotes_gpc() ? stripslashes($value) : $value;
} else {
return $default;
}
}
Which you can use as
$annonsera_headline = get_string($_POST, 'annonsera_headline');
By the way:
And if I don't even use htmlentities then everything after the quotes dissappears.
It's actually still there in the HTML source, you only don't see it. Do a View Source ;)
Update as per your update: the magic quotes is there to prevent SQL injection attacks in code of beginners. You see this often in 3rd party hosts. If you really know what you're doing in the code, then you can safely turn it off. But if you want to make your code distributable, then you'll really take this into account when gathering request parameters. For this the above function example is perfectly suitable (you only need to write simliar get_boolean(), get_number(), get_array() functions yourself).
Yes, you should disable magic quotes if you can. The feature is deprecated, and will likely go away completely in the future.
If you've relied on magic quotes for escaping data (for instance when inserting it into a database) you will may be opening yourself up to sql injection vulnerabilities if you disable it. You should check all your queries and make sure you're using mysql_real_escape_string().
I include the following file to undo magic quotes in apps that are deployed to servers not under my control.
<?php
set_magic_quotes_runtime(0);
function _remove_magic_quotes(&$input) {
if(is_array($input)) {
foreach(array_keys($input) as $key) _remove_magic_quotes($input[$key]);
}
else $input = stripslashes($input);
}
if(get_magic_quotes_gpc()) {
_remove_magic_quotes($_REQUEST);
_remove_magic_quotes($_GET);
_remove_magic_quotes($_POST);
_remove_magic_quotes($_COOKIE);
}
return true;
?>
This is actually a function of PHP trying to be security conscious, luckily there is an easy fix for it that looks something like this:
if (get_magic_quotes_gpc()) {$var = stripslashes($var);}
There isn't a huge problem in having it enabled, it comes down to personal preference. If you code will be moving servers much and you can't disable it through your php.ini file, it's best to use something as described above.
If you have access to your php.ini file and you want to change it, because you don't want to have to validate it each time you can add the following line to php.ini
magic_quotes_gpc = Off
Or the following to your .htaccess:
php_flag magic_quotes_gpc Off
Hope this helps clear things up.
Looks like your server is setup to use Magic Quotes.
You can fix it by stripping them with stripslashes, or better, by turning off Magic Quotes.
you shouldn't use htmlentities() when writing something to an input field value.
is magic_quotes enabled on your server? try out stripslashes before the output.

Categories