SlideShare ist ein Scribd-Unternehmen logo
1 von 70
SANJU SONY KURIAN
What is PHP? 
➔ Personal Home Page is now Hypertext 
Preprocessor 
➔ Server-side Scripting language 
➔ Installed on more than 240 million websites and 
2.1 million web servers 
➔ Open Source
How HTML Pages Work
How PHP Pages Work
What you need 
➔ A Basic Knowledge in HTML 
➔ A Server 
➔ A Computer 
➔ And a lot of Caffeine
Setting Up a server Locally
Hello World 
<?php 
echo "<h1>Hello World!</h1>"; 
?>
<html> 
<head> 
<title>My first PHP page</title> 
</head> 
<body> 
<?php 
echo "<h1>Hello World!</h1>"; 
?> 
</body> 
</html>
Date and Time 
date("y") Year 
date("m/n") Month 
date("F") Month in Words 
date("d") Date 
date("l") Weekday 
date("H") Hour 
date("i") Minute 
date("s") Seconds
Important Lesson to take Back 
● You Concatenate in PHP with a “ . “ 
● There are functions for dates that you can simply use 
● What you can do with PHP is simply upto your imagination. 
You think i’m Wrong? 
Do you think you can make a website with 
different background images each day of 
the week and that works in all browsers?
Solution 
<body background="background_<?php echo date("w"); ?>.png"> 
</body> 
ITS FUN
!!! RIGHT???
Variables 
➔ Starts with the $ sign, followed by the name of the variable 
➔ Name must start with a letter or the underscore character 
➔ Cannot start with a number 
➔ Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) 
➔ Names are case sensitive ($y and $Y are two different variables) 
ALSO 
PHP is a Loosely Type Language
<?php 
$txt="Hello world!"; 
$x=5; 
$y=10.5; 
?>
Loops 
While 
$x = 1; 
while ($x <= 50) { 
echo "<p>This text is repeated 50 times</p>"; 
$x = $x + 1; 
}
Loops 
FOR 
for ($x=0; $x<=50; $x=$x+5) { 
echo '<p>variable $x is now = ' . $x . '</p>'; 
}
Conditions 
IF 
if (condition) { 
statement 
} 
if ... else ... 
if (condition) { 
statement 
} 
else { 
statement 
} 
switch ... case 
switch (expression) { 
case 1: 
statement 
break; 
case 2: 
statement 
break; 
default: 
statement 
break; 
}
Arrays 
explode(“,”,listname) 
eg: $months=”jan,feb,mar”; 
$arr_month=explode(“,”,$months); 
array() 
eg: $arr_month=array(“jan”,”feb”,”mar”);
Looping in Array 
for loop 
eg: for ($x=0; $x<3; $x++) { 
echo $arr_month[$x]; 
} 
foreach Loop 
eg: foreach($arr_months as $x) { 
echo $x 
}
FUNCTIONS 
1.One Variable 
2.More than one Variable
SUPERGLOBALS 
$GLOBALS 
$GLOBALS['<varname>'] 
eg: $x = 10; 
$y = 20; 
function addition() { 
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
}
SUPERGLOBALS 
$_SERVER 
$_SERVER['PHP_SELF']; 
$_SERVER['SERVER_NAME']; 
$_SERVER['HTTP_HOST']; 
$_SERVER['HTTP_REFERER']; 
$_SERVER['HTTP_USER_AGENT']; 
$_SERVER['SCRIPT_NAME'];
SUPERGLOBALS 
$_REQUEST 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> 
<input type="text" name="fname"> 
<input type="submit"> 
</form> 
<?php 
$name = $_REQUEST['fname']; 
echo $name; 
?>
SUPERGLOBALS 
$_GET 
get.php?name=sanju&email=sanjukurian13@gmail.com 
<?php 
echo “my name is “ . $_GET[‘name’] . ”and email id is “ . $_GET[‘id’]; 
?>
SUPERGLOBALS 
$_POST 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> 
Name: <input type="text" name="fname"> 
<input type="submit"> 
</form> 
<?php 
$name = $_POST['fname']; 
echo $name; 
?>AT
FORM HANDLING - POST 
CREATE A SIMPLE FORM THAT TAKES INPUT “NAME” AND “EMAIL ID” 
<form action="welcome.php" method="post"> 
Name: <input type="text" name="name"><br> 
E-mail: <input type="text" name="email"><br> 
<input type="submit"> 
</form> 
welcome.php 
Welcome <?php echo $_POST["name"]; ?><br> 
Your email address is: <?php echo $_POST["email"]; ?>
FORM HANDLING - GET 
CREATE A SIMPLE FORM THAT TAKES INPUT “NAME” AND “EMAIL ID” 
<form action="welcome.php" method="get"> 
Name: <input type="text" name="name"><br> 
E-mail: <input type="text" name="email"><br> 
<input type="submit"> 
</form> 
welcome.php 
Welcome <?php echo $_GET["name"]; ?><br> 
Your email address is: <?php echo $_GET["email"]; ?>
POST vs GET 
❏ Both GET and POST create an array 
(e.g. array( key => value, key2 => value2, key3 => value3, ...)) 
❏ Both are superglobals 
❏ $_GET is an array of variables passed to the current script via the URL parameters. 
❏ $_POST is an array of variables passed to the current script via the HTTP POST method. 
When to use GET and POST 
GET : When char < 2000 ; 
visibility != issue; 
bookmarking = possible; 
POST : char = Infinity ; 
while (char=sensitive || char==passwords); 
Visibility = issue; bookmarking = not_possible;
FILE Handling 
PHP readfile() 
<?php 
echo readfile(“sample.txt"); 
?>
FILE Handling 
Open File - fopen() 
Ex: 
$myfile = fopen(“sample.txt", "r") or die("Unable to open file!"); 
r Open a file for read only. 
w Open a file for write only. Erases the contents of the file or creates a new file if it 
doesn't exist. 
a Open a file for write only. The existing data in file is preserved. 
x Creates a new file for write only. 
r+ Open a file for read/write. 
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it 
doesn't exist. File pointer starts at the beginning of the file 
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at 
the end of the file. Creates a new file if the file doesn't exist 
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
FILE Handling 
Close File - fclose() 
Eg: fclose($myfile); 
Read File – fread(pointer, maxFileSizeToRead); 
Eg: fread($myfile,filesize("webdictionary.txt")); 
Read Single Line - fgets() 
Eg: echo fgets($myfile); 
Check End-Of-File - feof() 
Eg: while(!feof($myfile)) { 
echo fgets($myfile) . "<br>"; 
} 
Read Single Character - fgetc() 
Eg: while(!feof($myfile)) { 
echo fgetc($myfile); 
}
FILE Handling 
Create File - fopen() 
Eg: $myfile = fopen("testfile.txt", "w") 
If you use fopen() on a file that does not exist, it will create it, given that the file 
is opened for writing (w) or appending (a). 
Write to File - fwrite() 
Eg: $txt = "John Doen"; 
fwrite($myfile, $txt);
Somethings I Missed OUT 
SORTING AN ARRAY 
$mark=array("Physics"=>“78",“Maths"=>“87",“Chem"=>“56"); 
sort() - sort arrays in ascending order 
rsort() - sort arrays in descending order 
asort() - sort associative arrays in ascending order, according to the value 
ksort() - sort associative arrays in ascending order, according to the key 
arsort() - sort associative arrays in descending order, according to the value 
krsort() - sort associative arrays in descending order, according to the key
Hands-On 
Try 
 SERVER Commands 
 Create a form to read Email, and details about user and display it in same page 
and different page using GET,POST and REQUEST 
 Create a file using PHP and then store data in it. Read the data and try using 
other file handlers 
 Laugh on Monday, laugh for danger. 
Laugh on Tuesday, kiss a stranger. 
Laugh on Wednesday, laugh for a letter. 
Laugh on Thursday, something better. 
Laugh on Friday, laugh for sorrow. 
Laugh on Saturday, joy tomorrow.
Hands-On 
 Create a dictionary that can 
Store data to dictionary.txt as Key=Value 
Check for a word 
 Create a Guessing game. 
Use rand(min,max)
TABLES 
100 200 
400 500 
<table> 
<tr> 
<td>100</td> 
<td>200</td> 
</tr> 
<tr> 
<td>400</td> 
<td>500</td> 
</tr> 
</table>
FORM VALIDATION 
say,we have 
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> 
for a page test.php, we get 
<form method="post" action="test.php"> 
SO what if someone enters 
test.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E 
We get, 
<form method="post" action="test.php"/><script>alert('hacked')</script>
How to avoid $_SERVER[“PHP_SELF”] 
Exploits? 
htmlspecialchars() 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
So Now, 
<script>alert('hacked')</script> Becomes &quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt; 
Instead of showing an alert it just displays the text as it is. Just plain text
Lets try it out 
Also remember, 
● Trim White spaces 
● Remove Backlashes 
$data = trim($data); 
$data = stripslashes($data); 
$data = htmlspecialchars($data); 
return $data;
FORM - REQUIRED FIELDS 
QUITE SIMPLE: 
if (empty($_POST["name"])) { 
$nameErr = "Name is required"; 
and then display it with the text form 
<span class="error">* <?php echo $nameErr;?></span>
FORM - KEEPING VALUES 
To Keep values even after pressing the “SUBMIT” Button 
Just add a new parameter 
value="<?php echo $name;?>" 
And for Gender add 
Gender: 
<input type="radio" name="gender" 
<?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female 
<input type="radio" name="gender" 
<?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
SOME TERMS TO KNOW 
Database 
Column 
Table 
Redundancy 
Row 
Primary Key 
Foreign Key 
Index 
Compound Key
MYSQL Database 
MYSQL 
❏ open-source license 
❏ very powerful program 
❏ uses a standard form of the well-known SQL data language 
❏ works on many operating systems and with many languages including PHP,C,C++,JAVA,etc 
❏ very quickly and works well even with large data sets 
❏ very friendly to PHP 
❏ supports large databases, up to 50 million rows or more in a table 
❏ is customizable
Setting up a USER account in MYSQL
PHP Function for MYSQL 
SYNTAX: 
mysql_function(value,value,...); 
Like 
mysql_connect($connect); 
mysql_query($connect,"SQL statement");
So, it will look something like, 
<html> 
<body> 
<?php 
$retval = mysql_function(value, [value,...]); 
if( !$retval ) 
{ 
die ( "Error: a related error message" ); 
} 
// Otherwise MySQL or PHP Statements 
?> 
</body> 
</html>
MYSQL CONNECTION 
SYNTAX: 
connection mysql_connect(server,user,passwd,new_link,client_flag); 
server Optional - The host name running database server. If not specified, then default 
value is localhost:3036. 
user Optional - The username accessing the database. 
passwd Optional - The password of the user accessing the database. 
new_link Optional - If a second call is made to mysql_connect() with the same arguments, no 
new connection will be established; instead, the identifier of the already opened 
connection will be returned. 
client_flags Optional - A combination of the following constants: 
● MYSQL_CLIENT_SSL - Use SSL encryption 
● MYSQL_CLIENT_COMPRESS - Use compression protocol 
● MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names 
● MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity 
before closing the connection
<html> 
<head> 
<title>Connecting MySQL Server</title> 
</head> 
<body> 
<?php 
$dbhost = 'localhost:3036'; 
$dbuser = 'guest'; 
$dbpass = 'guest123'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
echo 'Connected successfully'; 
mysql_close($conn); 
?> 
</body> 
</html>
CREATE DATABASE 
SYNTAX: 
mysql_query( sql, connection ) 
sql Required - SQL query to create or delete a MySQL database 
CREATE DATABASE WORKSHOP 
connection Optional - if not specified, then last opened connection by 
mysql_connect will be used.
<html><body> 
<?php 
$dbhost = 'localhost'; 
$dbuser = 'root'; 
$dbpass = 'rootpassword'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
echo 'Connected successfully<br />'; 
$sql = 'CREATE DATABASE TUTORIALS'; 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not create database: ' . mysql_error()); 
} 
echo "Database TUTORIALS created successfullyn"; 
mysql_close($conn); 
?> 
</body></html>
SELECT DATABASE 
SYNTAX: 
mysql_select_db( db_name, connection ); 
db_name Required - Database name to be selected 
Connection Optional - if not specified then last opend connection by mysql_connect 
will be used.
<?php 
$dbhost = 'localhost:3036'; 
$dbuser = 'guest'; 
$dbpass = 'guest123'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
echo 'Connected successfully'; 
mysql_select_db( 'test_db' ); 
mysql_close($conn); 
?>
<?php 
$dbhost = 'localhost:3036'; 
$dbuser = 'root'; 
$dbpass = 'rootpassword'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) { 
die('Could not connect: ' . mysql_error()); } 
echo 'Connected successfully'; 
$sql = 'CREATE TABLE employee( '. 'emp_id INT NOT NULL AUTO_INCREMENT, '. 
'emp_name VARCHAR(20) NOT NULL, '. 
'emp_address VARCHAR(20) NOT NULL, '. 
'emp_salary INT NOT NULL, '. 
'join_date timestamp(14) NOT NULL, '. 
'primary key ( emp_id ))'; 
mysql_select_db('test_db'); 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not create table: ' . mysql_error()); 
} 
echo "Table employee created successfullyn"; 
mysql_close($conn); 
?>
DELETE DATABASE 
<?php 
$dbhost = 'localhost:3036'; 
$dbuser = 'root'; 
$dbpass = 'rootpassword'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
$sql = 'DROP DATABASE test_db'; 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not delete database db_test: ' . mysql_error()); 
} 
echo "Database deleted successfullyn"; 
mysql_close($conn); ?>
Deleting a Table 
<?php 
$dbhost = 'localhost:3036'; 
$dbuser = 'root'; 
$dbpass = 'rootpassword'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
$sql = 'DROP TABLE employee'; 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not delete table employee: ' . mysql_error()); 
} 
echo "Table deleted successfullyn"; 
mysql_close($conn); 
?>
Insert into 
<?php $dbhost = 'localhost:3036'; 
$dbuser = 'root'; 
$dbpass = 'rootpassword'; 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
$sql = 'INSERT INTO employee '. '(emp_name,emp_address, emp_salary, join_date) '. 
'VALUES ( "guest", "XYZ", 2000, NOW() )'; 
mysql_select_db('test_db'); 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not enter data: ' . mysql_error()); 
} 
echo "Entered data successfullyn"; 
mysql_close($conn); 
?>
Getting Data From MySQL Database 
mysql_fetch_array() - MYSQL_ASSOC and MYSQL_NUM 
<?php 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn ) { 
die('Could not connect: ' . mysql_error()); } 
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee'; 
mysql_select_db('test_db'); 
$retval = mysql_query( $sql, $conn ); 
if(! $retval ) 
{ 
die('Could not get data: ' . mysql_error()); } 
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { 
echo "EMP ID :{$row['emp_id']} <br> ". 
"EMP NAME : {$row['emp_name']} <br> ". 
"EMP SALARY : {$row['emp_salary']} <br> "; 
} 
mysql_free_result($retval); 
echo "Fetched data successfullyn"; 
mysql_close($conn); ?>
UPDATE DATABASE 
$emp_id = $_POST['emp_id']; 
$emp_salary = $_POST['emp_salary']; 
$sql = "UPDATE employee ". 
"SET emp_salary = $emp_salary ". 
"WHERE emp_id = $emp_id" ; 
mysql_select_db('test_db'); 
$retval = mysql_query( $sql, $conn ); 
DELETE VALUES 
$emp_id = $_POST['emp_id']; 
$sql = "DELETE FROM employee ". 
"WHERE emp_id = $emp_id" ; 
mysql_select_db('test_db'); 
$retval = mysql_query( $sql, $conn ); 
ORDER BY 
SELECT * FROM Persons ORDER BY age
MULTIDIMENSIONAL ARRAY 
ARUN 97 93 
KIRAN 87 85 
SAM 67 89 
RAMU 54 67 
$student= array 
( 
array(“ARUN",97,93), 
array("KIRAN",87,85), 
array("SAM",67,89), 
array("RAMU",54,67) 
); 
<?php 
for ($row = 0; $row < 4; $row++) 
{ 
echo "<p><b>STUDENT number $row</b></p>"; 
for ($col = 0; $col < 3; $col++) 
{ 
echo $student[$row][$col]; 
} 
} 
?>
Sending Mail 
mail ( to , subject , message , headers , parameters ) 
Parameter Description 
to Required. Specifies the recipient's email address(es) 
subject Required. Specifies the email's subject line. Note: This parameter 
cannot contain any newline characters 
message Required. Specifies the actual email body (the message to be sent). 
Each line should be separated with a LF (n). Lines should not 
exceed 70 characters 
headers Optional. Specifies additional headers such as "From", "Cc", "Bcc", 
etc. The additional headers should be separated with a CRLF (rn) 
parameters Optional. Specifies any additional parameters
Creating a Cookie 
Syntax 
setcookie(name, value, expire, path, domain); 
<?php 
setcookie("user", "Alex Porter", time()+3600); 
?>
Retrieve a Cookie Value 
Syntax 
$_COOKIE 
<?php 
// Print a cookie 
echo $_COOKIE["user"]; 
// A way to view all cookies 
print_r($_COOKIE); 
?>
PHP Sessions 
Starting a Session 
session_start(); 
Storing a Session Variable 
$_SESSION['views']=1; 
Destroying a Session 
if(isset($_SESSION['views'])) 
unset($_SESSION['views']); 
OR 
To delete all session data 
session_destroy();
Working with ZIP files 
<?php 
$zip = zip_open("test.zip"); 
if ($zip) 
{ 
while ($zip_entry = zip_read($zip)) 
{ 
echo "<p>"; 
echo "Name: " . zip_entry_name($zip_entry) . "<br />"; 
if (zip_entry_open($zip, $zip_entry)) 
{ 
echo "File Contents:<br/>"; 
$contents = zip_entry_read($zip_entry); 
echo "$contents<br />"; 
zip_entry_close($zip_entry); 
} 
echo "</p>"; } 
zip_close($zip); 
} ?>
PHP SimpleXML 
<?xml version="1.0" encoding="UTF-8"?> 
<note> 
<to>Mea</to> 
<from>Sanju</from> 
<heading>Just Saying</heading> 
<body>Loved Ma week at MEA!</body> 
</note> 
<?php 
$xml=simplexml_load_file("note.xml"); 
print_r($xml); 
?> 
SimpleXMLElement Object ( [to] => mea [from] => Sanju[heading] => Just Saying [body] => Loved Ma week at MEA! <?php OUTPUT 
$xml=simplexml_load_file("note.xml"); Mea 
echo $xml->to . "<br>"; Sanju 
echo $xml->from . "<br>"; Just Saying 
echo $xml->heading . "<br>"; Loved ma week at MEA! 
echo $xml->body; 
?>
<?php 
$xml=simplexml_load_file("note.xml"); 
echo $xml->getName() . "<br>"; 
foreach($xml->children() as $child) { 
echo $child->getName() . ": " . $child . "<br>"; 
} 
?> 
note 
to: Mea 
from: Sanju 
heading: Just saying
 
body: Loved Ma weekend at Mea
!!!
KEEP IN TOUCH
!!! 
SANJU SONY KURIAN 
about.me/sanjukurian 
sanjukurian13@gmail.com 
09496805304 
fb.com/sanjukurian

Weitere Àhnliche Inhalte

Was ist angesagt?

Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui documentRazvan Raducanu, PhD
 
5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur documentRazvan Raducanu, PhD
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHPSandy Smith
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & sessionJamshid Hashimi
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)Guni Sonow
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)Chhom Karath
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESIsmail Mukiibi
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern PerlDave Cross
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPprabhatjon
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitdSorabh Jain
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with phpMuhamad Al Imran
 

