You are on page 1of 80

Intro to PHP

A brief overview – Sushil Kumar


What is PHP?
 PHP ("PHP: Hypertext Preprocessor") is
a widely-used Open Source general-
purpose scripting language that is
especially suited for Web development
and can be embedded into HTML.

<? echo “HI!”; ?>


How it works
 PHP is installed on web server
 Our web server is Apache
 Server parses files based on
extensions
 Returns plain HTML, no code
How To – The Basics
Need to name files is a .php extension
Example: index.php, mypage.php

Open and close tags: <? ?>


Was: <?php ?>

 Save file to server, view in a browser


Hello World
helloworld.php

<? echo “Hello World!”; ?>


Variables
Variables are like a cup

The same cup can hold


lots of different things

Same with variables


Variables
In PHP, you create a variable with a
dollar sign and some text.
Usually the text will be something
descriptive of what it is going to hold.

$name = “susheel”;
$dept = “mca”;
$local_addr = “kanpur”;
Variables

$name = “Josiah”;
$dob = “1/1/23”;
$age = 84;
Conditional statement
 Like any other language php also use
if else, for, while, switch case etc
If statements
 <?php
$a=8;
$b=8;
if ($a > $b) {
    echo "a is bigger than b";
} else {
    echo "a is NOT bigger than b";
}
?>
while loop
<?php
$i = 1;
while ($i <= 10)
  {
     echo $i++;  
}
?>
Include()
 Include function is used to include a
file .
 It can include any type of file.

The syntax is
include “file name”;
Include()
<?php
echo “hi “;
?>

 Save it with hi.php


Include()
<?
include “hi.php”;
echo “susheel”;
?>
Functions
Getting PHP to do some action for you

<?php
phpinfo();
?>
Functions
 <?php
function square($num)
{
    return $num * $num;
}
echo square(4);  
?>
Advance functions of php
Date/time function
<?
$d=date(j:n:Y);
echo $d;
?>
Date/time function
D A textual representation
of a day, three letters
(mon to sun)
l The day of the week
w Numeric representation
of the day of the week
d Day of the month(01 to
F 31)
Name of the month
(january to december )
Date/time function
 Try these

A,a,g,G,h,H,I,s,y
,Y
Example:-
<?php
$t=date(A);
echo $t;
?>
E-mail
 One of the major uses of a server side
scripting language is to provide a way
of sending e-mail from the server and,
in particular, to take form input and
output it to an e-mail address. In this
part I will show you how to send e-mail
messages using PHP.
E-mail

To send e-mail by php we use fuction


mail()
The syntax is:--

 mail($to,$subject,$body,$headers);
E-mail
 $to = “softfiesta@incordhbti.com";
$subject = "PHP Is Great";
$body = "PHP is one of the best
scripting languages around";
$headers = "From:
susheelhbti@gmail.com";

mail($to,$subject,$body,$headers);
echo "Mail sent to $to";
Functions
We’ll talk more about function later.
Passing information
 <a href =“submit.php?id=57”
>submit</a>

 <?
 $id=@$_request[‘id’];
 Echo $id;
 ?>
Passing information method
2
 By session variable
session
 Session:- Session support in PHP
consists of a way to preserve certain
data across subsequent accesses. This
enables you to build more customized
applications and increase the appeal
of your web site.
session
 Start a session

session_start();
Session
 Store info in session

$_session[‘id’]=$id;
session
 Retrieving information from session

echo $_session[‘id’];
session
 Retrieving information from session

$id=$_session[‘id’];

echo $id;
session
 To register a session

session_register("id");
session
Session_is_registered(id)

Return true if register otherwise return


false
session
 Destroy a session

session_destroy();
Implementation of session
To implementation you must start
session at each page where session is
being used

To session start session_start() is used


.It must be type above the <html> tag
or the top of the page
Implementation of session
 If session has started successful you
can store information in the session
Implementation of session
An example to use session
<?
Session_start();
$_SESSION[‘id’]=675;
?>
Implementation of session
 <?php
 session_start();
 echo $_SESSION['id'];
 ?>
Implementation of session

<?php
session_start();
echo $_SESSION['id'];
?>
Implementation of session
 Destroy a session

<?php
session_start();
session_destroy();
?>
Redirect to a page
Header function is used to
redirect

header("location:index.php");
Redirect to a page
<?
session_start();
if(!session_is_registered(id)){
header("location:index.php");
}
?>
Problem with session
 Warning: session_start(): Cannot send
session cache limiter - headers already
sent (output started at D:\mysite\page
1 s.php:3) in D:\mysite\page 1 s.php
on line 7
references
 www.phpeasystep.com
A Basic Form (Design view)
A Basic Form (code view)
How we do things with PHP:

basicform.html

<form method=“POST”
action=“output.php”>
<input type=“text” name=“name”>
<input type=“text” name=“age”>
<input type=“submit”>
</form>
A Basic Form
Weave HTML and PHP

output.php
<html><body>
<?
$name = $_POST[‘name’];
$age = $_POST[‘age’];
echo “My name is $name and I am $age years
old”;
?>
</body></html>
A Basic Form
Capturing the data in output.php

Variables:
 $_POST[‘name’]
 $_POST[‘age’]
Data Validation

We’ll talk more about validating user


input later.
A Basic Form
Outputting to the screen is nice, but
boring

We could email the results

Let’s store data in a database


