Search This Blog

Monday, September 13, 2010

Future of PHP

The fact that PHP is an open source programming language makes a great case against its competitors. It has a cheap, fast, reliable and widely supported environment to run in, therefore it is mainly used in standard web deployment, not only large enterprises. PHP became the most popular language on the Internet in 2002, and that with next to $0 marketing costs. None of PHP's main competitors – ASP, Perl and JavaScript – have such a great community to support them. On the other hand, commercial languages such as ColdFusion offer a lot more components, tools and support, but that comes with a lot of money also.
Why should you choose PHP? If you're a beginner, PHP is excellent for you. It is really easy to understand, and you can figure out most things on your own. PHP documentation isn't the most detailed one, but it can give you some information on what you're trying to find out. If you still cannot find what you're looking for, a search on the Internet will be worthwhile. There are a lot of tutorials and code examples, and most certainly you will find out more than you expected. Other languages, on the other hand, have a detailed documentation – even though it is sometimes too detailed and you can't understand anything from it – so you probably won't have to do any additional research on the Internet.
If you're an intermediate or advanced programmer, you may like PHP because there are a lot of things you can do with it. Flexibility and portability are two essential attributes of PHP. You can run it or almost every operating system in the world, and you can modify it as you wish. Besides, at the end of the day, you will not have spent any money into doing so. Other languages rely on the fact that having a lot of components and tools cover for their lack of versatility towards new ones.
When it comes to support, PHP is known for its excellent global community, which helps out people looking for answers. Alternatively, commercial languages provide support from well-trained personal who will answer you quickly, but then again the costs are much higher.
You will find both praises and critics to PHP. The best way to go is to try it for yourself. Just start fresh without taking into consideration other people's comments, and figure it out on your own.

PHP Database Manipulation

One of the defining features of PHP is the ease with which you can connect to and manipulate databases. PHP implements functions for connecting to a wide range of databases systems: MySQL, Oracle, MSSQL, Interbase, dBase, and many more. While there are many commercial database systems which cost thousands of dollars and provide thousands of components, the Internet community provides solutions for low-budget users as well. MySQL, for example, doesn't require you to purchase a license if you don't use it for commercial activities.
Most of the manipulating of any database is done while using SQL, which stands for Structured Query Language. This provides standard syntaxes by which different types of database can be queried. While there are a lot of extensions to SQL implemented by database systems, and some queries could work on a system but fail on another one, all of them incorporate some standard manipulating statements.
The way PHP talks to the database is simple. First you need to connect to the database system, which runs as a daemon (service for Windows) in the background. In order to do this, you must have appropriate permissions to connect to the database server from its owner. While you can always install and configure a database system on your own computer for starters, when it comes to hosting a web-site you must talk to a hosting company. They will open an account for you, and give you the information on how to connect to the database server.
Many hosting companies use MySQL, so we'll focus on using this database system. First, you must use the "mysql_connect()" function along with the server's IP, the username and the password required to connect to the server. After you connect, you can start running SQL statements as you like. Don't forget that to close the connection using "mysql_close()". You either must do this everytime you want to manipulate the database, or you use a persistent connection. This kind of connection is implemented when using the Apache web-server, and tells Apache not to terminate the connection after your script stops executing even if you call "mysql_close()". Instead, the connection is left active, waiting for another process to call mysql_pconnect(). So, using this function, you will skip the time required for your computer to connect to the database server.
if(!mysql_connect("localhost", "bob", "secret")) //tries to connect to the database server
die("Unable to connect to the database server!"); //terminates the script, and outputs the error
Depending on the hosting services, you can have access to one or more databases. But before you start changing data, you must also connect to the database of your choice. Selecting a database to work with is also accomplished using a simple function:
mysql_select_db("test_db") or die("Error when selecting the database!");
While we can treat the errors using the "die()" function, and stop the script if something bad happens, sometimes we might want to output more detailed information on the error. Whenever an operation fails, MySQL sets an error number and an error string, so we just have to read it:
if(!mysql_connect($db_ip, $db_user, $db_pass))
die("MySQL Error: " . mysql_error()); //stops the script if unable to connect to the database, and outputs the MySQL error message
All of the database manipulation is done thru SQL statements (also known as queries), which range from basic statements used to insert, modify or delete data in a table to complex statements used to retrieve some particular data using specified filters. You can find a lot of documentation on SQL on the Internet. Here are some of the most important statements:
//creates a table using the specified fields
CREATE TABLE users
(id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
username VARCHAR(20),
password VARCHAR(12),
email VARCHAR(20)
)
//adds a new record into the database
INSERT INTO my_table(id, username, password, email) VALUES (NULL, "bob", "secret", "bob@softwareprojects.org")
//modifies the password of the user "bob"
UPDATE my_table SET password = "very secret" WHERE username = "bobo"
//retrieves the email address of the user "bob"
SELECT email FROM users WHERE username = "bob"
To execute these queries, you must call the "mysql_query()" function. The result of this function is a resource that will be used with other functions, in order to access the information returned by the query.
$sql_result = mysql_query("SELECT password FROM users WHERE username='Bob'")
or die("Error or running query: " .$mysql_error())
$row = mysql_fetch_array($sql_result, MYSQL_NUM);
While it may seem that "mysql_fetch_array()" retrieves all the results from the query, you should know that it only returns one row at a time. After a call to this function, the internal index of $sql_result will be incremented by one, so the next time the next row will be retrieved, if there is any.
There are a lot of other built-in functions for MySQL, for a detailed explication of each one you should consult the PHP documentation.

