A Quick beginner to Lower-Advanced tutorial in PHP. Prepared for a session at MEA Perinthalmanna. Covers basic tutorials and concepts and covers some advanced topics.
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
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?
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
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;
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)
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 "><script>alert('hacked')</script>
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
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
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.
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.
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
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
Notas do Editor
file with the extension .php that contains a combination of HTML tags and scripts that run on a web server.
Browser gets the reply as HTML Page
Source Code doesnt SHow PHP
What you learn is to write commands to a server!
SERVER is Hardware or Software?
check source code
NO PHP Code
the client (the browser) only sees the result!
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
$_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
PHP $_REQUEST is used to collect data after submitting an HTML form.
Try making them use a instead of w for file open etc
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
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
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
validation1.php
validation2.php
validation3.php
validation4.php
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.
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 agosetcookie("user", "", time()-3600);?>
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.