Layers of a Database
 Server
 Database
 Tables
 Fields/Columns
 Records
 Data
How to Get a Database
 Request a MySQL Database
Request a MySQL Database
You will need:
 Server name
 Database name
 Username
 Password
Connecting to DB from PHP
Create one connection script:
dbconn.php
<?
$host=“ host name”;
$user=“user name”;
$pass=“ password “;
mysql_connect($server,$user,$pw);
$db=“data base name “;
mysql_select_db($db);
?>
Connecting to DB from PHP
Create one connection script:
dbconn.php
<?
$host=“ localhost”;
$user=“root”;
$pass=“ “;
mysql_connect($server,$user,$pw);
$db=“data base name “;
mysql_select_db($db);
?>
Connecting to DB from PHP
Remember, “Be Lazy!”

At the top of each file that needs the


DB:

<? require(“dbconn.php”); ?>


Database Table
Table named ‘info’ has two fields, name and age

Use a SQL INSERT statement:

$sql =
“INSERT INTO
info (name,age)
values (‘$name’, ‘$age’)”;
Database Table
Send it to the Database:

mysql_query($sql);
The Whole Picture
dbinsert.php

<? require(“dbconn.php”);
$name = $_POST[‘name’];
$age = $_POST[‘age’];
$sql = “INSERT into info (name,age)
values(‘$name’, ‘$age’);”
mysql_query($sql);
?>
<html><body>
Thank you, your name and age were received.
</body></html>
The Whole Picture - Fancier
fancydbinsert.php
<? require(“dbconn.php”);
$name = $_POST[‘name’];
$age = $_POST[‘age’];
$sql = “INSERT into info (name,age) values(‘$name’,
‘$age’);”
$success = mysql_query($sql);
?>
<html><body>
<? if($success)
{ echo “Thank you, your name and age were received.”; }
else
{ echo “Sorry, your info wasn’t received, please contact …”; }
?>
</body></html>
HTML REVISITED
 Create a table by html
 use of &nbsp;
 simple formating
 Inclusion css
Create an Output Page
 Connect to the Server
 Do a query of the data
 Programmatically write the data to a
page
 View the page in a browser
 Let’s see how to do it
Connect to the Server
First, include our connection script:
<? require(“dbconn.php”); ?>
Do a Query of the Data
This time we use SELECT

$sql = “SELECT name, age FROM info”;

Or if you have many fields and want to be LAZY!

$sql = “SELECT * from info”;


Programmatically Write the
Data
Here’s the only hard part:

<table border=“1”>
<? $result = mysql_query($sql);
while($table = mysql_fetch_object($result))
{
echo “<tr><td>”;
echo $table->name;
echo “</td><td>”;
echo $table->age;
echo “</td></tr>”;
}
?>
</table>
Putting it All Together
statuspage.php
<? require(“dbconn.php”);
$sql = “SELECT * FROM info”;
$result = mysql_query($sql, $conn);
?>
<html><body>
<table border=“1”>
<? while($table = mysql_fetch_object($result))
{ echo “<tr><td>”;
echo $table->name;
echo “</td><td>”;
echo $table->age;
echo “</td></tr>”;
}
?>
<table>
</body></html>
I Hate Objects!
If you don’t like using
mysql_fetch_object:
 mysql_fetch_row($result)
Putting it All Together
statuspage.php
<? require(“dbconn.php”);
$sql = “SELECT * FROM info”;
$result = mysql_query($sql);
?>
<html><body>
<table border=“1”>
<? while($table = mysql_fetch_row($result))
{ echo “<tr><td>”;
echo $table[0];
echo “</td><td>”;
echo $table[1];
echo “</td></tr>”;
}
?>
<table>
</body></html>
Data Validation
 Very Important!
 Without it, your site and all others can
be hacked!
 PHP makes it easier
Data Validation

 Check that you’re getting what you


expect
 Check that you’re getting the length
you expect
 Don’t trust JavaScript
 Do client side validation and server
side validation
Data Validation

client side validation


 Use java script

Client side validation is not secure


because some browser like opera can
disable it
Data Validation
 Do client side validation because it can
not be disabled by user
Data Validation
 Get what you expect to get
 Don’t change it, give error message

Example: (validinsert.php)
Age, should be less than 110, and numeric.
Reject anything else
if(strlen($age)>3){ //error message }
if(!is_int($age)){ //error message }
if($age>110 || $age<18){ //error message }
Data Validation

ctype_alnum -- Check for 
alphanumeric character(s) 
ctype_alpha -- Check for alphabetic 
character(s) 
ctype_digit -- Check for numeric 
character(s)
Data Validation
Get the length you expect

<input type=“text” name=“username”


maxlength=“8”>

Make sure the username is no


longer than 8

if(strlen($username)>8)){ //error message }


Mysql-php function
 mysql_close -- Close MySQL connection
 mysql_connect -- Open a connection to a MySQL
Server
 mysql_create_db -- 
 mysql_db_name -- Get result data
 mysql_db_query -- Send a MySQL query
 mysql_drop_db -- Drop (delete) a MySQL database
 mysql_errno -- Returns the numerical value of the
error message from previous MySQL operation
 mysql_error 
 mysql_fetch_object -- Fetch a result row as an
object
 mysql_query -- Send a MySQL query
Thanks
I think that’s enough

webconcevoier@incordhbti.com

You might also like