This is a discussion on PHP Tips and Tricks within the PHP Programming forums, part of the Web Development category; PHP Tips and Tricks These are some common PHP and MySQL coding tips. I believe these are good do's ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| PHP Tips and Tricks These are some common PHP and MySQL coding tips. I believe these are good do's and don'ts, that most experienced coders would agree with, and not just my opinions. Note: in my examples, I'm using the new arrays ($_GET/$_POST/$_COOKIE/$_SERVER) because I'm assuming that you're using at least PHP 4.1.0. If you have an older version, then use the old, longer arrays ($HTTP_GET_VARS/$HTTP_POST_VARS/$HTTP_COOKIE_VARS/$HTTP_SERVER_VARS). But you should upgrade because of the file-upload vulnerability in unpatched versions prior to 4.1.2. That's a tip by itself!
__________________ Thanks & Regards Sabari... |
| Sponsored Links |
| |||
| PHP - register_globals First and foremost, I believe, is the use of register_globals. For those of you who don't know, register_globals allows you to access variables from forms and URLs (such as file.php?var=foo) as $var in your script -- "magically" created global variables. Unfortunately, this old method continues to be used in most tutorials/examples. The PHP developers seem to have realized that register_globals was a bad idea, though. They discuss Using Register Globals in the PHP manual and recommend turning them off in php.ini: Quote: Note that register_globals is going to be deprecated (i.e., turned off by default) in the next version of PHP, because it often leads to security bugs. ... You should do your best to write your scripts so that they do not require register_globals to be on In fact, as of PHP 4.2.0, register_globals is now off by default on new PHP installations. By writing code that relies on register_globals being on, you risk having that code not work on some systems! Wouldn't you rather use the preferred method of accessing variables and have your code work on all PHP installations? The proper way to access these variables is via their respective arrays. So instead of $var, in the above example, you should use $_GET['var']. Similarly, use $_SERVER['HTTP_USER_AGENT'] instead of just $HTTP_USER_AGENT. The main arrays are $_GET, $_POST, $_COOKIE, and $_SERVER, depending on where the variable came from, obviously. You can read more about them, and a couple of others, here and here in the manual. Please access your variables via these arrays!
__________________ Thanks & Regards Sabari... |
| |||
| magic_quotes, addslashes(), and stripslashes() magic_quotes_gpc, when on, automatically adds slashes to all GET/POST/COOKIE data so that you don't need to use addslashes() before using GET/POST/COOKIE data in MySQL queries, etc. (e.g. with magic_quotes_gpc OR addslashes(), I'm becomes I\\'m). Well, magic_quotes_gpc is no convenience and just complicates things! Since magic_quotes_gpc can be on or off, you don't know whether to use addslashes() or not. You don't want to use addslashes() when magic_quotes_gpc is on because you'll add too many slashes (e.g. I'm becomes I\\\\'m), which is bad. Use addslashes() if magic_quotes_gpc is off, and don't if it's on (you can find out its setting with get_magic_quotes_gpc()). But you can't use the same code all the time. One workaround is something such as: if (!get_magic_quotes_gpc()) { $txt = addslashes($txt); } Things are further complicated if you want to first manipulate text that has had magic_quotes_gpc applied. You then have some text that has slashes added and some that doesn't. The effect of this is: some text will be wrong whether you use addslashes() or not. It's easiest to turn off magic_quotes_gpc, which I recommend, and use addslashes() manually all the time and not worry about the wrong amount of slashes. This is what it says in the recommended php.ini: Quote: magic_quotes_gpc = Off Input data is no longer escaped with slashes so that it can be sent into SQL databases without further manipulation. Instead, you should use the function addslashes() on each input element you wish to send to a database. As I said above, if you use addslashes() when magic_quotes_gpc is on, too many slashes will be added. For inserting I'm into MySQL, you want it to be I\\'m (and it will come out as I'm). Using addslashes() with magic_quotes_gpc, however, will give you I\\\\'m. THAT will come out of MySQL as I\\'m, which is not the original text. Most people assume that you are supposed to use stripslashes() when retrieving data from MySQL because otherwise they have slashes in their text. But that's fixing a problem that should never have occurred. If you have to use stripslashes() on text from your database, it's because you added too many slashes when you inserted it. You should never have to use stripslashes() on text from your database. If you do, you need to fix the problem at the source, rather than after the fact. You can turn off magic_quotes_gpc in php.ini or like this in a .htaccess file: <IfModule mod_php4.c> php_flag magic_quotes_gpc off </IfModule> If that's not possible, you can put the following code at the top of all your files (in a require or include). It will strip the slashes that magic_quotes_gpc added, virtually turning it off. function strip_magic_quotes($arr) { foreach ($arr as $k => $v) { if (is_array($v)) { $arr[$k] = strip_magic_quotes($v); } else { $arr[$k] = stripslashes($v); } } return $arr; } if (get_magic_quotes_gpc()) { if (!empty($_GET)) { $_GET = strip_magic_quotes($_GET); } if (!empty($_POST)) { $_POST = strip_magic_quotes($_POST); } if (!empty($_COOKIE)) { $_COOKIE = strip_magic_quotes($_COOKIE); } }
__________________ Thanks & Regards Sabari... |
| |||
| ereg vs preg When it comes to the regular expression functions, ereg* and preg*, the preg functions are the clear choice. The preg functions are generally twice as fast as their ereg counterpart. They also support more advanced regular expression operations. I can't think of any reason why you would need to use the ereg functions. preg manual page and pattern syntax (long and confusing but pretty good).
__________________ Thanks & Regards Sabari... |
| |||
| PHP tags I recommend always using the full PHP open tag, <?php, rather than the short one, <?. This means also that instead of <?=$var?>, it's better to use the full <?php echo $var?>. Using the full open tag ensures that your code will work on all PHP installations, regardless of the short_open_tag setting.
__________________ Thanks & Regards Sabari... |
| |||
| Alternative control structure syntax I highly recommend staying away from the if (): ... endif; style syntax and sticking with curly braces, if () { ... }. This is the preferred syntax and it makes your code easier to read.
__________________ Thanks & Regards Sabari... |
| |||
| error_reporting You should probably test your code with error_reporting set to at least E_ALL & ~E_NOTICE (all errors except notices) so that you aren't suppressing errors that should be fixed. error_reporting can be set in php.ini or with the error_reporting() function.
__________________ Thanks & Regards Sabari... |
| |||
| Line breaks People want to know how they can retain textarea line breaks in HTML. You should store text in the database in its original format (e.g. with just newlines) and then use nl2br() to convert newlines to HTML <br /> tags on display. That's all good, except for one problem with nl2br(): it doesn't seem to convert \r newlines (edit: this has now been fixed in PHP 4.2.0). Windows uses \r\n newlines; *nix uses \n; Mac uses \r. nl2br() works correctly on text from Windows/*nix because they contain \n. However, if you get text from a Mac, nl2br() will not convert its newlines (again, fixed in PHP 4.2.0). To remedy this, I use the following bit of code to convert \r\n or \r to \n before inserting it into the database. It won't hurt anything and ensures that nl2br() will work on the \n only newlines on display. Also, it has the side effect of saving 1 byte in the database per newline from Windows (by storing only \n instead of \r\n). $txt = preg_replace('/\r\n|\r/', "\n", $txt);
__________________ Thanks & Regards Sabari... |
| |||
| Strings 1) As a finesse thing, I use single quotes around strings whenever possible (e.g. strings that don't contain variables, single quotes, \n, etc.). This is supposed to make less work for the PHP parser. 2) When an array variable isn't in a string, put quotes around string-literal keys so they are not regarded as constants: // OK echo $row[$key]; // Wrong, unless key is a constant echo $row[key]; // Right echo $row['key']; // OK, since it's in a string echo "Text: $row[key]"; 3) Remember, you can break out of PHP mode for large sections of HTML. This is faster than echo'ing and you don't need to escape quotes.
__________________ Thanks & Regards Sabari... |
| |||
| Quotes around numeric data in queries For numeric columns in MySQL, you shouldn't put quotes around any of their values in queries. As our resident database guru, MattR, says, "that is very non-standard and will only work on MySQL." But if it's unknown data, how do you know that it's numeric and not letters that will cause an error? You can make sure that only a number is used in the query by first type-casting the data as int (or float for decimal numbers): // If id is being passed in the URL $id = (int) $_GET['id']; $r = mysql_query("SELECT * FROM table WHERE id=$id"); Then even if id is set to "abc," the worst that can happen is a 0 will be used in the query. No quotes; no error.
__________________ Thanks & Regards Sabari... |
| |||
| Variable variables A variable variable looks like this: $$var So, if $var = 'foo' and $foo = 'bar' then $$var would contain the value 'bar' because $$var can be thought of as $'foo' which is simply $foo which has the value 'bar'. Variable variables sound like a cryptic a useless concept, but they can be useful sometimes. For example, if we have a configuration file consisting of configuration directives and values in this format: foo=bar abc=123 Then it is very easy to read this file and create corresponding variables: <?php $fp = fopen('config.txt','r'); while(true) { $line = fgets($fp,80); if(!feof($fp)) { if($line[0]=='#' || strlen($line)<2) continue; list($name,$val)=explode('=',$line,2); $$name=trim($val); } else break; } fclose($fp); ?> Along the same lines as variable variables, you can create compound variables and variable functions. <?php $str = 'var'; $var_toaster = "Hello World"; echo ${$str.'_toaster'}; $str(); // Calls a function named var() ${$str.'_abc'}(); // Calls a function named var_abc() ?>
__________________ Thanks & Regards Sabari... |
| |||
| Connection Handling PHP maintains a connection status bitfield with 3 bits: o 0 - NORMAL o 1 - ABORTED o 2 - TIMEOUT By default a PHP script is terminated when the connection to the client is broken and the ABORTED bit is turned on. This can be changed using the ignore_user_abort() function. The TIMEOUT bit is set when the script timelimit is exceed. This timelimit can be set using set_time_limit(). <?php set_time_limit(0); ignore_user_abort(true); /* code which will always run to completion */ ?> You can call connection_status() to check on the status of a connection. <?php ignore_user_abort(true); echo "some output"; if(connection_status()==0) { // Code that only runs when the connection is still alive } else { // Code that only runs on an abort } ?> You can also register a function which will be called at the end of the script no matter how the script was terminated. <?php function foo() { if(connection_status() & 1) error_log("Connection Aborted",0); if(connection_status() & 2) error_log("Connection Timed Out",0); if(!connection_status()) error_log("Normal Exit",0); } register_shutdown_function('foo'); ?>
__________________ Thanks & Regards Sabari... |
| |||
| Don't use a regex if you don't have to PHP has a rich set of string manipulation functions - use them! BAD: <? $new = ereg_replace("-","_",$str); ?> GOOD:<? $new = str_replace("-","_",$str); ?> BAD: <? preg_match('/(\..*?)$/',$str,$reg);?> GOOD:<? substr($str,strrpos($str,'.')); ?>
__________________ Thanks & Regards Sabari... |
| |||
| Use References if you are passing large data structs around to save memory There is a tradeoff here. Manipulating references is actually a bit slower than making copies of your data, but with references you will be using less memory. So you need to determine if you are cpu or memory bound to decide whether to go through and look for places to pass references to data instead of copies.
__________________ Thanks & Regards Sabari... |
| |||
| Use Persistent Database connections Some database are slower than others at establising new connections. The slower it is, the more of an impact using persistent connections will have. But, keep in mind that persistent connections will sit and tie up resources even when not in use. Watch your resource limits as well. For example, by default Apache's
__________________ Thanks & Regards Sabari... |
| |||
| Using MySQL? Check out mysql_unbuffered_query() Use it exactly like you would mysql_query(). The difference is that instead of waiting for the entire query to finish and storing the result in the client API, an unbuffered query makes results available to you as soon as possible and they are not allocated in the client API. You potentially get access to your data quicker, use a lot less memory, but you can't use mysql_num_rows() on the result resource and it is likely to be slightly slower for small selects.
__________________ Thanks & Regards Sabari... |
| |||
| Adding an extension Problem You need PHP's built-in ftp functions for the ultra-cool script you are writing, but your service provider does not have PHP compiled with the --enable-ftp option. Solution If you have a shell account on a system with the same operating system as your web server, grab the PHP source tarball and build using: --with-apxs --enable-ftp=shared You can check which flags your provider used by putting a phpinfo() call in a script on your server. <?phpinfo()?> Once compiled, you will find a "modules/ftp.so" file which you can copy to your web server and enable either by putting: extension=ftp.so in your php.ini file or by adding this to the top of your script: <?php dl("ftp.so") ?>
__________________ Thanks & Regards Sabari... |
| |||
| Cookie Expiry Problem Short expiry cookies depend on users having their system clocks set correctly. Solution Don't depend on the users having their clocks set right. Embed the timeout based on your server's clock in the cookie. <?php $value = time()+3600 . ':' . $variable; SetCookie('Cookie_Name',$value); ?> Then when you receive the cookie, decode it and determine if it is still valid. <?php list($ts,$variable) = explode(':',$Cookie_Name,2); if($ts < time()) { ... } else { SetCookie('Cookie_Name',''); } ?>
__________________ Thanks & Regards Sabari... |
| |||
| HTTP Client/Server Request/Response HTTP is a simple client/server protocol with stateless request/response sequences. The Client HTTP Request 7 possible HTTP 1.1 request types: GET, PUT, POST, DELETE, HEAD, OPTIONS and TRACE. Any number of HTTP headers can accompany a request. GET /filename.php HTTP/1.0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* Accept-Charset: iso-8859-1,*,utf-8 Accept-Encoding: gzip Accept-Language: en Connection: Keep-Alive Host: localhost User-Agent: Mozilla/4.77 [en] (X11; U; Linux 2.4.5-pre4 i686; Nav) The Server HTTP Response HTTP/1.1 200 OK Date: Mon, 21 May 2001 17:01:51 GMT Server: Apache/1.3.20-dev (Unix) PHP/4.0.7-dev Last-Modified: Fri, 26 Jan 2001 06:08:38 GMT ETag: "503d3-50-3a711466" Accept-Ranges: bytes Content-Length: 80 Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Content-Type: text/html
__________________ Thanks & Regards Sabari... |
| |||
| Returning References Passing arguments to a function by reference <?php function inc(& $b) { $b++; } $a = 1; inc($a); echo $a; ?> Output: 2 A function may return a reference to data as opposed to a copy <?php function & get_data() { $data = "Hello World"; return $data; } $foo = & get_data(); ?>
__________________ Thanks & Regards Sabari... |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| C# .Net Tips & Tricks | oxygen | C# Programming | 83 | 09-24-2008 02:20 AM |
| SAP Tips & Tricks | leoraja8 | Operating Systems | 0 | 03-29-2008 12:11 AM |
| BlueTooth tips and tricks | devarajan.v | Mobile Software Development | 52 | 03-13-2008 09:46 PM |
| .NET tricks & Tips | Karpagarajan | VB.NET Programming | 1 | 04-23-2007 08:17 AM |
| SEO Tips & Tricks | spid4r | Search Engine Optimization | 0 | 03-08-2007 11:03 PM |