SlideShare a Scribd company logo
Learn
PHP
with
PSK
Learn PHP with Prabhjot Singh Kainth.
Prabhjot Singh Kainth is currently pursuing B.E in CSE from Thapar
University Patiala.
H Hostel Thapar University Patiala.
PRABHJOT SINGH KAINTH 2
ABOUT THE BOOK
This book is being written by Prabhjot Singh Kainth, currently pursuing
B.E in Computer Science from Thapar University Patiala.
He has written many other books on various languages.
This book is purely his own work, no code have been copied from any
other book/source.
This books doesn`t go in much details of PHP.It will only provide you
information necessary to start developing web pages.
This books comes with a zip file attached which contains some
examples.
Hope you will enjoy his small effort.
You can contact him through following ways:
Email:prabhjot409069@gmail.com
Facebook:www.facebook.com/prab409069
Mobile: +919814181928
PRABHJOT SINGH KAINTH 3
Php stands for Hypertext preprocessor.
It is a server side scripting language (which means all the actions performed by the
script will be processed by server not the client).
Php is basically used to create dynamic websites (websites which return dynamic
data for example: facebook, google, youtube etc.).
You can find various definition and advantages of PHP in lots of books.
What are the data types involved in php?
There are integer, character, string, Boolean and float data type.
There is no such reserved keyword for data type (for ex: we have int for integer,
float for float data type in c/c++).
So how do we differentiate data types?
All data types are stored as variable in php with a $ sign.
Example will make things clear for you ($prab is the name of the variable you can
use anything instead of prab)
$prab=10; //makes it integer type
$prab=”Prabhjot”; //makes it string type
$prab=10.0; //makes it float type
$prab=true; //makes it Boolean type
// is used for comments.
How to print data in php?
You can use print but echo is more often used.
For example:
echo “Prabhjot”;
PRABHJOT SINGH KAINTH 4
How to write php scripts?
All php script starts with <?php and ends with ?> as show below.
<?php
//your code
?>
Writing your first php script?
<?php
echo “My name is Prabhjot singh”;
?>
Result:
My name is Prabhjot singh
Now working more with variables:
$a=10;
$b=20;
echo “a”; //will print a not the value of a which is 10.
echo “$a”; // this will print 10 not a.
or simply type echo $a;
“ ” is used to print strings but php takes anything as variable if it starts with $
sign.
A simple program to add 2 numbers:
<?php
$a=10;
$b=20;
$c=$a+$b; //note if you simply use a+b it will return an error (discussed later why)
echo “$c”; or echo $c;
?>
How to concatenate strings with variables (suppose you want to print: Addition of
a and b is 30.how to do this)
For this we have a concatenation operator “.”, dot operator is used to
concatenate strings.
PRABHJOT SINGH KAINTH 5
In above example:
echo “Addition of a and b is”. $c ;
// will print: Addition of a and b is 30
You can even concatenate two strings using this operator.
Moving onto loops and decisions:
The syntax remains the same as we have in c/c++ only difference comes is $ sign
for variables. For example:
For loop:
for($i=0;$i<=10;$i++)
{
echo $i;
}
Switch statements:
switch($i)
{
case 1:
echo “one”;
break;
default:
echo “wrong choice”;
break;
}
PRABHJOT SINGH KAINTH 6
Moving onto Arrays
There are two types of array in php:
1. Indexed: Simple arrays as we have in c/c++.
2. Associative: This type of array is also referred to as a hash or map. With
associative arrays, each element is referenced by a string index.
You will get to know the difference between them later.
Arrays can be declared in following ways in php:
$arr=array(“apple”,”orange”,”mango”); //indexed array
$arr=array(“name”=>”Prabhjot”,”rollno”=>101203073,”branch”=>”Computer”);
//associative array
How to access elements of array?
echo $arr[0]; // will print apple in case of indexed array
echo $arr[“name”]; // will print Prabhjot .
You can also add items to an array:
$arr[3]=”grapes”;
$arr[0]=”banana”; // note it will replace apple
If you want to print an array whole in once (all the elements without loop),you can
use print_r() function:
For example: print_r($arr); // it will print apple orange mango.
You can use html tags within Php also,this process is known as fusion.
For example:
echo “Prabhjot”.’<br>’.”singh”;
This will print Prabhjot and singh in next line as breakline tag is being used.
echo "prabhjot".'<b>'."singh".'</b>';
This will print Prabhjot and singh in bold letters.
Please note html tags are used with single quote.
PRABHJOT SINGH KAINTH 7
Some more functions related to Strings and Arrays
printf() and sprintf() functions:
As we use in c,we can use printf in the same way.
For ex: printf(“Answer is %d”,$i); //where i is an integer type.
You can also specify the precision of a floating point number as we do in c.
For ex: printf(“%0.4f”,123.45678) will result in 123.4567
Now if we want to store result and not to print it,sprint() is used.
$psk=sprintf(file_get_contents(“psk.txt”));
How to count elements of an Array?
Using count function.Suppose name of our array is arr.
$ctr=count($arr);
echo $ctr;
For each loop in array:
$arr= array( “cricket”, “football”, “Tennis”, “Hockey” );
foreach ( $arr as $val )
{
echo $val . “ < br/ > ”;
}
Where $val can be name of any variable.This will print all the elements of array.
Multi dimension array are also there but it is not necessary for web
development right now.
You can sort,merge and push-pop an array by following functions:
sort($arr); //sorting in ascending order for indexed array.
rsort($arr); //sorting in descending order for indexed array.
asort($arr); //sorting in ascending order for associative array.
arsort($arr); //sorting in descending order for associative array.
array_push($arr,”badminton”); // to insert an element at the end of the array.
array_pop($arr); // will pop an item from the end of the array.
array_merge($arr1,$arr2); // will merge two arrays named arr1 and arr2.
PRABHJOT SINGH KAINTH 8
RUNNING A PHP PAGE
Before moving on further,we first have to learn how to run php pages.
Since php is a server side scripting language therefore we need a server to run php.
After writing your php script in notepad/any other software you need to save it
with .php extension.For ex: psk.php
But if you will open this directly as you do in case of html pages,nothing will be
processed.
So to process a php page we need servers like apache,IIS etc.
But it’s complicated to configure these servers for an amateur,therefore we will
use a software known as wamp or xampp.
You just need to install any of them.
After installing (I am assuming that you installed xampp),open xampp and you will
see some window like this.
Now click on start corresponding to Apache and MySQL also. That`s it you have
successfully started an Apache server.
PRABHJOT SINGH KAINTH 9
Now go to C:xampphtdocs
Place your php files in htdocs folder.As shown below.
Now go to your web browser let’s say google chrome and then type on address bar
localhost and hit enter.You will see your files listed,click on your file and it will be
processed.
Screenshot will make things more clear for you.
PRABHJOT SINGH KAINTH 10
Now you have learnt how to run php pages,we will now learn how to work with
html pages in php.
Before moving on please install Adobe Dreamviewer(it’s an application to
write html,php,javascripts).
PRABHJOT SINGH KAINTH 11
WORKING WITH HTML FORMS AND PHP
Assuming you have learnt concepts of form in html classes,if not refer to my html
book(Learn Html with PSK).
Let`s suppose you want to create a simple page which gets username and
password from user,if username is Prabhjot and password is 1234 welcome
text is displayed.
Now send.html page:
<html>
<body>
<form action=”receive.php” method=”POST”>
Username:<input type=”text” name=”user”>
<br>
Password:<input type=”password” name=”pass”>
<input type=”submit” value=”login”>
</form>
</body>
</html>
receive.php is the name of the file which contains your php code and
method=”POST” means that username and password will be send to the server via
post method. You can also use GET method instead of POST,but POST is
preferred(you can see the difference between them after this tutorial).
Now receive.php :
<?php
$use=$_POST[‘user’];
$pas=$_POST[‘pass’];
if($use==”Prabhjot” && $pass=1234)
{
echo “welcome user”;
}
else
{
echo “login failed”;
}
?>
PRABHJOT SINGH KAINTH 12
Understanding the php code written above.
$use and $pas are the names of the variables (it could be anything you want).
$_POST: it’s a syntax you have to use this when catching values from different
pages.
$_POST[‘user’]: ‘user’ is the name of the input field in our send.html page.
You can also use $_GET[‘user’] if you have used method=”GET” in send.html page.
Now save both of these files into your c:xampphtdocs folder.
Run send.html page and then see the results.
DIFFERENCE BETWEN POST AND GET METHOD
• The GET method sends the encoded user information appended to the
page request. The page and the encoded information are separated by the
? character as follows:
• http://www.psk.com?user=prabhjot&pass=1234
• The GET method is the defualt method to pass information from browser
to web server and it produces a long string that appears in your browser's
address bare. Never use the GET method if you have password or other
sensitive information to pass to the server. The GET method has size
limtations,only 1024 characters can be in a request string.
• A generally more reliable method of passing information to a backend
program is the POST method.
• This packages the information in exactly the same way as GET methods,
but instead of sending it as a text string after a ? in the URL it sends it as a
separate message.
• This message comes to the backend program in the form of the standard
input which you can parse and use for your processing.
• No characters limitations.
• Provides more security than GET method.
PRABHJOT SINGH KAINTH 13
How to upload a file in html form using PHP
First of all we need two files upload.html and uploaded.php(names can be any)
Upload.html
<html>
<body>
<form action=”uploaded.php” method=”POST” enctype=”multipart/form-data”>
Upload file<input type=”file” name=”psk”>
<input type=”submit” value=”upload”>
</form>
</body>
</html>
What is enctype=”multipart/form-data”?
This attribute ensures that the form data is encoded as mulitpart MIME data, the
same format that is used for encoding file attachments in email messages , which
is required for uploading binary data such as files.
Uploaded.php
<?php
$filename=$_FILES[‘psk’][‘name’];
move_uploaded_file($_FILES['psk']['tmp_name'],”uploads/psk”);
echo “file”.$filename.”uploaded successfully”;
?>
Understanding the code:
$filename is a variable which is used to store the name of the file.
$FILES[‘psk’][‘name’] is used because we have name of the input field as psk in
upload.html page and ‘name’ is used because we have used name attribute(if we
have used id attribute then $FILES[‘psk’][‘id’]).
How to redirect to another page in PHP?
You can use header .For ex:
header(‘location:www.google.com’);
PRABHJOT SINGH KAINTH 14
WORKING WITH QUERY STRINGS IN PHP
Suppose I want to pass an information from one page to another,this is done by
query string as you might be knowing.
send.php:
<?php
$user=”Prabhjot”;
header(‘location:receive.php?username=$user’);
?>
url will be something like this receive.php?username=Prabhjot
receive.php:
<?php
$username=$_GET[‘username’];
?>
$_GET[‘username’] is used because we have used username as the name attribute
in the url(see above).
Query strings are always caught by GET/REQUEST method not POST method.
PRABHJOT SINGH KAINTH 15
WORKING WITH COOKIES IN PHP
How to create a cookie?
By using following:
setcookie(name,value,expires,path,domain,secure,HttpOnly);
name:name of the cookie
value:value of the cookie if any
expires:the time after which the cookie should get expire
path: The path that the browser should send the cookie back to.
domain: By default, a browser only sends a cookie back to the exact computer that
sent it.But if you want any other computer to receive a cookie back.
Secure:This ensures that the cookie will only be sent if there is a secure
connections that is https connection
HttpOnly:Cookies will only be used by browser which makes request via HTTP
For example:
setcookie(“psk”,0,time()+60*60*2,”/data”,”www.psk.com”,false,true);
Please note time is in milliseconds.
How to access cookies?
It`s very simple.
echo $_COOKIE[“psk”];
If you want to display welcome message only if cookie psk is running.
<?php
$cook=$_COOKIE[“psk”];
if($cook)
{
echo “welcome user”.$cook;
}
?>
PRABHJOT SINGH KAINTH 16
WORKING WITH SESSIONS IN PHP
How to create a session?
By using session_start();
How to write and read sessions?
$_SESSION[‘name of the session’]=value of the session; // writing session
echo $_SESSION[‘name of the session’]; // reading session
For example:
<?php
session_start();
$_SESSION[‘psk’]=”Prabhjot”;
echo $_SESSION[‘psk’];
?>
How to destroy a session?
By using session_destroy();
For example:
If session psk is Prabhjot redirect to www.google.com, if it is prakhar redirect to
www.facebook.com.
<?php
session_start();
$sess=$_SESSION[‘psk’];
if(sess==”Prabhjot”)
{
header(‘location:www.google.com’);
}
if(sess==”prakhar”)
{
header(‘location:www.facebook.com’);
}
?>
PRABHJOT SINGH KAINTH 17
WORKING WITH FILES AND DIRECTORIES IN PHP
file_exists(“c:/psk.txt”); // this will return true if the file exists else false.
filesize(“/home/psk.txt”); // will return the size of the file.
How to get the name of the file?
$filename=basename(“/home/psk.txt”);
How to open files in php?
$handle=fopen(“path of the file”,”permission”);
$handle is a resource data type that is associated with file open.
Permission means the rights on the file whether we have open that file for
reading or writing purpose.
For ex:
$handle=fopen(“/home/psk.txt”,”r”); //means psk.txt is opened only for reading
purpose.
$handle=fopen(“/home/psk.txt”,”w”); //means psk.txt is opened only for writing
purpose.
If we use a then it means file is opened only for appending purpose.
How to close files in php?
fclose($handle);
How to read and write from file in php?
By following functions:
fread() — Reads a string of characters from a file
fwrite() — Writes a string of characters to a file
fgetc() — Reads a single character at a time
feof() — Checks to see if the end of the file has been reached
fgets() — Reads a single line at a time
file() — Reads an entire file into an array
Examples on next page.
PRABHJOT SINGH KAINTH 18
$handle=fopen(“psk.txt”,”r”);
$ans=fread($handle,5); // this will read only first 5 characters of the file
$handle=fopen(“psk.txt”,”w”);
fwrite($handle,”Prabhjot”); // this will write Prabhjot at the end of the file.
fwrite($handle,”Prabhjot”,5); // this will write only first 5 characters of Prabhjot at
the end of the file.
How to change permissions of file in php?
By using chmod(path of the file,permission);
For ex: chmod(“/home/psk.txt”,0166);
0166 is basically UNIX based permission granting technique you can learn this
from google.
How to copy,rename or delete files in php?
copy(source,destination);
Ex:copy(“/home/psk.txt”,”/download/ps.txt”);
rename(oldname,newname);
Ex:rename(“/home/psk.txt”,”/home/prab.txt”);
unlink() function is used to delete files in php.
Ex:unlink(“/home/psk.txt”);
WORKING WITH DIRECTORIES
Same as file are opened or close,only difference instead of fopen or fclose use
opendir or closedir.
For ex: $handle=opendir(“/home/download”);
closedir($handle);
$file=readdir($handle); // will read contents of the directory.
How to create or delete directory?
mkdir(“/home/download/psk”); //will create psk folder
rmdir(“/home/download/psk”); //will remove psk folder
PRABHJOT SINGH KAINTH 19
WORKING WITH MYSQL IN PHP
This is the most important topic of this book.
Before starting we must first set up a MYSQL server to handle sql queries.
Remember when we were setting up Apache server,we clicked on MYSQL start if
not then go back to xampp control panel and click on start corresponding to
MySQL.
After doing this step go to your browser and type localhost/phpmyadmin and a
window something like this will open.
Now from left hand side click on new to create a new database(Assuming the
name of the database is psk).
Then click on psk database from the list and then create a table named as
details.
Then create two columns one username and another password with varchar
datatype.( I am assuming that you know some basic concepts of sql if not
then refer to my book Learn simple MySQL with psk)
Screenshots will help you don`t worry.
PRABHJOT SINGH KAINTH 20
TABLE CREATION
COLUMN CREATION
PRABHJOT SINGH KAINTH 21
After setting up the server our next task is to link php with Mysql.
For this in our php code we need to include following things.
<?php
$con=mysql_connect('servername','username','password');
mysql_select_db('databasename',$con);
?>
$con is the name of the variable (you can use any of your choice).
mysql_connect is a syntax use to connect to Mysql.
servername is the name of the server,in our case localhost.
Username is the username for accessing the server by default it is root
Password: by default empty.
Mysql_select_db is use to select database.
So this is how our connection will look like:
$con=mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘psk’,$con);
WORKING WITH QUERIES(Please note name of our table is details)
SELECT QUERY:
mysql_query(“select * from details”,$con);
It`s better to store this in a variable(usually $data is used but you can use any) as
data which is returned by select query come in form of an array.
$data= mysql_query(“select * from details”,$con);
Take another variable to fetch data in array form usually $row is used.
$row=mysql_fetch_array($data);
Now to print data:
echo $row[‘name of the column’];
for ex:we have 2 columns in our details table,namely username and password
echo $row[‘username’]; //will only print first entry in the table not all values.
PRABHJOT SINGH KAINTH 22
So how to print all data returned by select query?
Simply use a loop as we do in c/c++.
For example:
while($row=mysql_fetch_array($data)
{
echo $row[‘username’];
}
INSERT QUERY:
mysql_query(“insert into `details` (`username`,`password`)
values(‘prab40’,’1234’)”,$con);
UPDATE QUERY:
mysql_query(“update `details` set `username`=‘prab40’ `password`=’1234’
”,$con);
Please note: ` ` is different from ‘ ‘
DELETE QUERY:
mysql_query(“delete from `details` where `username`=’prab40’ “,$con);
Next page will show you how to create a login page and check if username exists
in the database or not,if username and password are correct then create a
session named id of username and then redirect to home.html page else return
login details wrong.
PRABHJOT SINGH KAINTH 23
Login.html
<html>
<body>
<form action=log.php method=”POST” >
Enter username:<input type=”text” name=”user”><br>
Enter password:<input type=”password” name=”pass”><br>
<input type=”submit” value=”login”>
</form>
</body>
</html>
log.php
<?php
session_start();
$con=mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘psk’,$con);
$user=$_POST[‘user’];
$pass=$_POST[‘pass’];
$data=mysql_query(“select * from details where `username`=’$user’ “,$con);
$row=mysql_fetch_array($data);
if($pass==$row[‘password’])
{
$_SESSION['id']=$user;
header(‘location:home.html’);
}
else
{
echo “wrong login details”;
}
?>
PRABHJOT SINGH KAINTH 24
Now if suppose you have 50 pages in your website which uses sql
connection,every time you have to write connection code but we can reduce
our job by creating a separate file which only have connection code and then
include that in every page.
For example:
lib.php
<?php
$con=mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘psk’,$con);
?>
Now to use this page in another page,we have to use include function as we
have in c/c++ but with some changes.
For example in login.php I have to use lib.php
Login.php
<?php
include(‘lib.php’);
?>
PRABHJOT SINGH KAINTH 25
SOME MORE FUNCTIONS, ATTRIBUTES AND THINGS
RELATED TO PHP
How to print current date and time?
$dat=getdate();
echo $dat[“mday”].$dat[“month”].$dat[“year”];
echo $dat[“hours”].$dat[“minutes”];
How to get IP address of your website visitor?
echo “Your IP address is: “ . $_SERVER[“REMOTE_ADDR”];
How to create a random number/text?
$psk=rand(1,10);
echo $psk.$psk.$psk; //will generate a 3 digit number(concatenate more if you
want more digits)
$psk='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$text= $psk[rand(0,25)].$psk[rand(0,25)]; //will generate text of 2 characters.
How to mail in php?
mail(“destination address”,”subject”,”message”);
example:mail(“prabhjot409069@gmail.com”,”application”,”hi”);
PRABHJOT SINGH KAINTH 26
WORKING ON SECURITY IN PHP
First of all we will learn how to protect our website from vulnerability and then
encryption and decryption also.Since our password,username,session id or any
other sensitive data must be protected from unauthorized access therefore we
will implementing some methods to protect our website from getting hacked.
When we were creating session in above lessons,we were giving session value as
username.If someone somehow knows your username he can easily get access to
your website.
So to remove such vulnerabilities we should use some random session id
using random function.
For example:
$sess=rand(10,10000);
$_SESSION[‘login’]=$sess;
Always have validations on input fields,never allow any script to be as input.
For example: In an input field someone input something as:
<script>alert(“Website Hacked by Me”);</script>
You can make use of regular expression in javascript to remove such inputs from
being getting processed.This attack is well known as XSS attacks.
Some ways to remove XSS attacks:
Data Validation:To validate data
For example:to validate a phone number in php
if(preg_match(‘/^((1-)?d{3}-)d{3}-d{4}$/’,$phone))
{
echo $phone.”is correct”;
}
PRABHJOT SINGH KAINTH 27
Data Sanitization:To remove unwanted data
For example:If your input field should have only text nothing else then:
$ans=strip_tags($_POST[‘name’]);
Output escaping:To prevent browser from applying any unintended meaning to
any special sequence of characters that may be found.
For example:
echo “You queried for”. Htmlspecialchars($_GET[‘nm’]);
Now to prevent SQL injection attacks:
SQL injection attacks can be prevented by using prepared statements.
What are prepared statements?
Prepared Statements do not combine variables with SQL strings,so it is not
possible for an attacker to modify the SQL query.
They combine the variables with compiled statement which means that SQL
query and variables are sent separately.
For example:
$user=$_GET[‘username’];
if($stmt=$mysqli->prepare(“select password from user where username=?”))
{
$stmt->bind_param(“s”,$user);
$stmt->execute();
$stmt->bind_result($password);
$stmt->fetch();
echo $password;
}
PRABHJOT SINGH KAINTH 28
SOME ENCRYTION AND DECRYPTION TECHNIQUES
MD5 hash:Message Digest Hash
md5() function is used to calculate md5 hash of string.
Syntax:md5(string,raw);
String:your text.
Raw:specifies hex or binary output form(true for binary and false for hex)
For example:
$psk=”Prabhjot”;
echo md5($psk);
SHA1:Secured Hash Algorithm
sha1() function is used to calculate sha hash of string.
Syntax:sha1(string,raw);
String:your text.
Raw:specifies hex or binary output form(true for binary and false for hex)
For example:
$psk=”Prabhjot”;
echo sha1($psk);
PRABHJOT SINGH KAINTH 29
EXAMPLE TO ADD ENCRYPTION AND DECRYPTION(source php website)
<?php
# --- ENCRYPTION ---
# the key should be random binary, use scrypt, bcrypt or PBKDF2 to
# convert a string into a key
# key is specified using hexadecimal
$key = pack('H*',
"bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3")
;
# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size = strlen($key);
echo "Key size: " . $key_size . "n";
$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";
# create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,
MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);
# prepend the IV for it to be available for decryption
$ciphertext = $iv . $ciphertext;
# encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);
echo $ciphertext_base64 . "n";
# Resulting cipher text has no integrity or authenticity added
# and is not protected against padding oracle attacks.
PRABHJOT SINGH KAINTH 30
# --- DECRYPTION ---
$ciphertext_dec = base64_decode($ciphertext_base64);
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
echo $plaintext_dec . "n";
?>
PRABHJOT SINGH KAINTH 31
CREATING PAGE WHICH LISTS 100 CHECKBOXES WITH RANDOM VALUES
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<?php
$word=array();
$psk='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for($i=1;$i<=100;$i++)
{
$text= $psk[rand(0,25)].$psk[rand(0,25)].$psk[rand(0,25)].$psk[rand(0,25)];
$word[$i]=$text;
}
?>
</head>
<body>
<ul>
<?php
for($i=1;$i<=100;$i++)
{?>
<li style="display:inline">
<input type="checkbox" name="check_list[]" value="<?php echo $word[$i];?>"
/><?php echo $word[$i];?></li>&nbsp;&nbsp;&nbsp;
<?php
if($i%8==0)
{?> </br></BR>
<?php }
?>
<?php }?>
</ul>
</body>
</html>
PRABHJOT SINGH KAINTH 32
TEXT TO SPEECH CONVERSION USING GOOGLE TRANSLATE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Text to speech APi</title>
<?php
if($_POST){
$text=substr($_POST['ps'],0,100);
$text=urlencode($text);
$file='psk';
$file=$file.".mp3";
$mp3=file_get_contents("http://translate.google.com/translate_tts?tl=en&q=$te
xt");
file_put_contents($file,$mp3);
}
?>
</head>
<body>
<form action="" method="post">
Enter your text here
<input type="text" name="ps" /><br />
<input type="submit" name="submit" />
<br />
</form>
<br />
<?php if($_POST)
{?>
<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $file;?>" type="audio/mp3" />
</audio>
<?php } ?>
</body>
</html>
PRABHJOT SINGH KAINTH 33
ATTACHED ZIP INCLUDES FOLLOWING THINGS
• Webkiosk(Student Information Management website of Thapar
university created by Prabhjot Singh Kainth)
• FaceMash(FaceMash website which was originally created by
Mark Zuckerberg to rate people)
• CAPTCHA implementation in php by Prabhjot Singh Kainth
• Online T-shirt ordering system
• A love calculator website(please note it may be funny but do have
a look on the algorithm used)
• Text to Speech Conversion using google translation by Prabhjot
Singh Kainth
• A facebook home page look like which changes according to your
device size by Prabhjot Singh Kainth
• Music website which plays songs according to the selected mood
by Prabhjot Singh Kainth
*by Prabhjot Singh Kainth means this is original work by him rest
means he has edited the code of some other person.
Ad

More Related Content

What's hot (18)

PHP Basic
PHP BasicPHP Basic
PHP Basic
Yoeung Vibol
 
Web development
Web developmentWeb development
Web development
Seerat Bakhtawar
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
Gnugroup India
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
Nisa Soomro
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
Santhiya Grace
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
Dhani Ahmad
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
S Bharadwaj
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Phpwebdevelping
PhpwebdevelpingPhpwebdevelping
Phpwebdevelping
mohamed ashraf
 
PHP MySQL
PHP MySQLPHP MySQL
PHP MySQL
Md. Sirajus Salayhin
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
Todd Barber
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
Dr. Ramkumar Lakshminarayanan
 
Php
PhpPhp
Php
WAHEEDA ROOHILLAH
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
Php(report)
Php(report)Php(report)
Php(report)
Yhannah
 

Similar to Learn php with PSK (20)

Lecture14-Introduction to PHP-coding.pdf
Lecture14-Introduction to PHP-coding.pdfLecture14-Introduction to PHP-coding.pdf
Lecture14-Introduction to PHP-coding.pdf
IotenergyWater
 
Php, mysq lpart1
Php, mysq lpart1Php, mysq lpart1
Php, mysq lpart1
Subhasis Nayak
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
Shivi Tomer
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
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 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
 
Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
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
Arti Parab Academics
 
Php
PhpPhp
Php
TSUBHASHRI
 
Php
PhpPhp
Php
TSUBHASHRI
 
Php
PhpPhp
Php
TSUBHASHRI
 
Php
PhpPhp
Php
Ajaigururaj R
 
Php essentials
Php essentialsPhp essentials
Php essentials
sagaroceanic11
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
Lecture14-Introduction to PHP-coding.pdf
Lecture14-Introduction to PHP-coding.pdfLecture14-Introduction to PHP-coding.pdf
Lecture14-Introduction to PHP-coding.pdf
IotenergyWater
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
Shivi Tomer
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
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 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
 
Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
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
Arti Parab Academics
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
Ad

Recently uploaded (20)

Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Ad

Learn php with PSK

  • 1. Learn PHP with PSK Learn PHP with Prabhjot Singh Kainth. Prabhjot Singh Kainth is currently pursuing B.E in CSE from Thapar University Patiala. H Hostel Thapar University Patiala.
  • 2. PRABHJOT SINGH KAINTH 2 ABOUT THE BOOK This book is being written by Prabhjot Singh Kainth, currently pursuing B.E in Computer Science from Thapar University Patiala. He has written many other books on various languages. This book is purely his own work, no code have been copied from any other book/source. This books doesn`t go in much details of PHP.It will only provide you information necessary to start developing web pages. This books comes with a zip file attached which contains some examples. Hope you will enjoy his small effort. You can contact him through following ways: Email:[email protected] Facebook:www.facebook.com/prab409069 Mobile: +919814181928
  • 3. PRABHJOT SINGH KAINTH 3 Php stands for Hypertext preprocessor. It is a server side scripting language (which means all the actions performed by the script will be processed by server not the client). Php is basically used to create dynamic websites (websites which return dynamic data for example: facebook, google, youtube etc.). You can find various definition and advantages of PHP in lots of books. What are the data types involved in php? There are integer, character, string, Boolean and float data type. There is no such reserved keyword for data type (for ex: we have int for integer, float for float data type in c/c++). So how do we differentiate data types? All data types are stored as variable in php with a $ sign. Example will make things clear for you ($prab is the name of the variable you can use anything instead of prab) $prab=10; //makes it integer type $prab=”Prabhjot”; //makes it string type $prab=10.0; //makes it float type $prab=true; //makes it Boolean type // is used for comments. How to print data in php? You can use print but echo is more often used. For example: echo “Prabhjot”;
  • 4. PRABHJOT SINGH KAINTH 4 How to write php scripts? All php script starts with <?php and ends with ?> as show below. <?php //your code ?> Writing your first php script? <?php echo “My name is Prabhjot singh”; ?> Result: My name is Prabhjot singh Now working more with variables: $a=10; $b=20; echo “a”; //will print a not the value of a which is 10. echo “$a”; // this will print 10 not a. or simply type echo $a; “ ” is used to print strings but php takes anything as variable if it starts with $ sign. A simple program to add 2 numbers: <?php $a=10; $b=20; $c=$a+$b; //note if you simply use a+b it will return an error (discussed later why) echo “$c”; or echo $c; ?> How to concatenate strings with variables (suppose you want to print: Addition of a and b is 30.how to do this) For this we have a concatenation operator “.”, dot operator is used to concatenate strings.
  • 5. PRABHJOT SINGH KAINTH 5 In above example: echo “Addition of a and b is”. $c ; // will print: Addition of a and b is 30 You can even concatenate two strings using this operator. Moving onto loops and decisions: The syntax remains the same as we have in c/c++ only difference comes is $ sign for variables. For example: For loop: for($i=0;$i<=10;$i++) { echo $i; } Switch statements: switch($i) { case 1: echo “one”; break; default: echo “wrong choice”; break; }
  • 6. PRABHJOT SINGH KAINTH 6 Moving onto Arrays There are two types of array in php: 1. Indexed: Simple arrays as we have in c/c++. 2. Associative: This type of array is also referred to as a hash or map. With associative arrays, each element is referenced by a string index. You will get to know the difference between them later. Arrays can be declared in following ways in php: $arr=array(“apple”,”orange”,”mango”); //indexed array $arr=array(“name”=>”Prabhjot”,”rollno”=>101203073,”branch”=>”Computer”); //associative array How to access elements of array? echo $arr[0]; // will print apple in case of indexed array echo $arr[“name”]; // will print Prabhjot . You can also add items to an array: $arr[3]=”grapes”; $arr[0]=”banana”; // note it will replace apple If you want to print an array whole in once (all the elements without loop),you can use print_r() function: For example: print_r($arr); // it will print apple orange mango. You can use html tags within Php also,this process is known as fusion. For example: echo “Prabhjot”.’<br>’.”singh”; This will print Prabhjot and singh in next line as breakline tag is being used. echo "prabhjot".'<b>'."singh".'</b>'; This will print Prabhjot and singh in bold letters. Please note html tags are used with single quote.
  • 7. PRABHJOT SINGH KAINTH 7 Some more functions related to Strings and Arrays printf() and sprintf() functions: As we use in c,we can use printf in the same way. For ex: printf(“Answer is %d”,$i); //where i is an integer type. You can also specify the precision of a floating point number as we do in c. For ex: printf(“%0.4f”,123.45678) will result in 123.4567 Now if we want to store result and not to print it,sprint() is used. $psk=sprintf(file_get_contents(“psk.txt”)); How to count elements of an Array? Using count function.Suppose name of our array is arr. $ctr=count($arr); echo $ctr; For each loop in array: $arr= array( “cricket”, “football”, “Tennis”, “Hockey” ); foreach ( $arr as $val ) { echo $val . “ < br/ > ”; } Where $val can be name of any variable.This will print all the elements of array. Multi dimension array are also there but it is not necessary for web development right now. You can sort,merge and push-pop an array by following functions: sort($arr); //sorting in ascending order for indexed array. rsort($arr); //sorting in descending order for indexed array. asort($arr); //sorting in ascending order for associative array. arsort($arr); //sorting in descending order for associative array. array_push($arr,”badminton”); // to insert an element at the end of the array. array_pop($arr); // will pop an item from the end of the array. array_merge($arr1,$arr2); // will merge two arrays named arr1 and arr2.
  • 8. PRABHJOT SINGH KAINTH 8 RUNNING A PHP PAGE Before moving on further,we first have to learn how to run php pages. Since php is a server side scripting language therefore we need a server to run php. After writing your php script in notepad/any other software you need to save it with .php extension.For ex: psk.php But if you will open this directly as you do in case of html pages,nothing will be processed. So to process a php page we need servers like apache,IIS etc. But it’s complicated to configure these servers for an amateur,therefore we will use a software known as wamp or xampp. You just need to install any of them. After installing (I am assuming that you installed xampp),open xampp and you will see some window like this. Now click on start corresponding to Apache and MySQL also. That`s it you have successfully started an Apache server.
  • 9. PRABHJOT SINGH KAINTH 9 Now go to C:xampphtdocs Place your php files in htdocs folder.As shown below. Now go to your web browser let’s say google chrome and then type on address bar localhost and hit enter.You will see your files listed,click on your file and it will be processed. Screenshot will make things more clear for you.
  • 10. PRABHJOT SINGH KAINTH 10 Now you have learnt how to run php pages,we will now learn how to work with html pages in php. Before moving on please install Adobe Dreamviewer(it’s an application to write html,php,javascripts).
  • 11. PRABHJOT SINGH KAINTH 11 WORKING WITH HTML FORMS AND PHP Assuming you have learnt concepts of form in html classes,if not refer to my html book(Learn Html with PSK). Let`s suppose you want to create a simple page which gets username and password from user,if username is Prabhjot and password is 1234 welcome text is displayed. Now send.html page: <html> <body> <form action=”receive.php” method=”POST”> Username:<input type=”text” name=”user”> <br> Password:<input type=”password” name=”pass”> <input type=”submit” value=”login”> </form> </body> </html> receive.php is the name of the file which contains your php code and method=”POST” means that username and password will be send to the server via post method. You can also use GET method instead of POST,but POST is preferred(you can see the difference between them after this tutorial). Now receive.php : <?php $use=$_POST[‘user’]; $pas=$_POST[‘pass’]; if($use==”Prabhjot” && $pass=1234) { echo “welcome user”; } else { echo “login failed”; } ?>
  • 12. PRABHJOT SINGH KAINTH 12 Understanding the php code written above. $use and $pas are the names of the variables (it could be anything you want). $_POST: it’s a syntax you have to use this when catching values from different pages. $_POST[‘user’]: ‘user’ is the name of the input field in our send.html page. You can also use $_GET[‘user’] if you have used method=”GET” in send.html page. Now save both of these files into your c:xampphtdocs folder. Run send.html page and then see the results. DIFFERENCE BETWEN POST AND GET METHOD • The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows: • http://www.psk.com?user=prabhjot&pass=1234 • The GET method is the defualt method to pass information from browser to web server and it produces a long string that appears in your browser's address bare. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limtations,only 1024 characters can be in a request string. • A generally more reliable method of passing information to a backend program is the POST method. • This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. • This message comes to the backend program in the form of the standard input which you can parse and use for your processing. • No characters limitations. • Provides more security than GET method.
  • 13. PRABHJOT SINGH KAINTH 13 How to upload a file in html form using PHP First of all we need two files upload.html and uploaded.php(names can be any) Upload.html <html> <body> <form action=”uploaded.php” method=”POST” enctype=”multipart/form-data”> Upload file<input type=”file” name=”psk”> <input type=”submit” value=”upload”> </form> </body> </html> What is enctype=”multipart/form-data”? This attribute ensures that the form data is encoded as mulitpart MIME data, the same format that is used for encoding file attachments in email messages , which is required for uploading binary data such as files. Uploaded.php <?php $filename=$_FILES[‘psk’][‘name’]; move_uploaded_file($_FILES['psk']['tmp_name'],”uploads/psk”); echo “file”.$filename.”uploaded successfully”; ?> Understanding the code: $filename is a variable which is used to store the name of the file. $FILES[‘psk’][‘name’] is used because we have name of the input field as psk in upload.html page and ‘name’ is used because we have used name attribute(if we have used id attribute then $FILES[‘psk’][‘id’]). How to redirect to another page in PHP? You can use header .For ex: header(‘location:www.google.com’);
  • 14. PRABHJOT SINGH KAINTH 14 WORKING WITH QUERY STRINGS IN PHP Suppose I want to pass an information from one page to another,this is done by query string as you might be knowing. send.php: <?php $user=”Prabhjot”; header(‘location:receive.php?username=$user’); ?> url will be something like this receive.php?username=Prabhjot receive.php: <?php $username=$_GET[‘username’]; ?> $_GET[‘username’] is used because we have used username as the name attribute in the url(see above). Query strings are always caught by GET/REQUEST method not POST method.
  • 15. PRABHJOT SINGH KAINTH 15 WORKING WITH COOKIES IN PHP How to create a cookie? By using following: setcookie(name,value,expires,path,domain,secure,HttpOnly); name:name of the cookie value:value of the cookie if any expires:the time after which the cookie should get expire path: The path that the browser should send the cookie back to. domain: By default, a browser only sends a cookie back to the exact computer that sent it.But if you want any other computer to receive a cookie back. Secure:This ensures that the cookie will only be sent if there is a secure connections that is https connection HttpOnly:Cookies will only be used by browser which makes request via HTTP For example: setcookie(“psk”,0,time()+60*60*2,”/data”,”www.psk.com”,false,true); Please note time is in milliseconds. How to access cookies? It`s very simple. echo $_COOKIE[“psk”]; If you want to display welcome message only if cookie psk is running. <?php $cook=$_COOKIE[“psk”]; if($cook) { echo “welcome user”.$cook; } ?>
  • 16. PRABHJOT SINGH KAINTH 16 WORKING WITH SESSIONS IN PHP How to create a session? By using session_start(); How to write and read sessions? $_SESSION[‘name of the session’]=value of the session; // writing session echo $_SESSION[‘name of the session’]; // reading session For example: <?php session_start(); $_SESSION[‘psk’]=”Prabhjot”; echo $_SESSION[‘psk’]; ?> How to destroy a session? By using session_destroy(); For example: If session psk is Prabhjot redirect to www.google.com, if it is prakhar redirect to www.facebook.com. <?php session_start(); $sess=$_SESSION[‘psk’]; if(sess==”Prabhjot”) { header(‘location:www.google.com’); } if(sess==”prakhar”) { header(‘location:www.facebook.com’); } ?>
  • 17. PRABHJOT SINGH KAINTH 17 WORKING WITH FILES AND DIRECTORIES IN PHP file_exists(“c:/psk.txt”); // this will return true if the file exists else false. filesize(“/home/psk.txt”); // will return the size of the file. How to get the name of the file? $filename=basename(“/home/psk.txt”); How to open files in php? $handle=fopen(“path of the file”,”permission”); $handle is a resource data type that is associated with file open. Permission means the rights on the file whether we have open that file for reading or writing purpose. For ex: $handle=fopen(“/home/psk.txt”,”r”); //means psk.txt is opened only for reading purpose. $handle=fopen(“/home/psk.txt”,”w”); //means psk.txt is opened only for writing purpose. If we use a then it means file is opened only for appending purpose. How to close files in php? fclose($handle); How to read and write from file in php? By following functions: fread() — Reads a string of characters from a file fwrite() — Writes a string of characters to a file fgetc() — Reads a single character at a time feof() — Checks to see if the end of the file has been reached fgets() — Reads a single line at a time file() — Reads an entire file into an array Examples on next page.
  • 18. PRABHJOT SINGH KAINTH 18 $handle=fopen(“psk.txt”,”r”); $ans=fread($handle,5); // this will read only first 5 characters of the file $handle=fopen(“psk.txt”,”w”); fwrite($handle,”Prabhjot”); // this will write Prabhjot at the end of the file. fwrite($handle,”Prabhjot”,5); // this will write only first 5 characters of Prabhjot at the end of the file. How to change permissions of file in php? By using chmod(path of the file,permission); For ex: chmod(“/home/psk.txt”,0166); 0166 is basically UNIX based permission granting technique you can learn this from google. How to copy,rename or delete files in php? copy(source,destination); Ex:copy(“/home/psk.txt”,”/download/ps.txt”); rename(oldname,newname); Ex:rename(“/home/psk.txt”,”/home/prab.txt”); unlink() function is used to delete files in php. Ex:unlink(“/home/psk.txt”); WORKING WITH DIRECTORIES Same as file are opened or close,only difference instead of fopen or fclose use opendir or closedir. For ex: $handle=opendir(“/home/download”); closedir($handle); $file=readdir($handle); // will read contents of the directory. How to create or delete directory? mkdir(“/home/download/psk”); //will create psk folder rmdir(“/home/download/psk”); //will remove psk folder
  • 19. PRABHJOT SINGH KAINTH 19 WORKING WITH MYSQL IN PHP This is the most important topic of this book. Before starting we must first set up a MYSQL server to handle sql queries. Remember when we were setting up Apache server,we clicked on MYSQL start if not then go back to xampp control panel and click on start corresponding to MySQL. After doing this step go to your browser and type localhost/phpmyadmin and a window something like this will open. Now from left hand side click on new to create a new database(Assuming the name of the database is psk). Then click on psk database from the list and then create a table named as details. Then create two columns one username and another password with varchar datatype.( I am assuming that you know some basic concepts of sql if not then refer to my book Learn simple MySQL with psk) Screenshots will help you don`t worry.
  • 20. PRABHJOT SINGH KAINTH 20 TABLE CREATION COLUMN CREATION
  • 21. PRABHJOT SINGH KAINTH 21 After setting up the server our next task is to link php with Mysql. For this in our php code we need to include following things. <?php $con=mysql_connect('servername','username','password'); mysql_select_db('databasename',$con); ?> $con is the name of the variable (you can use any of your choice). mysql_connect is a syntax use to connect to Mysql. servername is the name of the server,in our case localhost. Username is the username for accessing the server by default it is root Password: by default empty. Mysql_select_db is use to select database. So this is how our connection will look like: $con=mysql_connect(‘localhost’,’root’,’’); mysql_select_db(‘psk’,$con); WORKING WITH QUERIES(Please note name of our table is details) SELECT QUERY: mysql_query(“select * from details”,$con); It`s better to store this in a variable(usually $data is used but you can use any) as data which is returned by select query come in form of an array. $data= mysql_query(“select * from details”,$con); Take another variable to fetch data in array form usually $row is used. $row=mysql_fetch_array($data); Now to print data: echo $row[‘name of the column’]; for ex:we have 2 columns in our details table,namely username and password echo $row[‘username’]; //will only print first entry in the table not all values.
  • 22. PRABHJOT SINGH KAINTH 22 So how to print all data returned by select query? Simply use a loop as we do in c/c++. For example: while($row=mysql_fetch_array($data) { echo $row[‘username’]; } INSERT QUERY: mysql_query(“insert into `details` (`username`,`password`) values(‘prab40’,’1234’)”,$con); UPDATE QUERY: mysql_query(“update `details` set `username`=‘prab40’ `password`=’1234’ ”,$con); Please note: ` ` is different from ‘ ‘ DELETE QUERY: mysql_query(“delete from `details` where `username`=’prab40’ “,$con); Next page will show you how to create a login page and check if username exists in the database or not,if username and password are correct then create a session named id of username and then redirect to home.html page else return login details wrong.
  • 23. PRABHJOT SINGH KAINTH 23 Login.html <html> <body> <form action=log.php method=”POST” > Enter username:<input type=”text” name=”user”><br> Enter password:<input type=”password” name=”pass”><br> <input type=”submit” value=”login”> </form> </body> </html> log.php <?php session_start(); $con=mysql_connect(‘localhost’,’root’,’’); mysql_select_db(‘psk’,$con); $user=$_POST[‘user’]; $pass=$_POST[‘pass’]; $data=mysql_query(“select * from details where `username`=’$user’ “,$con); $row=mysql_fetch_array($data); if($pass==$row[‘password’]) { $_SESSION['id']=$user; header(‘location:home.html’); } else { echo “wrong login details”; } ?>
  • 24. PRABHJOT SINGH KAINTH 24 Now if suppose you have 50 pages in your website which uses sql connection,every time you have to write connection code but we can reduce our job by creating a separate file which only have connection code and then include that in every page. For example: lib.php <?php $con=mysql_connect(‘localhost’,’root’,’’); mysql_select_db(‘psk’,$con); ?> Now to use this page in another page,we have to use include function as we have in c/c++ but with some changes. For example in login.php I have to use lib.php Login.php <?php include(‘lib.php’); ?>
  • 25. PRABHJOT SINGH KAINTH 25 SOME MORE FUNCTIONS, ATTRIBUTES AND THINGS RELATED TO PHP How to print current date and time? $dat=getdate(); echo $dat[“mday”].$dat[“month”].$dat[“year”]; echo $dat[“hours”].$dat[“minutes”]; How to get IP address of your website visitor? echo “Your IP address is: “ . $_SERVER[“REMOTE_ADDR”]; How to create a random number/text? $psk=rand(1,10); echo $psk.$psk.$psk; //will generate a 3 digit number(concatenate more if you want more digits) $psk='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $text= $psk[rand(0,25)].$psk[rand(0,25)]; //will generate text of 2 characters. How to mail in php? mail(“destination address”,”subject”,”message”); example:mail(“[email protected]”,”application”,”hi”);
  • 26. PRABHJOT SINGH KAINTH 26 WORKING ON SECURITY IN PHP First of all we will learn how to protect our website from vulnerability and then encryption and decryption also.Since our password,username,session id or any other sensitive data must be protected from unauthorized access therefore we will implementing some methods to protect our website from getting hacked. When we were creating session in above lessons,we were giving session value as username.If someone somehow knows your username he can easily get access to your website. So to remove such vulnerabilities we should use some random session id using random function. For example: $sess=rand(10,10000); $_SESSION[‘login’]=$sess; Always have validations on input fields,never allow any script to be as input. For example: In an input field someone input something as: <script>alert(“Website Hacked by Me”);</script> You can make use of regular expression in javascript to remove such inputs from being getting processed.This attack is well known as XSS attacks. Some ways to remove XSS attacks: Data Validation:To validate data For example:to validate a phone number in php if(preg_match(‘/^((1-)?d{3}-)d{3}-d{4}$/’,$phone)) { echo $phone.”is correct”; }
  • 27. PRABHJOT SINGH KAINTH 27 Data Sanitization:To remove unwanted data For example:If your input field should have only text nothing else then: $ans=strip_tags($_POST[‘name’]); Output escaping:To prevent browser from applying any unintended meaning to any special sequence of characters that may be found. For example: echo “You queried for”. Htmlspecialchars($_GET[‘nm’]); Now to prevent SQL injection attacks: SQL injection attacks can be prevented by using prepared statements. What are prepared statements? Prepared Statements do not combine variables with SQL strings,so it is not possible for an attacker to modify the SQL query. They combine the variables with compiled statement which means that SQL query and variables are sent separately. For example: $user=$_GET[‘username’]; if($stmt=$mysqli->prepare(“select password from user where username=?”)) { $stmt->bind_param(“s”,$user); $stmt->execute(); $stmt->bind_result($password); $stmt->fetch(); echo $password; }
  • 28. PRABHJOT SINGH KAINTH 28 SOME ENCRYTION AND DECRYPTION TECHNIQUES MD5 hash:Message Digest Hash md5() function is used to calculate md5 hash of string. Syntax:md5(string,raw); String:your text. Raw:specifies hex or binary output form(true for binary and false for hex) For example: $psk=”Prabhjot”; echo md5($psk); SHA1:Secured Hash Algorithm sha1() function is used to calculate sha hash of string. Syntax:sha1(string,raw); String:your text. Raw:specifies hex or binary output form(true for binary and false for hex) For example: $psk=”Prabhjot”; echo sha1($psk);
  • 29. PRABHJOT SINGH KAINTH 29 EXAMPLE TO ADD ENCRYPTION AND DECRYPTION(source php website) <?php # --- ENCRYPTION --- # the key should be random binary, use scrypt, bcrypt or PBKDF2 to # convert a string into a key # key is specified using hexadecimal $key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3") ; # show key size use either 16, 24 or 32 byte keys for AES-128, 192 # and 256 respectively $key_size = strlen($key); echo "Key size: " . $key_size . "n"; $plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted."; # create a random IV to use with CBC encoding $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); # creates a cipher text compatible with AES (Rijndael block size = 128) # to keep the text confidential # only suitable for encoded input that never ends with value 00h # (because of default zero padding) $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv); # prepend the IV for it to be available for decryption $ciphertext = $iv . $ciphertext; # encode the resulting cipher text so it can be represented by a string $ciphertext_base64 = base64_encode($ciphertext); echo $ciphertext_base64 . "n"; # Resulting cipher text has no integrity or authenticity added # and is not protected against padding oracle attacks.
  • 30. PRABHJOT SINGH KAINTH 30 # --- DECRYPTION --- $ciphertext_dec = base64_decode($ciphertext_base64); # retrieves the IV, iv_size should be created using mcrypt_get_iv_size() $iv_dec = substr($ciphertext_dec, 0, $iv_size); # retrieves the cipher text (everything except the $iv_size in the front) $ciphertext_dec = substr($ciphertext_dec, $iv_size); # may remove 00h valued characters from end of plain text $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec); echo $plaintext_dec . "n"; ?>
  • 31. PRABHJOT SINGH KAINTH 31 CREATING PAGE WHICH LISTS 100 CHECKBOXES WITH RANDOM VALUES <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <?php $word=array(); $psk='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; for($i=1;$i<=100;$i++) { $text= $psk[rand(0,25)].$psk[rand(0,25)].$psk[rand(0,25)].$psk[rand(0,25)]; $word[$i]=$text; } ?> </head> <body> <ul> <?php for($i=1;$i<=100;$i++) {?> <li style="display:inline"> <input type="checkbox" name="check_list[]" value="<?php echo $word[$i];?>" /><?php echo $word[$i];?></li>&nbsp;&nbsp;&nbsp; <?php if($i%8==0) {?> </br></BR> <?php } ?> <?php }?> </ul> </body> </html>
  • 32. PRABHJOT SINGH KAINTH 32 TEXT TO SPEECH CONVERSION USING GOOGLE TRANSLATE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Text to speech APi</title> <?php if($_POST){ $text=substr($_POST['ps'],0,100); $text=urlencode($text); $file='psk'; $file=$file.".mp3"; $mp3=file_get_contents("http://translate.google.com/translate_tts?tl=en&q=$te xt"); file_put_contents($file,$mp3); } ?> </head> <body> <form action="" method="post"> Enter your text here <input type="text" name="ps" /><br /> <input type="submit" name="submit" /> <br /> </form> <br /> <?php if($_POST) {?> <audio controls="controls" autoplay="autoplay"> <source src="<?php echo $file;?>" type="audio/mp3" /> </audio> <?php } ?> </body> </html>
  • 33. PRABHJOT SINGH KAINTH 33 ATTACHED ZIP INCLUDES FOLLOWING THINGS • Webkiosk(Student Information Management website of Thapar university created by Prabhjot Singh Kainth) • FaceMash(FaceMash website which was originally created by Mark Zuckerberg to rate people) • CAPTCHA implementation in php by Prabhjot Singh Kainth • Online T-shirt ordering system • A love calculator website(please note it may be funny but do have a look on the algorithm used) • Text to Speech Conversion using google translation by Prabhjot Singh Kainth • A facebook home page look like which changes according to your device size by Prabhjot Singh Kainth • Music website which plays songs according to the selected mood by Prabhjot Singh Kainth *by Prabhjot Singh Kainth means this is original work by him rest means he has edited the code of some other person.