PHP Sessions

Besides cookies, there is another way to pass information to different web-pages: sessions. A session-enabled page allocates unique identifiers to users the first time they access the page, and then reassociates them with the previously allocated ones when they return to the page. Any global variables that were associated with the session will then become available to your code. The difference between sessions and cookies is that a session can hold multiple variables, and you don't have to set cookies for every variable. By default, the session data is stored in a cookie with an expiry date of zero, which means that the session only remains active as long as the browser. When you close the browser, all the stored information is lost. You can modify this behavior by changing the "session.cookie_lifetime" setting in "php.ini" from zero to whatever you want the cookie lifetime to be.
PHP uses several functions to deal with sessions. Before you start the actual work with sessions, you must explicitly start a session with "session_start()". If you want sessions to start automatically, you must enable the "session.auto_start" setting in PHP's configuration file. This way a session will be initiated for every PHP document. After you have started a session, you have access to the session ID via the "session_id()" function. After you're done with the session, you can destroy it using "session_destroy()". The following script always assigns a new session ID:
session_start(); //starts or resumes a function
print "Your session ID is: " . session_id(); //displays the session ID
session_destroy(); //ends the session; comment this line and the browser will output the same session ID as before
While accessing the unique identifier is a good start, the main objective of a session is to hold the values of variables. You must register variables to a session using the "session_register()" function before you try to read them on a session-enabled page. Also, you should remember that when you register a variable to a session, and then change the variable's value, the altered value will be reflected in the session file. Finally, remember that "session_register()" requires you to pass as an argument the variable name, not the variable itself:
session_start();
if(isset($stored_var))
{
print $stored_var; //this will not be displayed the first time you load the page, because you haven't registered the variable yet!
}
else
{
$stored_var = "Hello from a stored variable!";
session_register("stored_var"); //don't do this: session_register($session_var)
}
As you can seen, you can test if a variable is assigned using the "isset()" function. While this works with all of the script's variables, to only check variables registered with a session you should use "session_is_registered()" function. You must again pass as an argument a string containing the variable name, and the function will return TRUE if the variable has been registered within the session.
session_start();
if(session_is_registered("stored_var"))
{
print $stored_var;
}
else
{
$stored_var = "Hello from a stored
variable!";

session_register("stored_var"); //don't do this: session_register($session_var)
}
As you've read before, "session_destroy()" is used to clean up the session variables, and end the session. However, "session_destroy()" does not destroy the session's variables, and they will remain accessible to the rest of the script in which "session_destroy()" is called.
session_start();
session_register("test");
$test = 12;
session_destroy();
print $test; // outputs 12
If you want to remove the registered variables, you need to use the session_unset() function. This destroys all variables associated with a session, both in the session file and within the script.
session_start();
session_register("test");
$test = 12;
session_unset(); //$test is destroyed
session_destroy();
print $test; //outputs nothing

