PHP Hints
PHP is an embedded scripting language, where the scripts are directly built into hypertext files and are executed on a web server. A PHP program utilizes the tags <?php, ?>. An interpreter processes commands between this pair of tags and forms the final file and is then served to a web browser.
One of the strongest points of PHP (which at the same time is its weakest point) is that PHP is very easy to learn.PHP is an embedded scripting language, where the scripts are directly built into hypertext files and are executed on a web server. A PHP program utilizes the tags <?php, ?>. An interpreter processes commands between this pair of tags and forms the final file and is then served to a web browser.
One of the strongest points of PHP (which at the same time is its weakest point) is that PHP is very easy to learn. It attracts many people. However, despite its seeming simplicity, it’s not so easy to learn how to use this language in an effective and correct way. In this article I will show you some different examples of useful PHP hints, which are usually ignored by novice programmers.
1. The variable of variables
Dynamically changed variable names (changed during operation of a script) can be very convenient to use in a script. Here is an example of what I mean:
This example assigns the value “hello” to a variable with the name ‘a’: $a = ’hello’;
In this next operation, we assign the value of the variable ‘a’, the value “world”: $$a = ’world’;
In effect, this is the same as this statement: $hello = ‘world’;
We can display the output from these variables with either of the following:
<?php echo $a.’ ‘.$$a; ?>
<?php echo $a.’ ‘.$hello; ?>
Both statments produce the output ‘hello world’.
The same technique can be applied to arrays. You will have to use a little bit more complicated syntax:
${$a[1]} which stores a value in the variable ‘$a[1]’.
${$a}[1] which address a unit of 1 array with a name which is stored in $a.
2. Transmission to a script of parameters to start from the shell (command line)
If you happen to be working directly on a machine that has PHP installed, it is not always necessary to view the output of your scripts through a web server. Here are some examples to transfer parameters to a script from the command line.
Example 1:
You can read arguments provided directly from the command line. The file.php used in the command line below contains the following segment of PHP code:
<? echo $argv[1].”
”. $argv[2]; ?>
To invoke the PHP from a command line use:
command line prompt> php file.php 10 20
The ‘$argv[1]’ and ‘$argv[2]’ will be parsed by the PHP interpreter to show this output. The values ‘10’ and ‘20’ are taken as arguments to the command line invocation of the script. Below is an example of the output:
X-Powered-By: PHP 4.0.5
Content-type: texthtml
10
20
Example 2:
You can provide a querystring to a command line, the same as a browser would submit from a form or a link:
command line prompt>php -f file.php &a=10&b=20
In this example, the file.php contains this fragment of PHP code:
<? echo $a.”
”. $b; ?>
Here the ‘$a’ and ‘$b’ variables are parsed by the PHP interpreter from the querystring. Again the values ‘10’ and ’20’ are taken as arguments to the command line invocation of the script, but we have assigned them specific variables. The command line used to run the script no longer depends on the order of the arguments provided to the script.
3. The Ternary Operator
In PHP, as well as in C, there is something called a ternary operator ‘? :’. This is a short-hand expression for the IF-THEN-ELSE logic, which can be read as ‘IF EXPRESSION ? THEN EXPRESSION : ELSE EXPRESSION’.
$res = (expr1) ? (expr2) : (expr3);
The result of this statement is the value of ‘expr2’ if ‘expr1’ is true, or ‘expr3’ if ‘expr1’ is false. This has the same result as the following, but is much shorter:
if (expr1) $res = (expr2); else $res=(expr3);
Here is another example: <?php echo ‘>option value=”’ .$id . ’”’ . ( $id==$current_id ? ’selected’ : ’’ ) . ’> ’ . $name . ’</option>’; ?>
This statement outputs one of the variants for the dropdown menu. If the current output ‘$id’ is equal to ‘$current_id’ then that option is selected in the menu.
4. Simplified syntax of the ECHO command
The ECHO command also has a short hand syntax. Here is an example of the standard syntax for the echo command:
<?php echo ‘var1: ’ . $var1; ?>
The short hand syntax for this statement is:
<?= ‘var1: ‘.$var1;?>
Notice that the PHP tag is also shortened and the opening ‘php’ is omitted from the tag.
5. Displaying HTML code fragments
If it is necessary to display a big fragment of the HTML code, you don’t need to output it with the help of a set echo or print. There is a syntax that parallels the “here printing” syntax from Perl. It allows the display of whole blocks of output, framing their instructions with a terminal label (< < <).
<?php
$version = phpversion(); $valstr = “Example of HerePrinting\n”; print <<<mylabel
<b>PHP’s New Features</b>
<ul>
<li>ISAPI support
<li>COM support on Win32
<li>Java and servlets support
$valstr
Tested on PHP version $version
mylabel; >
?>
In this example, everything framed between ‘<<<mylabel’ and ‘mylabel;’ will be printed.
6. Downloading files by HTTP
You can use PHP to get the access to the files located on remote Web servers from within your scripts by using sockets. Socket operations are performed at the time the script is run. The result of a socket operation is read out just the same way as a file handle.
Generally when we open a socket, we send a GET request that describes the document we want with a URL, then we read the answer from the socket. The answer consists of two things: the response header and the body of a document. Since we want to obtain a file, the body of the document is more important to us. The body is separated from the response header string by a carriage return and a newline character: “\r\n”.
In the following example you may edit the variables ‘$host’, ‘$file’ and ‘$localfile’, to customize them for the remote request server, URL and the name of the local file to store the response.
<?php
$host=”mywebhost.com”;
$file=”/home/my/dir/myfile.zip”;
$localfile=”savedfile.zip”;
// opened the connection
$fp = fsockopen($host, 80, &$errno, &$errstr, 30);
// transferring the request
fputs($fp,”GET “.$file.” HTTP/1.0
HOST: “.$host.”\n\n”);
// read everything, until the end of the header will be shown (i.e. the beginning of the document)
while(fgets($fp,2048)!=”\r\n” && !feof($fp));
unset($buff);
// read the document in the variable
while(!feof($fp)) $buff.=fread($fp,65536);
// close the socket
fclose($fp);
echo “Download fine, size “.strlen($buff).” bytes.”; flush();
// use the downloaded file (in the variable) in the correct way…
$f=fopen($localfile,”wb+”);
fwrite($f,$buff,strlen($buff));
fclose($f);
?>
Please note not to forget to read the binary data from the socket using the ‘fread’ functions, and the header text using the ‘fgets’ function. To save the file, open it in the “wb” mode (‘b’ opens the file for writing binary data).
7. How to transform IP into the number integer and vice versa
Sometimes it is necessary to transform IP addresses to a numeric integer to occupy less space. An IP address stored as a string “255.255.255.255” occupies 15 bytes, but when stored as a number it occupies four bytes. It is possible to write this number into a database or use it as a value in a PHP script.
There are intrinsic functions ‘ip2long’ and ‘long2ip’ in PHP 4, and their syntax is given below. If you want to use the results of these functions to store IP addresses as numeric data in an SQL database, use the INT data type for your fields.
int ip2long (string ip_address)
string long2ip (int proper_address)
If you do not have PHP 4 you can use the functions below as sysnonyms for the built-in conversions.
function ip2int($ip) {
$a=explode(“.”,$ip);
return $a[0]*256*256*256+$a[1]*256*256+$a[2]*256+$a[3];
}
function int2ip($i) {
$d[0]=(int)($i/256/256/256);
$d[1]=(int)(($i-$d[0]*256*256*256)/256/256);
$d[2]=(int)(($i-$d[0]*256*256*256-$d[1]*256*256)/256);
$d[3]=$i-$d[0]*256*256*256-$d[1]*256*256-$d[2]*256;
return “$d[0].$d[1].$d[2].$d[3]”;
}
These functions will transform IPs only as positive numbers.
Please note if you are working with an SQL database the conversion of IP addresses to numbers is faster if done with the SQL functions, rather than PHP. I have given the syntax for the SQL below:
INET_ATON (string ip_address)
INET_NTOA (int proper_address)
8. Program optimization in PHP
Any PHP script can be optimized without changing the algorithm. Due to the similar optimization it is possible to increase the speed of script operations changing the syntax only.
Example 1:
The syntax of PHP allows use of the variables directly in text string.
$x=”test $test”;
This can be convenient while writing programs but can slow down performance. Using strict concatenation of strings with variables can increase productivity up to 25 – 40% (at least in this example).
$x=”test”.$test;
Example 2:
Variables with short names (no longer than seven characters) can speed up execution of your programs by 15% (not to mention save you a lot of typing).
Example 3:
Use quotes in associative array names. The syntax of PHP allows you to define associative arrays (or hashes for those familiar with Perl or C) by specifying a key either with or without quotes.
$test[“a”]; $test[“b”]; $test[“c”]; $test[“d”]; $test[“e”];
$test[a]; $test[b]; $test[c]; $test[d]; $test[e];
Tests have shown that the associative array without quotes worsens productivity 30% – 40%. For multi-dimensional arrays the difference is even more appreciable.
Example 4:
PHP supports regular expressions of POSIX standard (ereg *) and Perl (preg *) – oriented. Perl oriented regular expressions perform faster, especially in cases where the expression is evaluated multiple times.
eregi(“te+st”,$text);
preg_match(“/te+st/im”,$text);
These two statements are equivalent, but the ‘preg_match’ will perform faster
Example 5:
Two functions are used in PHP to quantify units in the array: count() and sizeof(). As it is written in the PHP Manual, these functions are synonyms (aliases). Nevertheless, tests show that count() works appreciably slower than its synonym (~15%), so try to use function sizeof(). The difference in speed can be noticeable on large scale arrays.
Finally, if you find that it is hard for you to understand the given subtleties and nuances of programming, please write to us and we’ll perform your tasks with peak efficiency and in a minimum amount of time.
The above opportunities will undoubtedly be useful to you, and in some cases even appear irreplaceable. We share our own tips and secrets as we welcome competition, but also are confident that our experts are top notch. If it is necessary for you to solve any problems in programming, please feel free to address us for qualified help.
Jules is the lead programmer of AdultWebware Corporation with Internet programming experience totaling over four years. Jules can be reached at jules@adultwebware.com.