Was ist angesagt? (20)

Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Intro to php
Intro to phpIntro to php
Intro to php
 
7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document
 
5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
Php
PhpPhp
Php
 
File system
File systemFile system
File system
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
php part 2
php part 2php part 2
php part 2
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern Perl
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
My shell
My shellMy shell
My shell
 

Ähnlich wie Quick beginner to Lower-Advanced guide/tutorial in PHP

Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQLTiji Thomas
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting languageElmer Concepcion Jr.
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
What is PHPOffice?
What is PHPOffice?What is PHPOffice?
What is PHPOffice?Mark Baker
 
Php mysql
Php mysqlPhp mysql
Php mysqlAbu Bakar
 
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 Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture NotesSanthiya Grace
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1truptitasol
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomerShivi Tomer
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.jssouridatta
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)Chhom Karath
 

Ähnlich wie Quick beginner to Lower-Advanced guide/tutorial in PHP (20)

Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
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 For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
What is PHPOffice?
What is PHPOffice?What is PHPOffice?
What is PHPOffice?
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
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 Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)
 

KĂŒrzlich hochgeladen

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 

KĂŒrzlich hochgeladen (20)

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 

Quick beginner to Lower-Advanced guide/tutorial in PHP

  • 2. What is PHP? ➔ Personal Home Page is now Hypertext Preprocessor ➔ Server-side Scripting language ➔ Installed on more than 240 million websites and 2.1 million web servers ➔ Open Source
  • 5. What you need ➔ A Basic Knowledge in HTML ➔ A Server ➔ A Computer ➔ And a lot of Caffeine
  • 6. Setting Up a server Locally
  • 7. Hello World <?php echo "<h1>Hello World!</h1>"; ?>
  • 8. <html> <head> <title>My first PHP page</title> </head> <body> <?php echo "<h1>Hello World!</h1>"; ?> </body> </html>
  • 9.
  • 10. Date and Time date("y") Year date("m/n") Month date("F") Month in Words date("d") Date date("l") Weekday date("H") Hour date("i") Minute date("s") Seconds
  • 11. Important Lesson to take Back ● You Concatenate in PHP with a “ . “ ● There are functions for dates that you can simply use ● What you can do with PHP is simply upto your imagination. You think i’m Wrong? Do you think you can make a website with different background images each day of the week and that works in all browsers?
  • 12. Solution <body background="background_<?php echo date("w"); ?>.png"> </body> ITS FUN