PHP Cookies

During a complex project, there are times when you want to send data from one web-page to another. For example, in an e-commerce web-site, it is essential that you store the contents of a shopping cart while the user is browsing your site. In order to do this, there are two easy ways: you either use cookies or sessions.
Cookies are small amounts of data stored by the user's browser after a request from a server or script. While they are excellent from passing information from page to page, or even from visit to visit, cookies do have some limitations. For example, the maximum number of cookies from a host that can be stored by a browser is 20, and the maximum cookie size is 4KB. The main thing about cookies is that only the originating host can read the stored data, so the user's privacy is respected. Not only that, but the user can choose to be notified by the browser when accepting a cookie, and can even refuse some, or all of them. This is why you shouldn't rely on cookies to be an essential part of your web-site without first warning the user that you are using cookies.
Cookies consist of a name, value, expiry date, host and path information, and they end up to the user because they are send from the server thru an HTTP header. There are 3 ways a PHP script can access the cookie: using the environmental variable "$HTTP-COOKIE" – which holds all cookie names and values -, in a global variable "$cookie_name" (replace with the name, of course), or in the global array variable "HTTP_COOKIE_VARS["cookie_name"]" (again, replace "cookie_name" with the actual name of the cookie). Let's say we have a cookie called "visits" which holds the value 23, this is how you can output it to the web-browser:
print $HTTP_COOKIE; //outputs "visits=23"
print getenv("HTTP_COOKIER"); //outputs "visits=23"
print $visits; //outputs "23"
print $HTTP_COOKIE_VARS[visits]; //outputs "23"
To set a cookie with PHP, you can use the "header()" function, or the "setcookie()" function. While "header()" has a larger scope, and its main purpose is not to set a cookie, it will work just like "setcookie()". Using "header()", you write the cookie header yourself, while "setcookie()" is much more automated. If you don't know this already, always remember that the HTTP headers are automatically sent to the browser, so you must set a cookie before any output is sent to the browser:
//don't output anything before this…
header("visits=23; expires=Friday, 20-Aug-04 03:27:21 GMT; path=/; domain=softwareprojects.org");
setcookie("hits", 23, time() + 3600, "/","softwareprojects.org", 0); //notice this last extra argument
Both statements are used to send a cookie to the user's web-browser, and if you're wondering what's with that last argument we passed to "setcookie()", that tells the web-browser weather the cookies will be send only over a secure connection (0 means no, 1 means yes).
You may think that the "$visits" variable will be created after we send the header, and the first time we run PHP we will be able to read it. That is not true. The web-server reads the information only when the browser sends it the cookie, and this will not happen until the user revisits the web-page.
Setting an expiry date of zero will make the browser use the cookie until the user closes it; the browser will not remember the cookie the next time it's started. This can be useful for scripts that validate a user using cookies, and allow continued access to personal information on multiple pages after a password or other sensitive information has been submitted. It's not ok for the browser to have continued access to these pages after it has been restarted, because you cannot be sure if it's you who is using the browser, or some other user. So it would be better to allow the user to choose weather he wants to have more privacy, or he is the only user of that computer and nobody else accesses it.
Deleting cookies is also very easy, you should set the cookie you want to delete a date that has already expired. Remember to include the same path, domain and secure parameters you originally used when setting the cookie:
setcookie("visits", 23, time() – 60, "/", "softwareprojects.org", 0)

