SlideShare une entreprise Scribd logo
1  sur  51
PHP BASIC
Dr. Ramkumar Lakshminarayanan
What is PHP?
• PHP stands for PHP: Hypertext Preprocessor
• PHP is a server-side scripting language, like ASP
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid, PostgreSQL, Generic ODBC, etc.)
• PHP is an open source software (OSS)
What is a PHP File?
• PHP files may contain text, HTML tags and scripts
• PHP files are returned to the browser as plain HTML 
• PHP files have a file extension of ".php", ".php3", or ".phtml"
What is MySQL?
• MySQL is a database server
• MySQL is ideal for both small and large applications
• MySQL supports standard SQL
• MySQL compiles on a number of platforms
PHP + MySQL
• PHP combined with MySQL are cross-platform (means that you can develop
in Windows and serve on a Unix platform)
Why PHP?
• Install an Apache server on a Windows or Linux machine
• Install PHP on a Windows or Linux machine
• Install MySQL on a Windows or Linux machine
What do You Need?
This tutorial will not explain how to install PHP, MySQL, or Apache Server.
If your server supports PHP - you don't need to do anything! You
do not need to compile anything or install any extra tools -
just create some .php files in your web directory - and the server will
parse them for you. Most web hosts offer PHP support.However, if your
server does not support PHP, you must install PHP. Below is a link to a
good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
Download Apache for free here:
http://httpd.apache.org/download.cgi
Download PHP
Download PHP for free here: http://www.php.net/downloads.php
Download MySQL Database
Download MySQL for free here:
http://www.mysql.com/downloads/index.html
Download Apache Server
Basic PHP Syntax
• A PHP scripting block always starts with <?php and ends with ?>. PHP scripting block can
be placed anywhere in the document.
<?php ?>
• A PHP file normally contains HTML tags, just like an HTML file, and
some PHP scripting code.
<html>
<body>
<?php
echo "Hello World"; ?>
</body>
</html>
Comments in PHP
<html>
<body>
<?php
//This is a comment
/* This is a comment block *
/?></body>
</html>
•In PHP, we use // to make a single-line comment or /* and */ to make a large comment
block.
Variables in PHP
• Variables are used for storing a values, like text strings, numbers or arrays.
• When a variable is set it can be used over and over again in your script
• All variables in PHP start with a $ sign symbol.
• The correct way of setting a variable in PHP:
<?php
$txt = "Hello World!";
$number = 16;
?>
Strings in PHP
• String variables are used for values that contains character strings.
<?php
$txt="Hello World";
echo $txt;
?>
PHP Operators
Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x=4
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus (division
remainder)
5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4
• Arithmetic Operators
Assignment Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true
Logical Operators
Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
PHP If...Else Statements
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise
it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else echo "Have a nice day!";
?>
</body>
</html>
PHP Arrays
What is an array?
When working with PHP, sooner or later, you might want to create many similar variables.
Instead of having many similar variables, you can store the data as elements in an array.
Each element in the array has its own ID so that it can be easily accessed.
There are three different kind of arrays:
• Numeric array - An array with a numeric ID key
• Associative array - An array where each ID key is associated with a value
• Multidimensional array - An array containing one or more arrays
Numeric Arrays
A numeric array stores each element with a numeric ID key.There are different ways to create a
numeric array.
Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
Example 2
In this example we assign the ID key manually:
$names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";
The ID keys can be used in a script:
<?php$names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";echo $names[1] . " and " . $names[2] . "
are ". $names[0] . "'s neighbors"; ?>
The code above will output:
Quagmire and Joe are Peter's neighbors
Associative Arrays
An associative array, each ID key is associated with a value.
Example 1
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
The ID keys can be used in a script:
<?php$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";echo "Peter is " .
$ages['Peter'] . " years old."; ?>
The code above will output:
Peter is 32 years old.
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array.
And each element in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
( "Griffin"=>array
( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output:
Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array (
[0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
Use a PHP Function
Now we will use the function in a PHP script:
<html>
<body>
<?php
function writeMyName() {
echo "Kai Jim Refsnes";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
echo " is my name."; ?>
</body>
</html>
The output of the code above will be:
Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my
name.
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
PHP Form Handling
<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>
The "welcome.php" file looks like this:
<html>
<body>
Welcome
<?php
echo
$_POST["name"];
?>.
<br />
You are
<?php echo $_POST["age"]; ?>
years old.
</body>
</html>
A sample output of the above script may be:
Welcome John. You are 28 years old.
PHP $_GET
• The $_GET variable is used to collect values from a form with
method="get".
• The $_GET variable is an array of variable names and values
sent by the HTTP GET method.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent could look something
like this:
http://www.w3schools.com/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will
automatically be the ID keys in the $_GET array):
Welcome
<?php echo $_GET["name"]; ?>.
<br />
You are <?php echo $_GET["age"]; ?> years old!
PHP $_POST
PHP $_POST
The $_POST variable is used to collect values from a form with method="post".
The $_POST Variable
The $_POST variable is an array of variable names and values sent by the HTTP POST method.
Example
<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age : <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL will not contain any
form data, and will look something like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the
names of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo
$_POST["age"]; ?> years old!
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo
$_REQUEST["age"]; ?> years old!
PHP Date()
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
<?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m-
d"); ?>
The output of the code above could be something like this:
2006/07/11 2006.07.11 2006-07-
11
The include() Function
The include() function takes all the text in a specified file and copies
it into the file that uses the include function.
Example 1
Assume that you have a standard header file, called "header.php".
To include the header file in a page, use the include() function, like this:
<html>
<body>
<?php include("header.php"); ?>
<h1>
Welcome to my home page
</h1>
<p>Some text</p>
</body>
</html>
PHP File Handling
The fopen() function is used to open files in PHP.
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
The file may be opened in one of the following modes:
Modes
Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it
doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already
exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already
exists
Example
The following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
PHP Cookies
setcookie(name, value, expire, path, domain);
Example
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> <body></body> </html>
How to Retrieve a Cookie Value?
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
PHP Sessions
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php
session_start();
?>
<html> <body></body> </html>
Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views']; ?>
</body>
</html>
Output:
Pageviews=1
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
PHP Sending E-mails
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
PHP MySQL Introduction
What is MySQL?
MySQL is a database. A database defines a structure for storing information.
In a database, there are tables. Just like HTML tables, database tables contain rows, columns, and cells.
Database Tables
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
PHP MySQL Connect to a Database
Connecting to a MySQL Database
Before you can access and work with data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function
Syntax
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is
"localhost:3306"
username Optional. Specifies the username to log in with. Default value is the
name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example
In the following example we store the connection in a variable ($con) for later use in the script. The "die"
part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed as soon as the script ends. To close the connection before, use
the mysql_close() function.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or
command to a MySQL connection.
Example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con) { die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{ echo "Database created"; } else { echo "Error creating database: " . mysql_error(); }
mysql_close($con);
?>
Simple Application
Html Coding
<form name="frm" action="login.php" method="post">
<table width="315" border="1" align="center" cellpadding="3" cellSpacing=0 style="BORDER-
COLLAPSE: collapse" borderColor=#d3d9ef >
<!--DWLayoutTable-->
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font class="emsg">
<p align="center"> </p>
</font> <br>
<tr>
<td height="38" colspan="2" align="center" valign="middle" class="header">Login
form</td>
</tr>
<tr>
<td width="105" height="30" align="center" valign="middle"
class="register">UserName</td>
<td width="192" align="left" valign="middle"> &nbsp; <input name="uname" type="text"
class="textbox" /></td>
</tr>
<tr>
<td height="30" align="center" valign="middle" class="register">Password</td>
<td align="left" valign="middle"> &nbsp; <input name="pass" type="password"
class="textbox"/></td>
</tr>
<tr class="login">
<td height="29" colspan="2" align="center" valign="middle" class="link">
<input name="Submit" type="submit" class="btn" value="Submit" /></td>
</tr>
<tr align="center">
<td height="50" colspan="2" valign="top"><? echo'<a href="register1.php"><img
src="register.gif" border="0"></a>'; ?>&nbsp;</td>
</tr>
</table>
</form>
PHP Coding :
<?php
session_start();//Session Start
ob_start();
?>
$link=mysql_connect("localhost",“username",“password");
//Connect Database
mysql_select_db(“Database Name“,$link);
//select Database
<?
if(isset($_POST['Submit']))
{
$user=array_key_exists('uname',$_POST)?$_POST['uname']:'';
$pwd=array_key_exists('pass',$_POST)?$_POST['pass']:'';
$sql="select * from register1 where username='$user' and password='$pwd'";
$result=mysql_query($sql);
if(mysql_num_rows($result))
{
Header(location:http://www.trichyrealestate.php/demo1/profile.ph
p);
//Redirect Into Next Page
}
else
{
$emsg='<font color="#FF0000" face="Arial"><strong> Error:Invalid
Entry</strong></font>';
}
}//submit
?>
Profile.PHP

Contenu connexe

Tendances (20)

Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP
PHPPHP
PHP
 
Php(report)
Php(report)Php(report)
Php(report)
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
php basics
php basicsphp basics
php basics
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 

En vedette

PHP tutorial | ptutorial
PHP tutorial | ptutorialPHP tutorial | ptutorial
PHP tutorial | ptutorialPTutorial Web
 
PHP7 - For Its Best Performance
PHP7 - For Its Best PerformancePHP7 - For Its Best Performance
PHP7 - For Its Best PerformanceXinchen Hui
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?Nikita Popov
 
PHP7.1 New Features & Performance
PHP7.1 New Features & PerformancePHP7.1 New Features & Performance
PHP7.1 New Features & PerformanceXinchen Hui
 
PHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainPHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainXinchen Hui
 
PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015Colin O'Dell
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorialalexjones89
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7Damien Seguy
 

En vedette (11)

PHP tutorial | ptutorial
PHP tutorial | ptutorialPHP tutorial | ptutorial
PHP tutorial | ptutorial
 
PHP7 - For Its Best Performance
PHP7 - For Its Best PerformancePHP7 - For Its Best Performance
PHP7 - For Its Best Performance
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
 
PHP7.1 New Features & Performance
PHP7.1 New Features & PerformancePHP7.1 New Features & Performance
PHP7.1 New Features & Performance
 
PHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainPHP7 - The New Engine for old good train
PHP7 - The New Engine for old good train
 
PHP 7
PHP 7PHP 7
PHP 7
 
PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 

Similaire à Php Tutorial

Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfShaimaaMohamedGalal
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.jssouridatta
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessoradeel990
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Gheyath M. Othman
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. wahidullah mudaser
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomerShivi Tomer
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersMohammed Mushtaq Ahmed
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners musrath mohammad
 
Introduction to PHP.pptx
Introduction to PHP.pptxIntroduction to PHP.pptx
Introduction to PHP.pptxSherinRappai
 

Similaire à Php Tutorial (20)

Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
Php
PhpPhp
Php
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
 
Php
PhpPhp
Php
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array.
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Introduction to PHP.pptx
Introduction to PHP.pptxIntroduction to PHP.pptx
Introduction to PHP.pptx
 

Plus de Dr. Ramkumar Lakshminarayanan

Plus de Dr. Ramkumar Lakshminarayanan (20)

IT security awareness
IT security awarenessIT security awareness
IT security awareness
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Web technology today
Web technology todayWeb technology today
Web technology today
 
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 
GPS in Android (in tamil)
GPS in Android (in tamil)GPS in Android (in tamil)
GPS in Android (in tamil)
 

Dernier

定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 

Dernier (20)

定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 

Php Tutorial

  • 1. PHP BASIC Dr. Ramkumar Lakshminarayanan
  • 2. What is PHP? • PHP stands for PHP: Hypertext Preprocessor • PHP is a server-side scripting language, like ASP • PHP scripts are executed on the server • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) • PHP is an open source software (OSS)
  • 3. What is a PHP File? • PHP files may contain text, HTML tags and scripts • PHP files are returned to the browser as plain HTML  • PHP files have a file extension of ".php", ".php3", or ".phtml"
  • 4. What is MySQL? • MySQL is a database server • MySQL is ideal for both small and large applications • MySQL supports standard SQL • MySQL compiles on a number of platforms
  • 5. PHP + MySQL • PHP combined with MySQL are cross-platform (means that you can develop in Windows and serve on a Unix platform) Why PHP? • Install an Apache server on a Windows or Linux machine • Install PHP on a Windows or Linux machine • Install MySQL on a Windows or Linux machine
  • 6. What do You Need? This tutorial will not explain how to install PHP, MySQL, or Apache Server. If your server supports PHP - you don't need to do anything! You do not need to compile anything or install any extra tools - just create some .php files in your web directory - and the server will parse them for you. Most web hosts offer PHP support.However, if your server does not support PHP, you must install PHP. Below is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php
  • 7. Download Apache for free here: http://httpd.apache.org/download.cgi Download PHP Download PHP for free here: http://www.php.net/downloads.php Download MySQL Database Download MySQL for free here: http://www.mysql.com/downloads/index.html Download Apache Server
  • 8. Basic PHP Syntax • A PHP scripting block always starts with <?php and ends with ?>. PHP scripting block can be placed anywhere in the document. <?php ?> • A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. <html> <body> <?php echo "Hello World"; ?> </body> </html>
  • 9. Comments in PHP <html> <body> <?php //This is a comment /* This is a comment block * /?></body> </html> •In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
  • 10. Variables in PHP • Variables are used for storing a values, like text strings, numbers or arrays. • When a variable is set it can be used over and over again in your script • All variables in PHP start with a $ sign symbol. • The correct way of setting a variable in PHP: <?php $txt = "Hello World!"; $number = 16; ?>
  • 11. Strings in PHP • String variables are used for values that contains character strings. <?php $txt="Hello World"; echo $txt; ?>
  • 12. PHP Operators Operator Description Example Result + Addition x=2 x+2 4 - Subtraction x=2 5-x 3 * Multiplication x=4 x*5 20 / Division 15/5 5/2 3 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 • Arithmetic Operators
  • 13. Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y
  • 14. Comparison Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true
  • 15. Logical Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true
  • 16. PHP If...Else Statements Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html>
  • 17. PHP Arrays What is an array? When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays: • Numeric array - An array with a numeric ID key • Associative array - An array where each ID key is associated with a value • Multidimensional array - An array containing one or more arrays
  • 18. Numeric Arrays A numeric array stores each element with a numeric ID key.There are different ways to create a numeric array. Example 1 In this example the ID key is automatically assigned: $names = array("Peter","Quagmire","Joe"); Example 2 In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; The ID keys can be used in a script: <?php$names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?> The code above will output: Quagmire and Joe are Peter's neighbors
  • 19. Associative Arrays An associative array, each ID key is associated with a value. Example 1 This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; The ID keys can be used in a script: <?php$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";echo "Peter is " . $ages['Peter'] . " years old."; ?> The code above will output: Peter is 32 years old.
  • 20. Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
  • 21. The array above would look like this if written to the output: Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
  • 22. Use a PHP Function Now we will use the function in a PHP script: <html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html>
  • 23. The output of the code above will be: Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name.
  • 24. PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling <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>
  • 25. The "welcome.php" file looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>. <br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> A sample output of the above script may be: Welcome John. You are 28 years old.
  • 26. PHP $_GET • The $_GET variable is used to collect values from a form with method="get". • The $_GET variable is an array of variable names and values sent by the HTTP GET method. Example <form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>
  • 27. When the user clicks the "Submit" button, the URL sent could look something like this: http://www.w3schools.com/welcome.php?name=Peter&age=37 The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array): Welcome <?php echo $_GET["name"]; ?>. <br /> You are <?php echo $_GET["age"]; ?> years old! PHP $_POST
  • 28. PHP $_POST The $_POST variable is used to collect values from a form with method="post". The $_POST Variable The $_POST variable is an array of variable names and values sent by the HTTP POST method. Example <form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> Enter your age : <input type="text" name="age" /> <input type="submit" /> </form>
  • 29. When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array): Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!
  • 30. The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!
  • 31. PHP Date() The PHP date() function formats a timestamp to a more readable date and time. Syntax date(format,timestamp) <?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m- d"); ?> The output of the code above could be something like this: 2006/07/11 2006.07.11 2006-07- 11
  • 32. The include() Function The include() function takes all the text in a specified file and copies it into the file that uses the include function. Example 1 Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this: <html> <body> <?php include("header.php"); ?> <h1> Welcome to my home page </h1> <p>Some text</p> </body> </html>
  • 33. PHP File Handling The fopen() function is used to open files in PHP. <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html>
  • 34. The file may be opened in one of the following modes: Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file x Write only. Creates a new file. Returns FALSE and an error if file already exists x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • 35. Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html
  • 36. Closing a File The fclose() function is used to close an open file: <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>
  • 37. PHP Cookies setcookie(name, value, expire, path, domain); Example 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> <body></body> </html>
  • 38. How to Retrieve a Cookie Value? <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>
  • 39. PHP Sessions Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body></body> </html>
  • 40. Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> Output: Pageviews=1
  • 41. Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?>
  • 42. PHP Sending E-mails <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>
  • 43. PHP MySQL Introduction What is MySQL? MySQL is a database. A database defines a structure for storing information. In a database, there are tables. Just like HTML tables, database tables contain rows, columns, and cells. Database Tables LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger
  • 44. PHP MySQL Connect to a Database Connecting to a MySQL Database Before you can access and work with data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function Syntax mysql_connect(servername,username,password); Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost:3306" username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process password Optional. Specifies the password to log in with. Default is ""
  • 45. Example In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
  • 46. Closing a Connection The connection will be closed as soon as the script ends. To close the connection before, use the mysql_close() function. <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>
  • 47. Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?>
  • 49. Html Coding <form name="frm" action="login.php" method="post"> <table width="315" border="1" align="center" cellpadding="3" cellSpacing=0 style="BORDER- COLLAPSE: collapse" borderColor=#d3d9ef > <!--DWLayoutTable--> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font class="emsg"> <p align="center"> </p> </font> <br> <tr> <td height="38" colspan="2" align="center" valign="middle" class="header">Login form</td> </tr> <tr> <td width="105" height="30" align="center" valign="middle" class="register">UserName</td> <td width="192" align="left" valign="middle"> &nbsp; <input name="uname" type="text" class="textbox" /></td> </tr> <tr> <td height="30" align="center" valign="middle" class="register">Password</td> <td align="left" valign="middle"> &nbsp; <input name="pass" type="password" class="textbox"/></td> </tr> <tr class="login"> <td height="29" colspan="2" align="center" valign="middle" class="link"> <input name="Submit" type="submit" class="btn" value="Submit" /></td> </tr> <tr align="center"> <td height="50" colspan="2" valign="top"><? echo'<a href="register1.php"><img src="register.gif" border="0"></a>'; ?>&nbsp;</td> </tr> </table> </form>
  • 50. PHP Coding : <?php session_start();//Session Start ob_start(); ?> $link=mysql_connect("localhost",“username",“password"); //Connect Database mysql_select_db(“Database Name“,$link); //select Database <? if(isset($_POST['Submit'])) { $user=array_key_exists('uname',$_POST)?$_POST['uname']:''; $pwd=array_key_exists('pass',$_POST)?$_POST['pass']:''; $sql="select * from register1 where username='$user' and password='$pwd'"; $result=mysql_query($sql); if(mysql_num_rows($result)) { Header(location:http://www.trichyrealestate.php/demo1/profile.ph p); //Redirect Into Next Page } else { $emsg='<font color="#FF0000" face="Arial"><strong> Error:Invalid Entry</strong></font>'; } }//submit ?>