PHP tips
PHP TIPS
PHP Hypertext Preprocessor is a tool for making dynamic websites. Outside this Wiki, countless tips can be found in the comments section of the official php manual in the reference pages for each function. Here's a few little PHP tips and tricks.
Making your first cut'n paste script work
The first thing people usually do when the experiment with php, is that they get a piece of php script from the web and try to use it. So here's how to make that first piece of code to work:
- Change the file permissions so that your webserver can use it.
- Make sure that the php-code starts with <?php, because sometimes just the basic <? doesn't work (or at least in my configuration)
- Make sure that the file extension is .php, not .php3, .php4 or .phtml. A lot of these old filenames won't work with modern apache web servers.
Creating larger pages with $variables
The first few pages work well by just by putting the code where you needed in the HTML-page. However,when your scripts grow bigger, it gets messy when you mix php and html. I my opinion, the easiest way is to put the PHP-code code at the beginning of the file and the HTML in the end.
The data that your great script has generated should be placed in string-type variables. For example: $pagetop, $list, $pageend and $menu. So now you can put all the generated data to those variables and use them in the HTML-part of you file by just putting <?php echo $pagetop; ?> in the according place.
By doing this you can easily edit the PHP-scipt and the HTML part of your page without mixing the two so badly that you don't understand anything the next week .
FANCY TABLES
It is easy -- and it also looks really cool 8) -- to generate a table with alternating coloured rows from PHP. What you have to do is
- Declare a CSS style class for each background colour.
- Create an array with the background colours in the order you want them to appear in the table.
- Place some code in the loop which generates the table, to set a background colour for each row while recirculating the array.
The following code snippets should make it clear.
Defining CSS Classes (outside <? ?>)
- .DARKBG {background-color: #bbbbbb}
- .MIDDLEBG {background-color: #cc4ccc}
- .LIGHTBG {background-color: #dddddd}
Initialising the array (inside <? ?>)
- $backgrounds = array("LIGHTBG", "MIDDLEBG", "DARKBG", "MIDDLEBG");
Building up the table (inside <? ?>)
- foreach ($foo as $i => $j) {
- array_push($backgrounds, ($bg = array_shift($backgrounds));
- echo "<TR CLASS=\"$bg\">";
- echo "<TD>$i</TD><TD>$j</TD>";
- echo "</TR>\n";
- };
Explanation
Each time around the loop (here I've used a foreach but it could be any kind of loop), the array_shift (in the innermost brackets, so it gets evaluated first) causes a variable $bg to be set to the first element in $backgrounds and the others to be shifted down a place. Then, this is pushed onto the tail end of the shortened array by the array_push. So the whole array just gets recirculated, each time a value is read from the beginning it is moved to the end. As the array_push and array_shift functions do not care about the length of the array, you could go through a whole rainbow of colours, or you could just alternate white and coloured rows.
Note that if you want to use more than one table in your page, and you want them all to start on the same colour, you will have to re-create the array between finishing one table and starting the next. This is because the array actually gets altered each time we go around the loop.
HIT COUNTER
This code can be used to generate a simple hit counter. It is deliberately kept as simple as possible, so as to make it easier to customise.
<?php
$filename = "count.dat"; # must be different for each page
$num_hits = 0;
if ($fh = fopen("$filename","r")) { # open the file
$data = fscanf($fh, "%d"); # read number from file
$num_hits = $data[0];
$num_hits++; # add one to count
fclose($fh);
if ($fh = fopen("$filename","w")) { # write updated value
fwrite($fh, "$num_hits\n"); # back to file
fclose($fh);
};
};
echo "$num_hits"; # display count
?>
Explanation
The file specified in $filename must exist and must have permissions 666; it holds the counter value. Start with just "1" on a line by itself.
The file is opened for reading, and a decimal integer value is read using the fscanf function. It is then incremented and written back to the file. before being echoed to the screen.
The script only produces a number. You probably will want to declare a CSS class for the counter, and surround the PHP block with <SPAN> ... </SPAN> tags.
To repeat the count elsewhere on the page, use
<?php
echo "$num_hits";
?>
Configuration Tricks and Traps
Here are some common pitfalls or trickies. Also, go take a look at this for a more comprehensive look at security issues in PHP.
The register_globals flag (a php.ini config option)
If set to true, all GET, POST, FILE, and COOKIE variables will be registered as global variables. That is, if you called the url index.php?page=home the script would have the variable $page available, with the value 'home'. However, with register_globals off (the way it should really be, for security) $page would not be available. Instead, you would use $_GET['page'] or $HTTP_GET_VARS['page'] (the first for any version of php beyond about 4.1; the second for older versions).
The allow_short_open_tags option
If set to true, <? is a legitimate way of starting a php block. This also means that you can use the short echo syntax: <?=$var ?> will output the value of $var.
Unfortunately, the shorts tags are a bad idea if:
- You are mixing scripting languages. Different languages use different tags, but often use the <? prefix.
- You have xml content. PHP will choke on the <?xml declaration if you are allowing the short tags; it reads it as a php command "xml", which of course doesn't work, so spews a parse error.