File Handling PHP

PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files thru the use of these functions. Note that before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while you're trying to figure out why you can't delete a file, it may be because the server doesn't allow you to do that.
The creation and removal of files are completed with two functions: "touch()" and "unlink()". "touch()" searches if a file exists, and if it doesn't, it creates one, according to the specified filename; "unlink()" is used to remove the file passed on as an argument:
touch("newinfo.txt"); //create a new file, if it doesn't already exist
unlink("oldinfo.txt"); //delete a file
Now that you know how to create a file, you should learn how to access it. This is done using the "fopen()" function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells "fopen()" to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. "fopen()" return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, "fopen()" returns FALSE. After you're done with the file, you should remember to close it with "fclose()", passing as an argument the file pointer.
$oldfp = fopen("oldinfo.txt", "r"); //opens a file for reading
if(!$fp = fopen("newinfo.txt", "w")) //tries to open a file for writing
die("Error on opening file!"); //terminates the execution of the script if it cannot open the file
fclose($oldfp);
Reading from files is done with "fgets()", which reads data from a file until it reaches a new line "\n", an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but "fgets()" first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The "fgetc()" is similar to "fgets()", except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, "fgetc()" doesn't require a length argument.
$text = fgets($fp, 2000); //reads 2000 bytes at most
$chr = fgetc($fp); //reads 1 byte only
While you can read lines using "fgets()", you need a way of telling when you have reached the end-of-file, so you won't continue reading without any results. This is accomplished with the "feof()" functions, which returns "TRUE" or "FALSE", weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp))
{
$line = fgets($fp);
print "$line<br>";
}
fclose($fp);
While "fgets()" works well around text files, you may sometimes want more functionality for your script. The "fread()" functions returns the specified amount of data from a file, and doesn't take into consideration the end-of-line "\n", like "fgets()". "fread()" also starts from the current file position, but if you're not happy with it, you can always change it using the "fseek()" function.
fseek($fp, 100); //moves the file pointer to the 100th byte
print(fread($fp, 15)); //outputs 15 bytes
Any writing to a file is done with the use of "fwrite()" or "fputs()" functions, which both use a file pointer and a string to perform the writing:
fwrite($fp, "Hello from PHP!");
fputs($fp, "Hello again from PHP!");
So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the "flock()" function, which will lock a file and won't allow other processes to write or read the file while the current process is running. "flock()" requires a file pointer and an integer to do this:
flock($fp1, 1); //shared lock – allows read, doesn't allow write
flock($fp2, 2); //exclusive lock – doesn't allow neither read, nor write
flock($fp3, 3); //release lock – releases a shared or exclusive lock
There are a lot of other functions that you can use with files like: testing functions – "file_exists()", "is_file()", "is_dir()", "is_readable()", "is_writeable()", "is_executable()"; functions that return information on files: "filesize()", "fileatime()", "filemtime()", "filectime()". You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.

Expanding PHP Classes

