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.
Related
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.
We have a large codebase, and every so often a var_dump used for testing and not removed/commented suddenly appears out of nowhere. There is a messy solution using XDebug (http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/), but maybe there's something ingenous that can be done in PHP at runtime.
Also, I don't want to modify or search code via regex. I've tried using my own var_dump_v2, but it falls out of use quickly.
Is it possible to use the disable_functions operation in php.ini to disable var_dump on your production server? I am not sure what the outcome of this setting is (ie does it fail with an error, or silently) the documentation is not so clear.
http://php.net/manual/en/ini.core.php - see "disable_functions"
Also there is override_function:
<?php
override_function('var_dump', '$a', 'return 0;');
?>
http://php.net/manual/en/function.override-function.php
There are actually ways to do this, if you have PECL available and runkit installed. You kan make runkit able to overide PHPs internal functions if you in php.ini set runkit.internal_override to "1".
For removing the var_dump function, you could use:
runkit_function_remove('var_dump');
In your case, not to get an error, you should probably instead use something like this:
runkit_function_redefine('var_dump', '','');
Take a look at the runkit extensions documentation here.
You may also want to take a look at "Advanced PHP debugger", another extension that seems to offer an override_function().
You can use monkey patching.
Just defines a namespace on the first line of your file and defines the function var_dump
<?php
namespace monkey;
function var_dump($obj) {}
Of course, it implies that you do not use a namespace in your current file
You could use the function var_dump() prefixing it with the root namespace(): \var_dump()
Of course, all others native function will continue to work as usual as long as you do not override them in your namespace.
Why don't you use serialize() or json_encode() if you have a large database? That will be very useful.
But take note, serialize() will give you a 1-line output somewhat like this:
's:0:"";s:5:"value";'
So you need to learn the anatomy of serialize() to use it: PHP Serialize
Is there a way to remove function alias in PHP?
I can rename my function but it would be nice to use name "fetch".
Problem:
I just tested the following code and it appears to work for me, but perhaps it is because I don't have the mysqli library installed. I would test it because it might be more contextual than your IDE will have you believe. It seems to be a method for mysqli, but it might not be a global function.
<?php
function fetch(){
echo 'Hello world!';
}
fetch();
No.
(Short of recompiling the PHP binary)
This is more of a function of the IDE than the actual language... Some IDEs may give you that ability... I don't even know if recompiling the PHP binary (as Alan Storm suggested) would help since sometimes the stuff is hardcoded into the IDE / use the PHP docs online
For completeness sake: Normally, no, this can not be done. However: this can be done using a PECL extension called "runkit".
Runkit is described as "For all those things you probably shouldn't have been doing anyway", and allows you to basically tear out the innards of PHP from within PHP itself. Replacing built-in functions, undefining constants, unloading classes - suddenly everything is possible. And you should really question what you are doing if you ever feel you need it - odds are what you are doing violates some principles that are there for very good reasons, you just don't know them yet. I've never found a situation where using Runkit was a genuinely Good Idea.
Oh, in order to remove built-in functions you'll specifically need to enable this capability in your php.ini
(have fun!)
I'm new in this site. I want to ask about PHP programming. How do we can handle deprecated function in PHP. I want to redirect it to my new function. As we know, ereg function has been deprecated in PHP 5.3.0 and recommended to preg_match (posix to PCRE). But, when we wrote a lot of code with ereg function, do we have to change it manually? I want a solution like this.
function ereg($pattern, $string, &$array) { return preg_match('#'.$pattern.'#', $string, $array); }
The main problem is not the ereg function, but solution of handling deprecated function.
I've been searching in Google. Someone suggest to use override_function (using APD extension). But, this extension is hard to find (I need precompiled extension build for windows). Anyone can help me?
I'm sorry for my bad English. I hope you can understand.
The reason they tell you it is deprecated, and they don't remove it completely, is to give you time to update your code.
If you don't want to update your code, you can always just not upgrade your install of PHP. Or you can wait until a release of PHP is out were ereg() is removed completely, and use your above solution.
Other possible solutions include doing a search/replace for all ereg calls, and replacing it my_ereg, which could be the function you defined above.
Also:
if(!function_exists("ereg")){ .... }
Define the function inside of the if statement that checks if the function already exists. This will make the transition smoother.
But all in all, the purpose of deprecation is to give developers time to update their code and stop using all of the deprecated functions before they remove it completely from the code base.
I believe some call it 'Maintenance'.
You could always use the function_exists function.
if(!function_exists('ereg'))
{
function ereg($pattern, $string, &$array)
{
return preg_match('#'.$pattern.'#', $string, $array);
}
}
Using this method would allow it to work in all version as if it is deprecated but still able to be used it will use the function but once it has been removed from php it will be able to use your user defined function.
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.
Some examples:
Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php
if ( count($arrayName) ) // handles $arrayName being unset or empty
Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...
Apply liberally for fun and profit:
Iterators in foreach loops. There's almost never a wrong time.
Design around class autoloading. Use spl_autoload_register(), not __autoload(). For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.
Typehint everywhere. Use assertions for scalars.
function f(SomeClass $x, array $y, $z) {
assert(is_bool($z))
}
Output something other than HTML.
header('Content-type: text/xml'); // or text/css, application/pdf, or...
Learn to use exceptions. Write an error handler that converts errors into exceptions.
Replace your define() global constants with class constants.
Replace your Unix timestamps with a proper Date class.
In long functions, unset() variables when you're done with them.
Use with guilty pleasure:
Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.
Use output buffers for assembling long strings.
ob_start();
echo "whatever\n";
debug_print_backtrace();
$s = ob_get_clean();
Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:
Magic methods (__get, __set, __call)
extract()
Structured arrays -- use an object
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
ini_set('display_errors', '1');
error_reporting(E_ALL);
Never use automagic. Stuff like autoLoad may bite you in the future.
Always require dependent classes using require_once. That way you can be sure you'll have your dependencies straight.
Use if(isset($array[$key])) instead of if($array[$key]). The second will raise a warning if the key isn't defined.
When defining variables (even with for cycles) give them verbose names ($listIndex instead of $j)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.
Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.
The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.
Make liberal use of === over ==. For instance:
if (array_search('needle',$array) == false) {
// it's not there, i think...
}
will give a false negative if 'needle' is at key zero. Instead:
if (array_search('needle',$array) === false) {
// it's not there!
}
will always be accurate.
See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.
There are a few things I do in PHP that tend to be PHP-specific.
Assemble strings with an array.
A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)
Array constants are nifty for implementing named parameters to functions.
Enable NOTICE, and if you realy want to STRICT error reporting. It prevents a lot of errors and code smell: ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);
Stay away from global variables
Keep as many functions as possible short. It reads easier, and is easy to maintain. Some people say that you should be able to see the whole function on your screen, or, at least, that the beginning and end curly brackets of loops and structures in the function should both be on your screen
Don't trust user input!
I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (Zend) with a solid javascript library (Dojo) and it's changed the way I work forever (in a good way, I think).
The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.
In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.
Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.
For some standalone tools worth using, see also:
Smarty (template engine)
ADODB (database access abstraction)
Declare variables before using them!
Get to know the different types and the === operator, it's essential for some functions like strpos() and you'll start to use return false yourself.