| Goals for this chapter: | rpm packages covered in this chapter:
|
|
|
|
-- Larry Wall in 1991Jul13.010945.19157@netlabs.com
PHP was created by Rasmus Lerdorf.
PHP stand for Pre Hypertext processor. PHP is an elegant and efficient new mode to create Web sites. For example, using PHP is possible to get all the customers inside a MySQL Database, create and handle International Websites where the Text belong to a MySQL DB, that changes in accord to the Language, or a standard Website but in a new and innovative mode.
PHP is a programming language capable to write functions inside the HTML code and write programs that take advantage of HTML tags, like fonts or colors.
<?php
function font(
$str_text,
$str_color = 'blue',
$int_size = 2
) {
echo "<font size=\"$int_size\" color=\"$str_color\">$str_text</a>";
}
?>
<?php font('This line is blue - size 2.'); ?>
<br>
<?php font('This line is red - size 2.', 'red'); ?>
<br>
<?php font('This line is white - size 4', 'white', 4); ?>
<br>
PHP is also capable to support Classes, like for example:
<?php // cls_body.inc
class cls_body extends cls_htmlbase {
var $valid_attributes = array(
'background'
,'bgcolor'
,'text'
,'link'
,'alink'
,'vlink'
,'leftmargin'
,'topmargin'
,'bgproperties'
);
function cls_body($in_props = '') {
$in_props['tag_name']
= 'body';
$this->cls_htmlbase($in_props);
}
}
?>
Any type of normal "normal" code is possible:
<?php
$flg_break_happened = 0;
for ($index = 0; $index < 10; $index++) {
if ($index == 3) {
break;
$flg_break_happened = 1;
}
echo "$index<br>";
}
if ($flg_break_happened) {
echo "Loop ended because of break.<br>";
}
else {
echo "Loop ended naturally.<br>";
}
?>
All the incredible and wonderfull code that we can write using PHP needs that the necessary PHP Apache modules are installed in the system. Generally, these modules are installed and present, therefore nothing is necessary.
You can check the file "/etc/httpd/conf/httpd.conf". You will find lines like:
DirectoryIndex index.html index.htm index.shtml index.php index.php4 index.php3 index.cgi
or
<IfDefine HAVE_PHP>
LoadModule php_module
modules/mod_php.so
</IfDefine>
<IfDefine HAVE_PHP3>
LoadModule php3_module
modules/libphp3.so
</IfDefine>
<IfDefine HAVE_PHP4>
LoadModule php4_module
modules/libphp4.so
</IfDefine>
Of course, also these modules must be installed in the system to work
with PHP !
| <HTML>
<HEAD> <TITLE> My first PHP file </TITLE> </HEAD> <BODY> <?PHP $string = 'world!'; ?> <H3>Hello <?php echo $string ?> </H3> </BODY> </HTML> |
![]() |
Now, we remove the HTML code and
| <?PHP $string
= 'world!'; ?>
<H3>Hello <?php echo $string ?> </H3> |
![]() |
Therefore removing the HTML code we get the same results!. (Is important that you remove any space between ? and PHP, in the declaration: <? PHP is wrong, <?PHP ... is correct).
These features are included in the PHP configuration file: /etc/php.ini
Why these PHP files does not work if we load it in the browser like: file://first.png ?
PHP is really an incredible and enthusiastic programming language!
PHP may run also local files, like we does with PERL!
| <?PHP
'<pre>'; echo `ls *`; '<pre>'; ?> |
![]() |
Here we resume (or apply) a most common way to write PHP code
<PHP
...
PHP code
...
?>
With PHP is possible to get
For example common PHP code is as follows:
<?php
function miles2kilometers ( $mykilo ) {
return(238857 * $mykilo );
}
$distance = miles2kilometers(5);
echo "The distance earth-moon $distance.<br>";
?>
The result is:
The distance earth-moon 1194285.
<?php
function inverse7 ( ) {
return(1/7 );
}
$result = inverse7();
echo "The inverse of seven is: $result.<br>";
?>
The result is:
The inverse of seven is: 0.14285714285714.
Note that this number haves a periodical
The number of decimals available is included in the PHP Configuration file: php.ini
[root@ftosx1 PHP]# more /etc/php.ini | grep precision
precision = 14
[root@ftosx1 PHP]#
With PHP is possible to run and realize any project that need PERL, CGI, MySQL code . The PHP idea to geneate code, any code is fantastic.
After you know the text and literals you can make confidence with PHP.
PHP supports also vectors
A complete set of library is also available to get results on different types of DB.
[root@ftosx1 php4]# ls
imap.so ldap.so mysql.so odbc.so pgsql.so
[root@ftosx1 php4]#
To check the PHP Operators please visit Appendix O: PHP Operators
Using PHP, the Pre-Hypertext processor is possible to create dynamic HTML pages using High-Level programming languages available in PHP.
For example suppose you want to print a list of numbers from 1 to 50.
Then, we can use the following PHP code:
| <?php
for ($i =1; $i <= 50; $i++) { echo "$i<br>"; } ?> |
![]() |
An extension to this simple code, may be for example an HTML form to print the the prime factors of an imput number or the message "the number is prime".
Now we will introduce the code:
| <?php
function theirfont(
<?php theirfont('This line is blue - size 4.'); ?>
|
![]() |
Another use is for example the possibility to list the records inside a table. The next section is more clear in this direction:
<?php
for ($iindex = 0; $iindex < $number_of_records_on_current_page;
$iindex++) {
$record = @mysql_fetch_object($result);
$key =
$record->key_studentid;
$delete = "$PHP_SELF?action=delete_record&key=$key";
$edit = "$PHP_SELF?action=edit_record&key=$key";
$clone = "$PHP_SELF?action=clone_record&key=$key";
echo "<tr>";
echo "<td>";
echo "<font size=\"1\">";
echo "<a href=\"<?php echo
$delete; ?>\">Delete</a>";
echo "<a href=\"<?php echo
$edit; ?>\">Edit</a>";
echo "<a href=\"<?php echo
$clone; ?>\">Clone</a>";
echo "</font><br>";
echo "$record->student_name";
echo "</td>";
echo "<td>";
echo "$record->date_updated";
echo "</td>";
echo "</tr>";
}
?>
Note how all the code is enclosed in a PHP Parenthesis. Also note how both:
We will complete this chapter presenting probably the most usefull mode to use PHP, browsing and connect to a MySQL DB.
Connecting to a MySQL DataBase
MySQL is a DataBase specially designed for WebMasters. This means for example that we can access a MySQL DB that is located in the Web, is we know the necessary user and password name.
For example, another user may access the DB, running the command.
[sales@www sales]$ mysql mydb -u root
Or from the Web:
[tony@ftosx1] mysql -h www.futuretg.com -u myuser -p
[root@www /root]# mysql -h www.futuretg.com -u myuser -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 77 to server version: 3.23.36
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
mysql> use mydb;
[root@ftosx1 Acqua-KDE2.0]# ls
Reading table information for completion of table and column
names
You can turn off this feature to get a quicker startup with
-A
Database changed
mysql>
The command 'use' allow to change the Database.
mysql> status
--------------
mysql Ver 11.13 Distrib 3.23.36, for redhat-linux-gnu
(i386)
Connection id:
77
Current database: mydb
Current user:
myuser@www.futuretg.com
Current pager:
stdout
Using outfile:
''
Server version:
3.23.36
Protocol version: 10
Connection:
www.futuretg.com via TCP/IP
Client characterset: latin1
Server characterset: latin1
TCP port:
3306
Uptime:
1 day 16 hours 37 min 6 sec
Threads: 1 Questions: 114 Slow queries: 0 Opens:
13 Flush tables: 1 Open tables: 7 Queries per second avg: 0.001
--------------
mysql>
These data belong to the mysql DB (standard) created after the MySQL installation.
Now we create three tables to access the rpmdb.
Then, we will access the data using some PHP functions to access the MySQL data. This insertion is fundamental to acces the DB thought PHP.
[root@ftosx1 root]# mysql mysql
Reading table information for completion of table and column
names
You can turn off this feature to get a quicker startup with
-A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 14 to server version: 3.23.41
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> INSERT INTO user (
-> host,
-> user,
-> password,
-> select_priv,
-> insert_priv,
-> update_priv,
-> delete_priv)
-> VALUES (
-> 'localhost',
-> 'myuser',
-> password('myuser'),
-> 'Y',
-> 'Y',
-> 'Y',
-> 'Y');
Query OK, 1 row affected (0.31 sec)
mysql>
mysql> INSERT INTO db (
-> host,
-> db,
-> user,
-> select_priv,
-> insert_priv,
-> update_priv,
-> delete_priv)
-> VALUES (
-> '%',
-> 'rpmdb',
-> 'myuser',
-> 'Y',
-> 'Y',
-> 'Y',
-> 'Y');
Query OK, 1 row affected (0.01 sec)
Now, we check the insertion.
[root@ftosx1 root]# mysql mysql
Reading table information for completion of table and column
names
You can turn off this feature to get a quicker startup with
-A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.23.41
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select * from user;
+---------------------+--------+------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+-------------
--+--------------+-----------+------------+-----------------+------------+------------+
| Host
| User | Password
| Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv |
Drop_priv | Reload_priv | Shutdown_pri
v | Process_priv | File_priv | Grant_priv | References_priv
| Index_priv | Alter_priv |
+---------------------+--------+------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+-------------
--+--------------+-----------+------------+-----------------+------------+------------+
| localhost
| root |
| Y | Y
| Y | Y
| Y | Y
| Y | Y
| Y
| Y | Y
| Y
| Y | Y
|
| ftosx1.futuretg.com | root |
| Y | Y
| Y | Y
| Y | Y
| Y | Y
| Y
| Y | Y
| Y
| Y | Y
|
| localhost
| |
| N | N
| N | N
| N | N
| N | N
| N
| N | N
| N
| N | N
|
| ftosx1.futuretg.com |
|
| N | N
| N | N
| N | N
| N | N
| N
| N | N
| N
| N | N
|
| localhost
| myuser | 62f1566f0abe9e27 | Y
| Y | Y
| Y | N
| N | N
| N
| N
| N | N
| N
| N | N
|
+---------------------+--------+------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+-------------
--+--------------+-----------+------------+-----------------+------------+------------+
5 rows in set (0.03 sec)
mysql>
mysql>
Note that mysql is the name of the DB.
Now, we will create a connection to the rpm DB, introduced in the Chapter 14.
PHP offers a special function to access the MySQL DB. This functions bases its definition on three parameters.
The PHP function is:
@mysql_connect('localhost', $username, $password);Where localhost is the IP address or Webserver address where is located the DB. Username and Password are the data that regards the MySQL DB (rpmdb) inserted in MySQL mysql Database.
We list here the code a PHP code that opens a connection and send a message if the connection is successfull:
[root@ftosx1 ch05]# more connect2db.php3
<?php
function my_header($title) {
echo '<html><head><title>';
echo "$title";
echo '</title></head><body>';
}
function my_body($msg) {
echo '<table>';
echo '<tr><td>';
echo "$msg";
echo '</td></tr>';
echo '</table>';
}
function my_footer() {
echo '</body></html>';
}
?>
<?php
if (count($arr_request)) {
$username = $arr_request['username'];
$password = $arr_request['password'];
}
else {
$username = 'myuser'; (The
data we enter in the DB - the user that have access to the DB)
$password = 'myuser'; (The
password relative to the user)
}
?>
<?php
$id_link = @mysql_connect('localhost', $username, $password);
(The
PHP command to connect to the DB)
if (! $id_link) {
my_body(
"The connection to the local
database has failed. Please enter a
username and password so a connection
can be made."
);
?>
<form action="connect.php3" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="username"
value="root"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Connect
to Database">
</td>
</tr>
</table>
</form>
<?php exit; } ?>
<p>The connection was successful!</p>
[root@ftosx1 ch05]#
The connection using PHP commands is only the beginning. Using PHP code is possible to write code that take advantage of both MySQL commands (SQL language) and HTML features.
For example if we load the previous PHP code, we get.

We can also split the previous code using the the PHP require code.
[root@ftosx1 ch05]# more myinclude.inc
<?php
function my_header($title) {
echo '<html><head><title>';
echo "$title";
echo '</title></head><body>';
}
function my_body($msg) {
echo '<table>';
echo '<tr><td>';
echo "$msg";
echo '</td></tr>';
echo '</table>';
}
function my_footer() {
echo '</body></html>';
}
?>
Now, we list the previous source in two pieces.
[root@ftosx1 ch05]# more myinclude.inc
<?php require('myinclude.inc'); ?>
<?php
if (count($arr_request)) {
$username = $arr_request['username'];
$password = $arr_request['password'];
}
else {
$username = 'myuser';
$password = 'myuser';
}
?>
<?php
$id_link = @mysql_connect('localhost', $username, $password);
if (! $id_link) {
my_body(
"The connection to the local
database has failed. Please enter a
username and password so a connection
can be made."
);
?>
<form action="connect.php3" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="username"
value="root"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Connect
to Database">
</td>
</tr>
</table>
</form>
<?php exit; } ?>
<p>The connection was successful!</p>
A PHP Web site
Any kind of operations may be made. We can insert, delete or edit records.
For example if we use the notation:
$record = @mysql_fetch_object ($result);
Then, we will have in the variables,
$key = $record->key_studentid;
$delete = "$PHP_SELF?action=delete_record&key=$key";
$edit = "$PHP_SELF?action=edit_record&key=$key";
$clone = "$PHP_SELF?action=clone_record&key=$key";
all the data equivalent to the Table:
mysql> create table lwc_students (
-> key_studentid int (10) unsigned
DEFAULT '0' NOT NULL auto_increment,
-> date_created datetime DEFAULT '0000-00-00
00:00:00' NOT NULL,
-> date_updated datetime DEFAULT '0000-00-00
00:00:00' NOT NULL,
-> flg_deleted enum ('Y', 'N') DEFAULT 'N'
NOT NULL,
-> student_name varchar (50) NOT NULL,
-> student_address varchar (150) NOT NULL,
-> student_email varchar (150) NOT NULL,
-> PRIMARY KEY (key_studentid));
Query OK, 0 rows affected (0.15 sec)
Now, we will present a simple example about PHP.
We will create a form to insert 'only' the student name. The key is a number that automatically increments.
The source is organized in three files:
![]() |
<?php // lwc_students.php3
// Specify which table is being maintained.
// NEW: Initialize variables to their default
// Create the connection to the specific Database!
// NEW: If the initial_record URL-based value exists,
require($table_name . '_actions.inc');
<H1>
<form action="<?PHP echo $PHP_SELF ?>" method="post">
|
We we can:
![]() |
![]() |
| Insert the student name ... | ... and the student name will displayed |
![]() |
![]() |
| ... We can edit and | ... and update it |
We can also duplicate it!

We will not describe all the source.
All the tables and operations are made using functions like:
$str_sql = "
select *
from
$table_name
where
flg_deleted='N'
limit
$initial_record, $number_records_to_display
";
All the source for the PHP code is included in the FTContribs/Files/PHP directory.
Check the Interactive Exam Cram WebMaster:
Internet Resources for this Chapter.