While you can always modify a class to add more properties and methods, there is a better way to create a more complex class based on a simple one. Extending existing classes by creating new classes which inherit their parent class properties and methods may come in handy when you need to create more classes based on the initial one. This is also called a "parent-child" relationship, the reasons are obvious. Know that the parent class must be defined before the child class, so the order in which the classes are defined is important. Let's get back to our automobile class, and create a new class based on the original one:
class used_automobile_class extends automobile_class
{
var $owner;
var $is_price_negotiable;
function write_negotiable()
{
if ($this->is_price_negotiable)
{
print "The price is negotiable!";
}
else
{
print "The price is NOT negotiable!";
}
}
}
We have created a new class that inherits the all of the properties and methods of "automobile_class", and adds some new ones. While you can always add new properties and methods, it is not possible to remove any of the properties or methods defined in the parent class. You can override them, though. This means that a child class can redefine a method of its parent class, and any new objects created based on the child class will use the child's redefined method.
After reading this, you may wonder why you should expand existing classes, and not just rewrite the class and adapt it to the new requirements. The answer lies in flexibility. There are times when you start writing a class from scratch, add some more properties as needed and create this large class, but then you want to get back to one of the initial structures and redefine it some other way. This would not have happened if you had created children classes that expanded the original class.
If you have worked with OOP before on other programming languages, you may be wondering "how about the constructors and destructors?" If you don't know what I'm talking about, you should be interested to know that PHP allows you to automatically call a special method (also known as a constructor) when you create a new instance of the class using "new". Destructors, on the other hand, are special methods that are automatically called when an object is destroyed. Unfortunately, there are no destructors in PHP, but you may use "register_shutdown_function()" instead to simulate most effects of a destructor.
Creating a constructor is easy, you only have to create a method with the same name as the class. In the following example, we output a string and set a variable when an object is created based on this class:
class automobile_class
{
var $negotiable_price;
var $price; //the price of the car, in dollars
function automobile_class()
{
print "Object created!";
this->$negotiable_price = FALSE;
}
}
Please take notice of the fact that in PHP there are some class and methods names that are reserved to language. A small constraint is that you cannot name a class "stdClass", because this is internally used by PHP. Also, it is recommended that you don't use function names beginning with "__", they are "magical" to PHP.

Programming PHP Arrays

The most inconvenient thing about a variable in software programming is that you can only store one value at a time. Arrays are special types that allow variables to overcome this limitation, so you can store as many values as you want in the same variable. For example, instead of having two variables "$number1" and "$number2", you could have an array "$numbers" that will hold both values. Imagine the same thing with ten numbers. What about a hundred? Because of the flexibility of the array, it can store two values or two hundred values, without having to define other variables. The PHP server-side scripting language indexes all the values within an array using a number or a string, so you will know which of the values you're using.
Programming with arrays is easy. You can process each item one after another, or you could just take one at random. Each item in an array is commonly referred to as an element. These elements can be accessed directly via their index, which can be either a number or a string. By default, PHP starts indexing elements numerically, from zero, and increments the element's index with each new addition, so keep in mind that the index of the last elements in a numerically indexed array is always the total number of elements minus one. Indexing arrays by string can be useful in cases where you need to store both names and values.
There are two ways you can create an array: with the "array()" function or directly using the array identifier "[]". You can use the "array()" function when you want to assign multiple elements to an array at a time. Don't think that an array can only contain elements of a certain type (for example, only numbers). You can have numbers, strings and booleans in the same array, PHP won't mind at all.
$names = array("John", 279, "Betty",TRUE);
This creates an array called "$names" which holds the specified elements. You can access an array element by placing its index between square brackets, right after the array name. Not only you can retrieve a value this way, but you can also assign a value to that element.
print $names[2]; //outputs "Betty"
$names[3] = "Harrison"; //replaces TRUE with "Harrison"
Remember that PHP starts indexing from zero, therefore "$names[0]" is "John", and so on – the index of any element always is one less than the element's place in the list. Another way to define an array is using the array identifier "[]" in conjunction with the array name. You can also use this to add new elements in you have already created an array – either using the "array()" function or the array identifier.
$names[] = "John";
$names[] = "Mary";
$names[] = "Betty";
$names = array("Harry", "Samantha","Danny");
There is no need to place any numbers between the square brackets, PHP takes care of the index number, so you don't have to figure out which is the next available slot. This doesn't mean that you cannot add numbers, but pay attention not to skip any of them, because PHP will initialize only the elements with the index number you specify.
Arrays indexed by strings, and not numbers, can prove to be useful when you need to access elements in array by name, and not by number. For example, if you have an address book, it would be much better to have a field called "name" or "address", instead of a numeric field called "1" or "2". You can define an associative array pretty much the same way you define a numerically indexed array.
$sysinfo = array(computer_name => "My computer",
cpu_mhz => 2800,
memory_size => 512,
multimedia => TRUE);
Or you can use the array identifier:
$sysinfo[computer_name] = "My computer";
$sysinfo[cpu_mhz] = 2800;
$sysinfo[memory_size] = 512;
$sysinfo[multimedia] = TRUE;
It's good to know that an array element can itself be an array, so this enabled you to create sophisticated data structures called multidimensional arrays. Let's say you have an address book, and you use an array to hold the information on the people you know (John, Mary, Betty, Harry). But on the other hand, each element must be a collection of a person's details (first name, last name, telephone number). This is how you define it:
$address_book = array(
array(first_name => "John", last_name => "Davis", phone_number => "1234567"),
array(first_name => "Mary", last_name => "Stewart", phone_number => "1234568"),
array(first_name => "Betty", last_name => "Willis", phone_number => "1234569"),
array(first_name => "Harry", last_name => "Miller", phone_number => "1234560"));
You can access the data using two indices, the first one for "$address_book" – which is a numeric index, and the second one for the person's details – which is a string index. The following text outputs the text "Mary":
print $address_book[1][first_name];
There are a lot of functions to use with arrays. You can merge, slice, shift and sort arrays, by using the functions with the same name: "array_merge()", "array_slice()", "array_shift()", and "sort()". Sorting is definitely one of the most used functions. The "sort()" function can sort both alphabetically or numerically, depending on the array elements. Read the PHP documentation to learn how to use these functions.

