c2 Language
c2 Language
c2 Language
Claudine Narciso
PHP
In 1994, an incredibly forward-thinking man named Rasmus Lerdorf developed a set of tools that used a parsing
engine to interpret a few macros here and there. He eventually combined these tools with form interpretation (FI)
package he had written, added some database support and release what has known as PHP/FI.
Its official name is PHP (Hypertext Preprocessor), and it is server side scripting language. A server-side
language is similar to Javascript in that it allows to embed little programs (scripts) into the HTML code of a web
page. When executed, these programs give greater control over what appears on the browser window than
HTML alone can provide. The key difference between Javascript and PHP is the stage of loading the web page
at which these embedded programs are executed. Server-side languages like PHP are run by the web server,
before ending the web page of a browser.
WAMP, Notepad++
Note: All created php files should be saved inside www folder
Basic Rules:
1. Use any text editor like notepad
2. Use html pattern then integrate the program
3. Store file in the same directory as html pages
4. Save program with file extension .php
COMMENTING
• //simple php comment
• /* c-style multi line comment */
• # used to shells? then use this kind of comment
CODE COHABILITATION
<html>
<head>
<title>My PHP Program</title>
</head>
<body>
<?php
echo “<h1> I love programming!. </h1>”;
echo “<h2> PHP Rocks!! </h2>”;
?>
</body>
</html>
Web Prog & Dev 2
Claudine Narciso
VARIABLES
Variables are user for storing values, such as numbers, strings or function results. User defined variables in
PHP must start with a $ sign symbol. A variable may hold a value of any type. There is no compile-time or
runtime type checking on variables. We can replace a variable’s value with another of the different type.
Naming Rules:
1. Can only contain alpha-numeric characters and underscores (a-z,A-Z,0-9, and _)
2. Must start with a letter or an underscore
3. Should not contain spaces. If a variable name is more than one-word, it should be separated with
underscore ($last_name), or with capitalization ($lastName)
VALUE TYPES
• Integer
• Floating-point/double
• Strings
• Boolean
• Array
• Object
• NULL
• Resource
OPERATORS
An operator is a symbol that represents a specific action.
• Arithmetic Operators
Web Prog & Dev 3
Claudine Narciso
• Assignment Operators
• Comparison operators
• Logical Operators
Web Prog & Dev 4
Claudine Narciso
BRANCHING STATEMENTS
• If…else Statement
<html>
<body>
<?php
$varx=4;
If($varx > 1)
echo $varx .“ is grater that 1”;
else
echo “Less”;
?>
</body>
</html>
• elseif Statement
<html>
<body>
<?php
$araw=date(“D”);
If($araw == “Fri”)
echo “Thank God it’s Friday!”;
else if ($araw == “Sun“)
echo “Have to go to church! ”;
else
echo “Hope you have a nice day! ”;
?>
</body>
</html>
• Switch Statement
<html>
<body>
<?php
$varx=3;
switch (#varx)
{
case 1:
echo “Variable x has a value of 1”; break;
case 2:
echo “Variable x has a value of 2”; break;
case 3:
echo “Variable x has a value of 3”; break;
default:
echo “No number between 1 and 3”;
}
?>
</body>
</html>
Web Prog & Dev 5
Claudine Narciso
CONTROL STRUCTURES
Control structures in programming are used to execute the same block of code at a specified number of times.
Types of Loops
• While – loops through a block if and as long as a specified condition is true
• For – loops through a block of code specific number of times
• Do while – loops through a block of code once, and then repeats a loop as long as a special condition
is true
• Foreach – loops through a block of code for each element in a array
ARRAYS
• Numeric Array – an array with a numeric index. Values are stored and accessed in a linear faschion
• Associative array – an array with strings as index. This stores element values in association with key
values rather that a strict linear index order
• Multidimensional array – an array containing one or more arrays and values are accessed using
multiple indeces
<?php
$student = array(“firstname” => “Lodi”, “lastname” => “petmalu”, “age” => “bente” );
echo $student[“firstname”];
?>
<html>
<head> <title>Practice PHP POST</title> </head>
<body>
<form id="form1" name="form1" method="post" action="welcome.php">
<label>Username:<input type="text" name="txtUsername" id="txtUsername"/></label>
<p><label>Password:<input type="password" name="txtPassword" id="txtPassword"/></label></p>
<p><label><input type="submit" name="btnInsert" id="btnInsert" value="Login" /></label></p>
</form>
</body>
</html>
Web Prog & Dev 6
Claudine Narciso
welcome.php
<html>
<head> <title>Practice PHP POST</title> </head>
<body>
<?php
$name = $_POST['txtUsername'];
echo "WELCOME ".$name;
?>
</body>
</html>
login.php
<html>
<head> <title>Practice PHP GET</title> </head>
<body>
<form id="form1" name="form1" method="get" action="welcome.php">
<label>Username:<input type="text" name="txtUsername" id="txtUsername"/></label>
<p><label>Password:<input type="password" name="txtPassword" id="txtPassword"/></label></p>
<p><label><input type="submit" name="btnInsert" id="btnInsert" value="Login" /></label></p>
</form>
</body>
</html>
welcome.php
<html>
<head> <title>Practice PHP GET</title> </head>
<body>
<?php
$name = $_GET['txtUsername'];
echo "WELCOME ".$name;
?>
</body>
</html>
Web Prog & Dev 7
Claudine Narciso
PHP FILE UPLOAD
index.php
<h2> Change Profile Picture </h2>
<form name = "sign" method = "POST" enctype = 'multipart/form-data' action = "upload.php">
Upload Profile Pic </br>
File: <input type = "file" name = "file"> </p>
<input type = "submit" value = "Upload" > </br>
</form>
1. the enctype attribute of the <form> tag specifies which aontent-type to use when submitting the
form.
2. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be
uploaded
3. The type=”file” attribute of the <input> tag specifies that the input should be processed as a file.
Note: allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.
upload.php
<?php
if((($_FILES["file"]["type"] == "image/gif")
||($_FILES["file"]["type"] == "image/jpeg")
||($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"]< 20000))
{
if($_FILES["file"]["error"]>0){
echo "Return Code: ". $_FILES["file"]["error"]."<br/>";
}
else{
echo "File Name to Upload: ".$_FILES["file"]["name"]."<br/>";
echo "Type: ".$_FILES["file"]["type"]."<br/>";
echo "Size: ".($_FILES["file"]["size"]/1024) ."Kb<br/>";
echo "Temporary File name: ".$_FILES["file"]["tmp_name"]."<br/>";
if(file_exists("saveUpload/".$_FILES["file"]["name"])){
echo $_FILES["file"]["name"]."already exists.";
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"],"saveUpload/".$_FILES["file"]["name"]);
echo "Saved in: ". "saveUpload/".$_FILES["file"]["name"];
}
}
}
else{
echo "Invalid file.";
}
Web Prog & Dev 8
Claudine Narciso
?>
By using the global PHP $_FILES array we can upload files from a client computer to remote server.
1. $_FILES[“file”][“name”] – the name of the uploaded file
2. $_FILES["file"]["type"] – the type of the uploaded file
3. $_FILES["file"]["size"] – the size in bytes of the uploaded file
4. $_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server
5. $_FILES["file"]["error"] – the error code resulting from the file upload
It is a de-facto standard database for websites that support huge volumes of both data and end users.
To create your database we will be using phpMyAdmin which is web based software used for creating and
maintaining MySQL databases provided by wamp.
1. Start WAMPSERVER.
2. Open phpMyAdmin
3. Create database named dbuser then click create.
8. To view the records, click SQL type “Select * from user” the Go.
Web Prog & Dev 11
Claudine Narciso
9. To add security to your database, click privileges, then Add a new User
Web Prog & Dev 12
Claudine Narciso
10. Fill in the log-in information, then click Go.
CONNECTING TO DATABASE
Before we can access data in a database, we must create a connection to the database. In PHP, this is done
by mysql_connect() function.
Syntax:
mysql_connect(servername, username, password);
Parameter Description
Severname Optional. Specifies the server to connect to. Default value is
“localhost:336”
Username Optional. Specifies the username to login with. Default value is the
name of the user that owns the server process
Password Optional. Specifies that password to login with. Default is “”.
<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysql_error());
?>
We store the connection in a variable ($conn). The “die” part will be executed if the connection fails.
<?php
$conn=mysql_connect("localhost","root", “”);
if(!$conn)
Web Prog & Dev 13
Claudine Narciso
die('Cannot connect to the server!'.mysqli_error());
mysqli_close($conn);
?>
Note: to get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a mysql connection.
<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());
mysqli_close($conn);
?>
<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
Web Prog & Dev 14
Claudine Narciso
Note: when we create a database field of type varchar, specify the maximum length of the field, e.g.
varchar(15).
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());
mysqli_select_db($conn ,"dbuser");
mysqli_query($conn, “insert into user (username, password) VALUES
(‘claud’,'123')”);
mysqli_close($conn);
?>
</body>
</html>
Web Prog & Dev 15
Claudine Narciso
insert2.php
<html>
<head> <title>Practice PHP</title> </head>
<body>
<p>
<?php
$conn=mysqli_connect("localhost","root");
if(!$conn)
die('Cannot connect to the server!'.mysql_error());
mysqli_select_db($conn,"dbuser");
$temp1 = $_POST['txtUsername'];
$temp2 = $_POST['txtPassword'];
//echo $temp1 ." ".$temp2,"</br>";
?></p>
<p>
<form id="form1" name="form1" method="post" action="records.php">
<label><input type="submit" name="btnview" value="View
Records"/></label>
</form></p>
<p> </p>
</body>
</html>
Web Prog & Dev 16
Claudine Narciso
records.php
<?php
$conn = mysqli_connect("localhost","root");
if(!$conn)
die("Not connected.".mysql_error());
mysqli_select_db($conn,"dbuser");
$result= mysqli_query($conn, "select * from user");
echo "<table border= '1'><tr>";
echo "<th>Username</th>";
echo "<th>Password</th></tr>";
while($row=mysqli_fetch_array($result))
{
$temp1=$row['username'];
$temp2=$row['password'];
echo"<tr><td> $temp1</td>";
echo"<td> $temp2</td><tr>";
}
mysqli_close($conn);
echo "<table>";
?>
mysqli_select_db($conn ,"dbuser");
$result= mysqli_query($conn ,"select * from user where username = ‘abc’");
while($row=mysqli_fetch_array($result))
{
echo"The password is: ".$row[‘password’];
echo"<br/>";
}
mysqli_close($conn);
?>
Web Prog & Dev 17
Claudine Narciso
edit.php
<html>
<head> </head>
<body>
<form id="form1" name="form1" method="post" action="myedit.php" >
<p><label>Username: <input type="text" name="txtUsername"
id="txtUsername"/></label></p>
<p><label>New Password: <input type="password" name="txtPassword"
id="txtPassword"/></label></p>
<p><label><input type="submit" name="btnedit" id="btnedit"
value="Change"/></label></p>
</form>
</body>
</html>
myedit.php
<?php
$conn=mysqli_connect("localhost","root");
if(!$conn)
die('Cannot connect to the server!'.mysql_error());
mysqli_select_db($conn,"dbuser");
$temp1= $_POST["txtUsername"];
$temp2= $_POST["txtPassword"];
?>
Web Prog & Dev 18
Claudine Narciso
delete.php
<html>
<head> </head>
<body>
<form id="form1" name="form1" method="post" action="delete2.php" >
<p><label>Username: <input type="text" name="txtdel"
id="txtdel"/></label></p>
<p><label><input type="submit" name="btndel" id="btndel"
value="Delete"/></label></p>
</form>
</body>
</html>
mydelete.php
<?php
$conn=mysqli_connect("localhost","root");
if(!$conn)
die('Cannot connect to the server!'.mysql_error());
mysqli_select_db($conn,"dbuser");
$temp1= $_POST["txtdel"];
Syntax:
setcookie(name, value, expire, path, domain);
Note: the setcookie() function must appear BEFORE the <html> tag.
<?php
$expiration=time()+60*60*24*7;
setcookie(“guest”, “Claudine Narciso”, $expiration);
?>
<html>
……
The expiration time is set to a week (60 sec * 60 min * 24 hours * 7 days).
Retrieving Cookies
PHP $_COOKIE variable is used to retrieve a cookie value.
<?php
// print a cookie
echo $_COOKIE[“guest”];
// a way to view all cookies
print_r($_COOKIE);
?>
isset() Function
the isset function is used to find out if a cookie has been set or not.
<html>
<body>
<?php
if(isset($_COOKIE["guest"]))
echo "Welcome ".$_COOKIE["guest"]."<br>/";
else
echo "Welcome guest!</br>";
?>
</body>
</html>
Deleting Cookies
In deleting cookies, just make sure that the expiration date is set in the past.
<?php
// set the expiration date to one hour ago
setcookie("guest","", time()-3600);
?>
Web Prog & Dev 20
Claudine Narciso
PHP Sessions
Sessions create a file in a temporary directory on the server where registered session variables and their
values are sorted. This data will be available to all pages and on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Bore
using any session variable make sure we have setup this path.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique
session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file
bearing that name and a validation can be done by comparing both values.
Note: the session_start() function must appear BEFORE the <html> tag.
The code above will register the user’s session with the server, allow us to start saving user information, and
assign a UID for the user’s session.
<?php
session_start();
$_SESSION['viewed'] = 1;
?>
<html>
<body>
<?php
echo "Page views: ".$_SESSION['viewed'];
?>
</body>
</html>
In the example below, we created a simple page views counter. The isset() function checks if the “viewed”
variable has already been set. If “viewed” has been set, we can increment our counter. If “viewed” doesn’t
exist, we create a “viewed” variable, and set it to 1.
<?php
session_start();
if(isset($_SESSION['viewed']))
$_SESSION['views']=$_SESSION['viewed']+1;
else
$_SESSION['viewed']=1;
echo "VIEWs: ".$_SESSION['viewed'];
?>
Web Prog & Dev 21
Claudine Narciso
Session Register
Session Register accepts a variable number of arguments, any of which can be either a string holding the
name of a variable or an array consisting of variable names of other arrays.
Syntax:
Session_register(mixed $name [, mixed $...])
Destroying Session
The unset() function is used to free the specified session variable
<?php
unset($_SESSION['viewed']);
?>
We can also completely destroy the session by calling the session_destry() function:
Note: session_destry() will reset our session and we will lose all our stored session data.
index.php
<?php
include("connect.php");
$_SESSION['username']="claud";
$username = $_SESSION['username'];
echo "<h1>Welcome, ". $username."! <h1>";
$query = mysqli_query($conn,"select * from avatar where name = '$username'");
//echo $query." ". $mysqli_num_rows($query);
if(mysqli_num_rows($query) == 0){
die("User not found..");
} else{
$row = mysqli_fetch_assoc($query);
$location = $row['imageLocation'];
echo "<img src='$location' width='200' height='200'> </p>";
}
mysqli_close($conn);
?>
</p> Upload new Avatar
<form method='POST' enctype="multipart/form-data" action='view.php'>
File: <input type='file' name='myfile'>
<input type='submit' name='submit' value='UPLOAD'>
</form>
view.php
<?php
include("connect.php");
$username = $_SESSION['username'];
if($_POST['submit']){
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name){
$location = "upload/$name";
echo "Upload: ".$_FILES["myfile"]["name"]."</br>";
echo "Type: ".$_FILES["myfile"]["type"]."</br>";
echo "Size: ".($_FILES["myfile"]["size"]/1024)."kb</br>";
echo "Temp Name: ".$_FILES["myfile"]["tmp_name"]."</br>";
move_uploaded_file($tmp_name,$location);
$query = mysqli_query($conn, "UPDATE avatar SET
imageLocation='$location' WHERE name='$username'");
die ("Your avatar has been uploaded <a href='index.php'> HOME </a>");
}
else die("Please select a file!");
}
mysqli_close($conn);
?>
Web Prog & Dev 23
Claudine Narciso