History of PHP, Apache Web Server, Mysql and Open Source
History of PHP, Apache Web Server, Mysql and Open Source
Open Source
∙ In general, open source refers to any program whose source code is made available for use or
modification.
Open source software is usually developed as a public collaboration and made freely available. It
means can be used without purchasing any license.
∙ Open Source is a certification mark owned by the Open Source Initiative (OSI). Developers of
software that is intended to be freely shared and possibly improved and redistributed by others can
use the Open Source trademark if their distribution terms conform to the OSI's Open Source
Definition. To summarize, the Definition model of distribution terms require that:
▪ The software being distributed must be redistributed to anyone else without any restriction. ▪
The source code must be made available (so that the receiving party will be able to improve
or modify it).
∙ Example of Open Source: Linux, Apache, MySQL, PHP.
PHP
∙ PHP is a general‐purpose server‐side scripting language originally designed for web development to
produce dynamic websites.
∙ PHP scripts execute on web server and serve WebPages to user on request.
∙ PHP was originally created by RasmusLerdorf in 1994. Programmer RasmusLerdorf initially created a
set of C scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts
performed tasks such as displaying his résumé and recording his web‐page traffic.
∙ These were released and extended to include a package called the Form Interpreter (PHP/FI). While
PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext
Preprocessor", a recursive acronym.
∙ PHP code is embedded into the HTML source document and interpreted by a web server with a PHP
processor module, which generates the web page document. It also has evolved to include a
command‐line interface capability and can be used in standalone graphical applications.PHP can be
deployed on most web servers and as a standalone interpreter, on almost every operating system
and platform free of charge.
∙ In 1997 ZeevSuraski and AndiGutmans along with Rasmus rewrite PHP and released PHP version 3.0
in June 1998.After this release PHP becomes so much popular.
∙ The PHP version 4.0 was launched in May 2000.This version includes session handling, output
buffering, a richer cire language and support for wide variety of web server platforms.
∙ The PHP 5.0 version released in 2004 with object oriented programming concept.
Web Server
∙ A Web Server is computer and the program installed on it. Web Server interacts with the client
through the browser. It delivers the web pages to the client and to an application by using the web
browser and HTTP protocol respectively.
∙ We can also define the web server as the package of larger number of programs installed on a
computer connected to internet or intranet for downloading the requested files using File Transfer
Protocol, serving e‐ mail and building and publishing web pages.
∙ A web server works on client server model. A computer connected to internet or intranet must have
a server program.
∙ A computer connected to the internet for providing the services to a small company or a department
store may contain the HTTP server to access and store WebPages and files, SMTP server to support
mail services, FTP server for files downloading and NNTP server for newsgroup.
∙ The computer containing all the above servers is called the web server.
MySQL
∙ MySQL is a relational database management system (RDBMS) that runs as a server providing
multi‐user access to a number of databases.
∙ It is named after developer Michael Widenius' daughter, My. The SQL phrase stands for Structured
Query Language.
∙ The data in MySQL is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.
∙ The MySQL development project has made its source code available under the terms of the License.
The license can require improved versions of the software to carry a different name or version from
the original software.
∙ First released in January,1998, MySQL was owned and sponsored by the Swedish company MySQL
AB, now owned by Oracle Corporation.
∙ MySQL is fully multithreaded using kernel threads, and provides application programming interfaces
(APIs) for many programming languages, including C,C++, Java, Perl, PHP, Python.
∙ MySQL is used in a wide range of applications, including data warehousing, e‐commerce, Web
databases, logging applications and distributed applications.
PHP
∙ PHP is a server side scripting that was designed for creating dynamic websites. It slots into your
Apache web server and processes instructions contained in a web page before that page is sent
through to your web browser.
∙ PHP is a powerful scripting language that can be run in the command line of any computer with
PHPinstalled. However, PHP alone isn't enough in order to build dynamic web sites.
Apache
∙ To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web
Server that, once installed on a computer, allows developers to test PHP scripts locally; this makes it
an invaluable piece of your local development environment.
∙ Like all web servers, Apache accepts an HTTP request and serves an HTTP response.
MySQL
∙ Additionally, dynamic websites are dependent on stored information that can be modified quickly
and easily; this is the main difference between a dynamic site and a static HTML site. However, PHP
doesn’t provide a simple, efficient way to store data. This is where a relational database
management system like MySQL comes into play. PHP provides native support for it and the
database is free, open‐source project.
∙ MySQL is a relational database management system (DBMS). Essentially, this means that MySQL
allows users to store information in a table‐based structure, using rows and columns to organize
different pieces of data.
∙ Numeric Array
∙ Associative Array
∙ Multidimensional Array
Numeric Array
∙ In numeric array each element having numeric key associated with it that is starting from 0;
<?php
$myarray=array(‘A’,’B’,’C’);
print_r($myarray);
?>
Output:
Array( [0]=>A [1]=>B [2]=>C)
∙ You can refer to individual element of an array in PHP script using its key value as shown below:
<?php
$myarray=array(‘A’,’B’,’C’);
echo $myarray[1];
?>
It will display
B
∙ In Numeric Array you can use for, while or do while loop to iterate through each element in array
because in numeric array key values are consecutive.
<?php
$myarray=array(“Apache”, “MySQL”, “PHP”);
for($i=0;$i<3;$i++)
{
echo
$myarray*$i+.”<br>”; }
?>
Output:
Apache
MySQL
PHP
Associative Array
∙ The associative part means that arrays store element values in association with key values rather
than in a strict linear index order.
∙ If you store an element in an array, in association with a key, all you need to retrieve it later from
that array is the key value.
∙ Key may be either numeric or string.
For Example 1:
<?php
$myarray=array(5=>”Apple”, 10=>”Mango”, 20=>”Grapes”);
print_r($my_array);
?>
Output:
Array([5]=>Apple [10]=>Mango [20]=>Grapes)
Example 2:
<?php
$myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
print_r($myarray);
?>
Output:
Array([Name]=>James [Age]=>25 [Gender]=>Male)
∙ You can refer to individual element of an array in PHP using its key value.
Example:
<?php
$myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
echo “Name:”.$myarray*‘Name’+;
?>
Output:
Name:James
∙ In associative array you cannot use for, while and do..while loop to iterate through each element
in array because in Associative array key value are not consecutive.
∙ So you have to use foreach loop.
For Example:
<?php
$myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
foreach($myarray as $item)
{
echo $item;
}
?>
Output:
James 25 Male
Multidimensional Array
PHP can easily support multidimensional arrays, with arbitrary numbers of key.And just as in one
dimensional arrays, there is no need to declare out intentions in advance. Assignment can be like:
$multi_array*0+*1+*2+*3+=”Good Morning”;
The values those are stored in array can themselves be arrays, just as legitimately as they can be string or
numbers.
For example:
The integer key of 0 stores a string, and the key 1 stores an array that ,in turn, has a string in it.
It is simply an array with two values stored in association with keys.Each of them values is an array itself. We
can reference it like this
echo $basket*‘fruit’+*‘black’+;
$kind=”flower”;
$color=”yellow”;
print(“ $basket *$kind+ *$color+”);
PHP Sessions
∙ A PHP session variable is used to store information about, or change settings for a user session.
∙ Session variables hold information about one single user, and are available to all pages in one
application.
∙ This is much like a Session. The computer knows who you are. It knows when you start the application
and when you end.
∙ But on the internet there is one problem: the web server does not know who you are and what you
do because the HTTP address doesn't maintain state.
∙ A PHP session solves this problem by allowing you to store user information on the server for later
use (i.e. username, shopping items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent storage you may want to store
the data in a database.
∙ Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The
UID is either stored in a cookie or is propagated in the URL.
<?phpsession_start(); ?>
<html>
<body>
</body>
</html>
∙ The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
∙ Output:Pageviews=1
∙ In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
∙ If you wish to delete some session data, you can use the unset() or the session_destroy() function.
<?php
unset($_SESSION['views']);
?>
∙ You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
∙ Note:session_destroy() will reset your session and you will lose all your stored session data.
PHP Cookie
∙ A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer.
∙ Each time the same computer requests a page with a browser, it will send the cookie too. With PHP,
you can both create and retrieve cookie values.
∙ Note: The setcookie() function must appear BEFORE the <html> tag.
∙ In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it.
We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
∙ Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
∙ You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
∙ In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
∙ In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
<html>
<body>
<form action="welcome.php" method="post"> Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
How can you connect to database in PHP? Show the simple database
operation using PHP with proper example.
Integration of PHP with MySQL
∙ It is possible to execute various commands of MySQL from PHP.PHP provides various built-in
functions which you allows you to use MySQL commands from PHP page. Thus you can integrate
PHP with MySQL.
∙ Following are the various PHP functions that allows you the facility of integrating PHP with MySQL:
mysql_connect()
∙ Before you can access data in a database, you must create a connection to the database.
∙ This function allows you to establish connection of PHP application with MySQL server.
∙ Syntax: mysql_connect(servername,username,password);
∙ If connection establish successfully with MySQL Server then this function returns TRUE value
otherwise it returns FALSE.
∙ Example <?php
?>
ed with
MySQL”; }
$conn=mysql_c e
onnect(“localh l
ost”,”root”,””); s
if($conn) e
{ {
e echo “Could not connect to database”;
cho }
“Connect
mysql_select_db()
∙ This function allows you to select database from the list of MySQL server databases.
DatabaseName
∙ Indicates the name of the database that you want to select.
ConnectionName
∙ Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.
∙ If function successfully executed then it returns TRUE otherwise it returns FALSE.
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”);
if($db)
{
echo “Database Selected Successfully ”;
}
else
{
echo “Error in selecting Database.”;
}
?>
mysql_query()
∙ This function allows you to specify and execute the MySQL command on MySQL Server. ∙
Syntax:
mysql_query(Query, ConnectionName);
∙ Example
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$cmd=mysql_query(“create table Test(ID integer, Name varchar(20))”);
if($cmd)
{
echo “Table created Successfully ”;
}
else
{
echo “Error in executing query.”;
}
?>
mysql_fetch_row()
∙ This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.
∙ The record that is returned by this function is in the form of numeric array. Numeric array contains
index and value associated with that index.
∙ If there is no record in the record set then it returns false value.
∙ Syntax:
mysql_fetch_row(VariableName);
∙ VariableName indicates the record set that is returned from executing the MySQL command using
mysql_query() function.
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query,$conn);
$ans=mysql_fetch_row($result);
print_r($ans);
mysql_close($con);
?>
mysql_fetch_array()
∙ This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.
∙ The record that is returned by this function is in the form of either numeric array, associative array
or both.
∙ If there is no record in record set then it will returns false value.
∙ Syntax:
mysql_fetch_array(VariableName, ResultArrayType)
∙ VariableName:- indicates the record set that is returned from executing the MySQL command
using mysql_query() function.
∙ ResultArrayType:-indicates the type of array to be returned. It can have one of the following
values:
MYSQL_ASSOC This type of array contains name of the field and the value associated with that
field for current record.
MYSQL_NUM This type of array contains index of the field and the value associcated with that
index for current record.
MYSQL_BOTH It is combination of both Associative array and Numeric array. It is the default
type to be returned by this function.
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_array($result,MYSQL_ASSOC);
print_r($ans);
mysql_close($con);
?>
mysql_fetch_assoc()
∙ This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query in the form of associative array.
∙ Syntax:
mysql_fetch_assoc(VariableName)
∙ Returns an associative array that corresponds to the fetched row, or FALSEif there are no more
rows.
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_assoc($result);
print_r($ans);
mysql_close($con);
?>
To go through all the records fetched in record set.
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
while($ans=mysql_fetch_assoc($result))
{
echo
$ans*‘field1’+.”<br>”;
echo
$ans*‘field2’+.”<br>”;
}
mysql_close($con);
?>
mysql_num_rows()
∙ This function allows you to retrieve number of records available in the record set.
∙ Syntax:
mysql_num_rows(ResultVariable);
∙ ResultVariable is the variable that holds result returned by mysql_query() function.
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$total_records=mysql_fetch_rows($result);
echo “Total Records:”.$total_records;
mysql_close($con);
?>
mysql_error()
∙ This function allows you to retrieve theerror text from the most recently executed MySQL
function.
∙ If no error encountered while executing the script then it will returns blank string.
∙ If the mysql operation contains more than one error then it will returns error description of the
last statement in which error is encountered.
∙ Syntax:
mysql_error();
∙ Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
if($conn)
{
echo “Connected with MySQL”;
}
else
{
echo “Error:”.mysql_error();
}
?>
mysql_close()
∙ This function allows you to close the connection that is established using mysql_connect()
function.
∙ Syntax:mysql_close(ConnectionName);
∙ ConnectionName :- Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.
∙ It returns true is connection is closed successfully otherwise it returns false.
∙ Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
mysql_close($con);
?>