Object Oriented Programming In PHP

One of the most common programming concepts in the world is OOP, which stands for Object-Oriented Programming. Using this technique, programmers manipulate objects, which are made of functions and variables, instead of manipulating the functions and variables themselves. Let's say that you develop an e-commerce web-site. You could use an object to manage a shopping cart, and assign the object different properties and methods, based on what you want it to do. Properties stand for variables holding the information about the object (for example: the name, items in the cart, total value of the items, etc.), and methods stand for the functions that can be used with the object (for example: add an item into the cart, remove an item, empty cart, etc.)
It sounds simple, doesn't it? Well, it really is. But for an object to be defined, you have to have a template on which you will define the object. This is where classes come in. A class is a blueprint for one or more objects. Therefore, an object is to a class what a variable is to a type. A class is a set of characteristics, and an object is entity that is defined based on those characteristics. Another example: let's think about an automobile class. Such a class could have a characteristic (property) called "color". All objects created based on this class would have such a characteristic, but some objects would initialize this property to "red", others to "blue", and so on. This means that the class only holds a definition, and the object holds the actual value.
You can declare a class by using the "class" keyword. Let's define a simple class:
class automobile_class
{
var $color; //the color of the car
var $max_speed; //the maximum speed
var $price; //the price of the car, in dollars
function is_cheap()
{
return ($this->price < 5000); //returns TRUE if the price is smaller than 5000 dollars
}
}
In this small example you can notice some of the most important aspects of a class. After the declaration of the class, you can see the variables used within the class, which are called properties. These are declared using the "var" statement. While they can be defined anywhere within the class, you should really define them at the very top, so you can better see the class' properties. The functions within the class are called methods; they're used to manipulate the class' properties and produce results. In that simple method you can see that when we use a class method or property, we must use the "->" operator. The keyword "this" tells PHP that the property of method belongs to the class being defined.
An object is a special variable that contains a bundle of other variables and functions; you always have to use a class upon which to create an object. But, unlike a class, you won't need to write any code, nor you will see how the class actually works. While you may first think that this isn't so great, in fact this is one of the main concepts of object-oriented programming. You only have to create the class once, then you can create a zillion objects, in a zillion other projects.
While a class only exists in code and is considered to be a blueprint, an object exists in memory and is a working instance of a class. An instance of an object is created using the "new" statement along with the name of the class the object is based on. Let's return to our automobile class:
$car_object = new automobile_class();
$car_object->color = "red";
$car_object->price = 6000;
if($car_object->is_cheap())
{
print "This car is cheap!";
}
else
{
print "This car is expensive!";
}
You can see that we use the "->" operator to access and modify object's properties. After that, we use the same operator to call a method.
Perhaps the greatest benefit of object-oriented code is its reusability. Because the classes used to create objects are self-enclosed, they can be easily pulled from one project and inserted into another. Additionally, it is possible to create child classes that inherit and/or override the characteristics of their parents. This technique allows you to create more complex and specialized objects. Even if you start with a small class, you can develop it to a complex class by time, with adding more properties and objects to its children classes.