!!! RIGHT???
  • 13. Variables ➔ Starts with the $ sign, followed by the name of the variable ➔ Name must start with a letter or the underscore character ➔ Cannot start with a number ➔ Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) ➔ Names are case sensitive ($y and $Y are two different variables) ALSO PHP is a Loosely Type Language
  • 14. <?php $txt="Hello world!"; $x=5; $y=10.5; ?>
  • 15. Loops While $x = 1; while ($x <= 50) { echo "<p>This text is repeated 50 times</p>"; $x = $x + 1; }
  • 16. Loops FOR for ($x=0; $x<=50; $x=$x+5) { echo '<p>variable $x is now = ' . $x . '</p>'; }
  • 17. Conditions IF if (condition) { statement } if ... else ... if (condition) { statement } else { statement } switch ... case switch (expression) { case 1: statement break; case 2: statement break; default: statement break; }
  • 18. Arrays explode(“,”,listname) eg: $months=”jan,feb,mar”; $arr_month=explode(“,”,$months); array() eg: $arr_month=array(“jan”,”feb”,”mar”);
  • 19. Looping in Array for loop eg: for ($x=0; $x<3; $x++) { echo $arr_month[$x]; } foreach Loop eg: foreach($arr_months as $x) { echo $x }
  • 20. FUNCTIONS 1.One Variable 2.More than one Variable
  • 21. SUPERGLOBALS $GLOBALS $GLOBALS['<varname>'] eg: $x = 10; $y = 20; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; }
  • 22. SUPERGLOBALS $_SERVER $_SERVER['PHP_SELF']; $_SERVER['SERVER_NAME']; $_SERVER['HTTP_HOST']; $_SERVER['HTTP_REFERER']; $_SERVER['HTTP_USER_AGENT']; $_SERVER['SCRIPT_NAME'];
  • 23. SUPERGLOBALS $_REQUEST <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input type="text" name="fname"> <input type="submit"> </form> <?php $name = $_REQUEST['fname']; echo $name; ?>
  • 24. SUPERGLOBALS $_GET get.php?name=sanju&email=sanjukurian13@gmail.com <?php echo “my name is “ . $_GET[‘name’] . ”and email id is “ . $_GET[‘id’]; ?>
  • 25. SUPERGLOBALS $_POST <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php $name = $_POST['fname']; echo $name; ?>AT
  • 26. FORM HANDLING - POST CREATE A SIMPLE FORM THAT TAKES INPUT “NAME” AND “EMAIL ID” <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> welcome.php Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?>
  • 27. FORM HANDLING - GET CREATE A SIMPLE FORM THAT TAKES INPUT “NAME” AND “EMAIL ID” <form action="welcome.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> welcome.php Welcome <?php echo $_GET["name"]; ?><br> Your email address is: <?php echo $_GET["email"]; ?>
  • 28. POST vs GET ❏ Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)) ❏ Both are superglobals ❏ $_GET is an array of variables passed to the current script via the URL parameters. ❏ $_POST is an array of variables passed to the current script via the HTTP POST method. When to use GET and POST GET : When char < 2000 ; visibility != issue; bookmarking = possible; POST : char = Infinity ; while (char=sensitive || char==passwords); Visibility = issue; bookmarking = not_possible;
  • 29. FILE Handling PHP readfile() <?php echo readfile(“sample.txt"); ?>
  • 30. FILE Handling Open File - fopen() Ex: $myfile = fopen(“sample.txt", "r") or die("Unable to open file!"); r Open a file for read only. w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. a Open a file for write only. The existing data in file is preserved. x Creates a new file for write only. r+ Open a file for read/write. w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
  • 31. FILE Handling Close File - fclose() Eg: fclose($myfile); Read File – fread(pointer, maxFileSizeToRead); Eg: fread($myfile,filesize("webdictionary.txt")); Read Single Line - fgets() Eg: echo fgets($myfile); Check End-Of-File - feof() Eg: while(!feof($myfile)) { echo fgets($myfile) . "<br>"; } Read Single Character - fgetc() Eg: while(!feof($myfile)) { echo fgetc($myfile); }
  • 32. FILE Handling Create File - fopen() Eg: $myfile = fopen("testfile.txt", "w") If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a). Write to File - fwrite() Eg: $txt = "John Doen"; fwrite($myfile, $txt);
  • 33. Somethings I Missed OUT SORTING AN ARRAY $mark=array("Physics"=>“78",“Maths"=>“87",“Chem"=>“56"); sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key
  • 34. Hands-On Try  SERVER Commands  Create a form to read Email, and details about user and display it in same page and different page using GET,POST and REQUEST  Create a file using PHP and then store data in it. Read the data and try using other file handlers  Laugh on Monday, laugh for danger. Laugh on Tuesday, kiss a stranger. Laugh on Wednesday, laugh for a letter. Laugh on Thursday, something better. Laugh on Friday, laugh for sorrow. Laugh on Saturday, joy tomorrow.
  • 35. Hands-On  Create a dictionary that can Store data to dictionary.txt as Key=Value Check for a word  Create a Guessing game. Use rand(min,max)
  • 36. TABLES 100 200 400 500 <table> <tr> <td>100</td> <td>200</td> </tr> <tr> <td>400</td> <td>500</td> </tr> </table>
  • 37. FORM VALIDATION say,we have <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> for a page test.php, we get <form method="post" action="test.php"> SO what if someone enters test.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E We get, <form method="post" action="test.php"/><script>alert('hacked')</script>
  • 38. How to avoid $_SERVER[“PHP_SELF”] Exploits? htmlspecialchars() <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> So Now, <script>alert('hacked')</script> Becomes &quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt; Instead of showing an alert it just displays the text as it is. Just plain text
  • 39. Lets try it out Also remember, ● Trim White spaces ● Remove Backlashes $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;
  • 40. FORM - REQUIRED FIELDS QUITE SIMPLE: if (empty($_POST["name"])) { $nameErr = "Name is required"; and then display it with the text form <span class="error">* <?php echo $nameErr;?></span>
  • 41. FORM - KEEPING VALUES To Keep values even after pressing the “SUBMIT” Button Just add a new parameter value="<?php echo $name;?>" And for Gender add Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  • 42. SOME TERMS TO KNOW Database Column Table Redundancy Row Primary Key Foreign Key Index Compound Key
  • 43. MYSQL Database MYSQL ❏ open-source license ❏ very powerful program ❏ uses a standard form of the well-known SQL data language ❏ works on many operating systems and with many languages including PHP,C,C++,JAVA,etc ❏ very quickly and works well even with large data sets ❏ very friendly to PHP ❏ supports large databases, up to 50 million rows or more in a table ❏ is customizable
  • 44. Setting up a USER account in MYSQL
  • 45. PHP Function for MYSQL SYNTAX: mysql_function(value,value,...); Like mysql_connect($connect); mysql_query($connect,"SQL statement");
  • 46. So, it will look something like, <html> <body> <?php $retval = mysql_function(value, [value,...]); if( !$retval ) { die ( "Error: a related error message" ); } // Otherwise MySQL or PHP Statements ?> </body> </html>
  • 47. MYSQL CONNECTION SYNTAX: connection mysql_connect(server,user,passwd,new_link,client_flag); server Optional - The host name running database server. If not specified, then default value is localhost:3036. user Optional - The username accessing the database. passwd Optional - The password of the user accessing the database. new_link Optional - If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned. client_flags Optional - A combination of the following constants: ● MYSQL_CLIENT_SSL - Use SSL encryption ● MYSQL_CLIENT_COMPRESS - Use compression protocol ● MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names ● MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection
  • 48. <html> <head> <title>Connecting MySQL Server</title> </head> <body> <?php $dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($conn); ?> </body> </html>
  • 49. CREATE DATABASE SYNTAX: mysql_query( sql, connection ) sql Required - SQL query to create or delete a MySQL database CREATE DATABASE WORKSHOP connection Optional - if not specified, then last opened connection by mysql_connect will be used.
  • 50. <html><body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully<br />'; $sql = 'CREATE DATABASE TUTORIALS'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create database: ' . mysql_error()); } echo "Database TUTORIALS created successfullyn"; mysql_close($conn); ?> </body></html>
  • 51. SELECT DATABASE SYNTAX: mysql_select_db( db_name, connection ); db_name Required - Database name to be selected Connection Optional - if not specified then last opend connection by mysql_connect will be used.
  • 52. <?php $dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db( 'test_db' ); mysql_close($conn); ?>
  • 53. <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $sql = 'CREATE TABLE employee( '. 'emp_id INT NOT NULL AUTO_INCREMENT, '. 'emp_name VARCHAR(20) NOT NULL, '. 'emp_address VARCHAR(20) NOT NULL, '. 'emp_salary INT NOT NULL, '. 'join_date timestamp(14) NOT NULL, '. 'primary key ( emp_id ))'; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create table: ' . mysql_error()); } echo "Table employee created successfullyn"; mysql_close($conn); ?>
  • 54. DELETE DATABASE <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete database db_test: ' . mysql_error()); } echo "Database deleted successfullyn"; mysql_close($conn); ?>
  • 55. Deleting a Table <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP TABLE employee'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete table employee: ' . mysql_error()); } echo "Table deleted successfullyn"; mysql_close($conn); ?>
  • 56. Insert into <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'INSERT INTO employee '. '(emp_name,emp_address, emp_salary, join_date) '. 'VALUES ( "guest", "XYZ", 2000, NOW() )'; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfullyn"; mysql_close($conn); ?>
  • 57. Getting Data From MySQL Database mysql_fetch_array() - MYSQL_ASSOC and MYSQL_NUM <?php $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT emp_id, emp_name, emp_salary FROM employee'; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "EMP ID :{$row['emp_id']} <br> ". "EMP NAME : {$row['emp_name']} <br> ". "EMP SALARY : {$row['emp_salary']} <br> "; } mysql_free_result($retval); echo "Fetched data successfullyn"; mysql_close($conn); ?>
  • 58. UPDATE DATABASE $emp_id = $_POST['emp_id']; $emp_salary = $_POST['emp_salary']; $sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); DELETE VALUES $emp_id = $_POST['emp_id']; $sql = "DELETE FROM employee ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); ORDER BY SELECT * FROM Persons ORDER BY age
  • 59.
  • 60. MULTIDIMENSIONAL ARRAY ARUN 97 93 KIRAN 87 85 SAM 67 89 RAMU 54 67 $student= array ( array(“ARUN",97,93), array("KIRAN",87,85), array("SAM",67,89), array("RAMU",54,67) ); <?php for ($row = 0; $row < 4; $row++) { echo "<p><b>STUDENT number $row</b></p>"; for ($col = 0; $col < 3; $col++) { echo $student[$row][$col]; } } ?>
  • 61. Sending Mail mail ( to , subject , message , headers , parameters ) Parameter Description to Required. Specifies the recipient's email address(es) subject Required. Specifies the email's subject line. Note: This parameter cannot contain any newline characters message Required. Specifies the actual email body (the message to be sent). Each line should be separated with a LF (n). Lines should not exceed 70 characters headers Optional. Specifies additional headers such as "From", "Cc", "Bcc", etc. The additional headers should be separated with a CRLF (rn) parameters Optional. Specifies any additional parameters
  • 62.
  • 63. Creating a Cookie Syntax setcookie(name, value, expire, path, domain); <?php setcookie("user", "Alex Porter", time()+3600); ?>
  • 64. Retrieve a Cookie Value Syntax $_COOKIE <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>
  • 65. PHP Sessions Starting a Session session_start(); Storing a Session Variable $_SESSION['views']=1; Destroying a Session if(isset($_SESSION['views'])) unset($_SESSION['views']); OR To delete all session data session_destroy();
  • 66. Working with ZIP files <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>"; echo "Name: " . zip_entry_name($zip_entry) . "<br />"; if (zip_entry_open($zip, $zip_entry)) { echo "File Contents:<br/>"; $contents = zip_entry_read($zip_entry); echo "$contents<br />"; zip_entry_close($zip_entry); } echo "</p>"; } zip_close($zip); } ?>
  • 67. PHP SimpleXML <?xml version="1.0" encoding="UTF-8"?> <note> <to>Mea</to> <from>Sanju</from> <heading>Just Saying</heading> <body>Loved Ma week at MEA!</body> </note> <?php $xml=simplexml_load_file("note.xml"); print_r($xml); ?> SimpleXMLElement Object ( [to] => mea [from] => Sanju[heading] => Just Saying [body] => Loved Ma week at MEA! <?php OUTPUT $xml=simplexml_load_file("note.xml"); Mea echo $xml->to . "<br>"; Sanju echo $xml->from . "<br>"; Just Saying echo $xml->heading . "<br>"; Loved ma week at MEA! echo $xml->body; ?>
  • 68. <?php $xml=simplexml_load_file("note.xml"); echo $xml->getName() . "<br>"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br>"; } ?> note to: Mea from: Sanju heading: Just saying
 body: Loved Ma weekend at Mea
!!!
  • 69.
  • 70. KEEP IN TOUCH
!!! SANJU SONY KURIAN about.me/sanjukurian sanjukurian13@gmail.com 09496805304 fb.com/sanjukurian

Hinweis der Redaktion

  1. file with the extension .php that contains a combination of HTML tags and scripts that run on a web server.
  2. Browser gets the reply as HTML Page Source Code doesnt SHow PHP What you learn is to write commands to a server!
  3. SERVER is Hardware or Software?
  4. check source code NO PHP Code the client (the browser) only sees the result!
  5. PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
  6. $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. $_SERVER['PHP_SELF'] Returns the filename of the currently executing script $_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI) the server is using $_SERVER['SERVER_ADDR'] Returns the IP address of the host server $_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3schools.com) $_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24) $_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as HTTP/1.1) $_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as POST) $_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as 1377687496) $_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string $_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request $_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1) $_SERVER['HTTP_HOST'] Returns the Host header from the current request $_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because not all user-agents support it) $_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol $_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page $_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to communicate with the web server $_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script $_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com) $_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server for communication (such as 80) $_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are added to server-generated pages $_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script $_SERVER['SCRIPT_NAME'] Returns the path of the current script $_SERVER['SCRIPT_URI'] Returns the URI of the current page
  7. PHP $_REQUEST is used to collect data after submitting an HTML form.
  8. Try making them use a instead of w for file open etc
  9. Check using Read the line one by one and then explode the line using “=“ and check the array first one for the word , if yes print the meaning
  10. 100200300400500600700800900 <table> <tr> <td>100</td> <td>200</td> <td>300</td> </tr> <tr> <td>400</td> <td>500</td> <td>600</td> </tr> <tr> <td>700</td> <td>800</td> <td>900</td> </tr> </table>
  11. To protect the form from hackers and spammers any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data
  12. The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
  13. validation1.php validation2.php
  14. validation3.php
  15. validation4.php
  16. MySQL is released under an open-source license. So you have nothing to pay to use it. MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages. MySQL uses a standard form of the well-known SQL data language. MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc. MySQL works very quickly and works well even with large data sets. MySQL is very friendly to PHP, the most appreciated language for web development. MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB). MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.
  17. mysql_fetch_assoc($retval) mysql_free_result($retval);
  18. When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
  19. The unset() function is used to free the specified session variable: Note: session_destroy() will reset your session and you will lose all your stored session data.
  20. <?php $zip = zip_open("test.zip"); if ($zip)   {   while ($zip_entry = zip_read($zip))     {     echo "<p>";     echo "Name: " . zip_entry_name($zip_entry) . "<br />";     if (zip_entry_open($zip, $zip_entry))       {       echo "File Contents:<br/>";       $contents = zip_entry_read($zip_entry);       echo "$contents<br />";       zip_entry_close($zip_entry);       }     echo "</p>";   } zip_close($zip); } ?>