PHP Configuration

The endless possibilities of the PHP scripting language and a great community of users has made it one of the most popular open-source languages. For all you people living outside the UNIX world, Open Source means it doesn't cost anything. You can use it as much as you want and where you want, and nobody will ever charge you thousands of dollars for licenses and support. Even though it was originally conceived as a set of macros to help coders maintain personal home pages, its name grew a lot more from its purpose. Since then, PHP's capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.


PHP scripting

PHP is now officially known as "PHP: HyperText Preprocessor". It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module, which is server-side installed. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers – the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user?s web-browser, therefore it can never tell the user whether the web-server uses PHP or not, because all the browser sees is HTML.
PHP's support for Apache and MySQL further increases its popularity. Apache is now the most-used web-server in the world, and PHP can be compiled as an Apache module. MySQL is a powerful free SQL database, and PHP provides a comprehensive set of functions for working with it. The combination of Apache, MySQL and PHP is all but unbeatable.
That doesn?t mean that PHP cannot work in other environments or with other tools. In fact, PHP supports an extensive list of databases and web-servers. The rise in popularity of PHP has coincided with a change of approach in web-publishing. While in the mid-1990s it was ok to build sites, even relatively large sites, with hundreds of individual hard-coded HTML pages, today?s webmasters are making the most of the power of databases to manage their content more effectively and to personalize their sites according to individual user preferences.

Reasons for using PHP

There are some indisputable great reasons to work with PHP. As an open source product, PHP is well supported by a talented production team and a committed user community. Furthermore, PHP can be run on all the major operating systems with most servers.
The speed of development is also important. Because PHP allows you to separate HTML code from scripted elements, you will notice a significant decrease in development time on many projects. In many instances, you will be able to separate the coding stage of a project from the design and build stages. Not only can this make life easier for you as a programmer, but it also can remove obstacles that stand in the way of effective and flexible design.
Well-maintained open source projects offer users additional benefits. You benefit from an accessible and committed community who offer a wealth of experience in the subject, as fast and as cheap as possible. Chances are that any problem you encounter in your coding can be answered swiftly and easily with a little research. If that fails, a question sent to a mailing list or forum can have an intelligent, authoritative response. You also can be sure that bugs will be addressed as they are found, and that new features will be made available as the need is defined. You will not have to wait for the next commercial release before taking advantage of improvements, and there is no hidden interest in a particular server product or operating system. You are free to make choices that suit your needs or those of your clients and incorporate whatever components you want.

PHP Installation

Before you start programming with PHP, you must first acquire, install, and configure the PHP interpreter. PHP is available for a lot of platforms, and works in conjunction with many web-servers. Along with PHP itself and a web-server you also need a web-browser, so you can view the outcome of your work.
The latest version of PHP can be downloaded from www.php.net; after the download is complete, don't forget to unpack the archive. There are two available downloads: the source code, which you can use to compile PHP, and the binary version of PHP, which means that it's already compiled. If you're new in the business, you should go with the binary version, for it will save you from a lot of headaches. If you don't have already installed a web-server, you should go ahead install one for your operating system (for example Apache on Linux, and IIS or Apache on Windows); a web browser is also required, but this should be the least of your concern, you most probably have it already installed. If you don't want to run the web-server on your own, you can find a hosting company that will host your web-site. This way, you can skip the installation, start writing scripts. There are a lot of hosting companies that offer free hosting services, just search it on the Internet and you'll find a lot of offers to choose from.

PHP and your web-server

There are two ways of attaching PHP to your web-server. The first and most common way is with using PHP's direct module interface – also called SAPI – for the most common web-servers: Apache, Microsoft IIS, Netscape and iPlanet. The second way to use PHP is as a CGI processor, which means that you must set up the server to use the command line executable of PHP, so it can process the PHP file requests on the server. This method mostly applies to the web-servers that PHP doesn't have a direct module interface for.
PHP has installation instructions for both ways. Before installing, you should always make sure that you are logged into the system as the root user (administrator). If you're not allowed to access the system's root account, you should ask your system administrator to install PHP for you.

SAPI installation

The first way of installing PHP and the easiest way to get PHP up and running is by using a direct module interface. This will require some configuring in your web-server; for example, Apache requires you to edit its configuration file and add a few new entries. In order to find out exactly what you need to do in order to properly install PHP on Apache, or any other web-server, you should read PHP's documentation.
The second way of installing PHP is not always recommended by the web-server's developer. Apache calls this method ?suicidal?, because, if not configured properly, could allow a user with not-so-good intentions to access some of the web-server's files which are not intended to be public. So if you're a beginner, you should stay away from this method of installing PHP. Even advanced users sometimes fail to cover all the security issues.
After you've completed the installation, you should remember to take PHP for a test drive, before you start programming. You wouldn't want to ask people around why your script isn't working, when the installation wasn't performed correctly.

What Is PHP?

The endless possibilities of the PHP scripting language and a great community of users has made it one of the most popular open-source languages. For all you people living outside the UNIX world, Open Source means it doesn't cost anything. You can use it as much as you want and where you want, and nobody will ever charge you thousands of dollars for licenses and support. Even though it was originally conceived as a set of macros to help coders maintain personal home pages, its name grew a lot more from its purpose. Since then, PHP's capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.

PHP scripting

PHP is now officially known as "PHP: HyperText Preprocessor". It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module, which is server-side installed. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers – the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user?s web-browser, therefore it can never tell the user whether the web-server uses PHP or not, because all the browser sees is HTML.
PHP's support for Apache and MySQL further increases its popularity. Apache is now the most-used web-server in the world, and PHP can be compiled as an Apache module. MySQL is a powerful free SQL database, and PHP provides a comprehensive set of functions for working with it. The combination of Apache, MySQL and PHP is all but unbeatable.
That doesn?t mean that PHP cannot work in other environments or with other tools. In fact, PHP supports an extensive list of databases and web-servers. The rise in popularity of PHP has coincided with a change of approach in web-publishing. While in the mid-1990s it was ok to build sites, even relatively large sites, with hundreds of individual hard-coded HTML pages, today?s webmasters are making the most of the power of databases to manage their content more effectively and to personalize their sites according to individual user preferences.

Reasons for using PHP

There are some indisputable great reasons to work with PHP. As an open source product, PHP is well supported by a talented production team and a committed user community. Furthermore, PHP can be run on all the major operating systems with most servers.
The speed of development is also important. Because PHP allows you to separate HTML code from scripted elements, you will notice a significant decrease in development time on many projects. In many instances, you will be able to separate the coding stage of a project from the design and build stages. Not only can this make life easier for you as a programmer, but it also can remove obstacles that stand in the way of effective and flexible design.
Well-maintained open source projects offer users additional benefits. You benefit from an accessible and committed community who offer a wealth of experience in the subject, as fast and as cheap as possible. Chances are that any problem you encounter in your coding can be answered swiftly and easily with a little research. If that fails, a question sent to a mailing list or forum can have an intelligent, authoritative response. You also can be sure that bugs will be addressed as they are found, and that new features will be made available as the need is defined. You will not have to wait for the next commercial release before taking advantage of improvements, and there is no hidden interest in a particular server product or operating system. You are free to make choices that suit your needs or those of your clients and incorporate whatever components you want.