Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views23 pages

c2 Language

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

Web Prog & Dev 1

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

START AND END TAGS


Opening Tag Closing Tag
<?php ?>
<? ?>
<script language=”php”> </script>

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”];
?>

PHP FORM HANDLING


There are two ways the browser client can send information to the web server by using the GET Method or
POST Method. Before the browser send information, it encodes it using a scheme using URL encoding. In this
scheme, name/value pairs are joined with equal signs and different pairs are separated with ampersand.
HTML forms contain at least the following elements:
1. Method
2. Action
3. Submit button

The $_POST Variable


The $_POST is a special variable that is known as a super global because it is built into PHP and is
a available throughout an entire script. $_POST already exists when our script runs. It is an array of variable
names and values sent by the HTTP post method. It is used to collect values from a form with a method =
“post”. The information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.
login.php

<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>
&nbsp;
<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>

The $_GET Variable


$_GET variable is an array of variable names and values sent by HTTP get method. It is used to collect
value from a form with a method=”get”. Information sent from a form with the GET method is visible to everyone.
It will be displayed in the browser’s address bar and it has limits on the amount of information to send (max. 100
characters).
Note: $_GET variable should not be used when sendin passwords or other sensitive information.

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>
&nbsp;
<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>

NOTE: first, create a folder named saveUpload inside C:\wamp\www\directory

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

PHP and MySQL


A database server is a program that can store large amounts of information in an organized format that’s
easily accessible through programming languages like PHP. PHP will work with virtually all database software,
including Oracle and Sybase but most commonly used is freely available in MySql database. MySQL is the most
popular open source database system. It is a program that can store large amounts of information in an organized
format that’s easily accessible through scripting languages like PHP.

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.

4. Create table named user with two fields then go


Web Prog & Dev 9
Claudine Narciso

5. Type username, password as fields then click save.

6. Click Insert to add records.


Web Prog & Dev 10
Claudine Narciso
7. Fill in the values then click Go.

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.

CLOSING DATABASE CONNECTION


The connection will be closed automatically when the script ends. To close the connection before, use the
mysql_close() function.
Syntax:
mysqli_close(connection_name);

<?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);
?>

CREATING MySQL DATABASE


The create database statement is used to create database in MySQL.
Syntax:
CREATE DATABASE database name;

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());

if(mysqli_query($conn ,“CREATE DATABASE dbuser”))


echo “Database successfully created.”;
else
echo “Error creating database: ”. mysqli_error();

mysqli_close($conn);
?>

CREATING MySQL TABLE


The CREATE TABLE statement is used to create a table in MySQL.
Syntax:
Create Table table_name
(
Column_name1 data_type,
Column_name2 data_type,
Column_name3 data_type, \...)

<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());

if(mysqli_query($conn ,“CREATE DATABASE dbuser”))


echo “Database successfully created.”;
else
echo “Error creating database: ”. mysqli_error();

$sql = “Create Table user


(
username varchar(20),
password varchar(10)
)”;

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).

• Primary Keys and Auto Increment Fields


A primary key is used to uniquely identify the rows in a table.
Auto_increment automatically increases the value of the field by 1 each time a new record is added.
<?php
$conn=mysqli_connect("localhost","root", “”);
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());

$sql = “Create Table Employee


(
EmpID int not NULL AUTO_INCREMENT,
PRIMARY KEY (EmpID),
Name varchar(15)
)”;

mysqli_query($conn, $sql);
mysqli_close($conn);
?>

PHP MySQL INSERT INTO


The insert into statement is used to add new records to a database table.
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3,…)

<?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);
?>

Insert Data from a Form Into a Database


insert.php
<html>
<head> <title>Practice PHP</title> </head>
<body>
<form id="form1" name="form1" method="post" action="insert2.php">
<label>Username:<input type="text" name="txtUsername"
id="txtUsername"/></label>
<p><label>Password:<input type="password" name="txtPassword"
id="txtPassword"/></label></p>
&nbsp;
<p><label><input type="submit" name="btnInsert" id="btnInsert"
value="Add New Record" /></label></p>
</form>

</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>";

$sql="insert into dbuser.user(username, password) VALUES


('$temp1','$temp2')";
mysqli_query($conn,$sql);
mysqli_close($conn);
//echo $sql;
echo "Username: ".$temp1." successfully added to the database.";

?></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> &nbsp;</p>
</body>
</html>
Web Prog & Dev 16
Claudine Narciso

PHP MySQL SELECT


The select statement is used to select data from database.
Syntax:
SELECT column_name(s)
FROM table_name

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>";
?>

PHP MySQL the WHERE Clause


The where clause is used to extract only those records that fulfill a specified criterion.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
The following example selects all rows from the “user” table where “username=abc”.
<?php
$conn = mysqli_connect("localhost","root");
if(!$conn)
die("Not connected.");

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

PHP MySQL Update


This command is used to update existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value, column2=value,…
WHERE some_column=some_value
Note: the WHERE clause specifies which record or records that should be updated. If we omit the WHERE
clause, all the records will be updated.

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"];

$sql="update user set password = '$temp2' where username = '$temp1'";


mysqli_query($conn,$sql);
mysqli_close($conn);
echo $temp1. " Database Successfully updated."

?>
Web Prog & Dev 18
Claudine Narciso

PHP MySQL DELETE


This command is used to delete records from a database
Syntax:
DELETE FROM table_name
WHERE some_column=some_value
Note: the WHERE clause specifies which record or records that should be deleted. If we omit the WHERE
clause, all records will be deleted.

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"];

$sql="delete from user where username= '$temp1'";


mysqli_query($conn,$sql);
mysqli_close($conn);
echo $temp1. ". Successfully deleted to the database.";
?>
Web Prog & Dev 19
Claudine Narciso
PHP COOKIES
PHP Cookies is used to identify a user. It is a small file that the server embeds on the user’s computer. Each
time that the computer requests a page with a browser, it will send the cookie too.

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 session is started following this happen:


1. PHP first creates a unique identifier for that particular session which is random string of 32 hexadecimal
numbers such as 94bmi92uuclsvmo4bu1ku86qr1.
2. A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session
identification string.
3. A file is automatically created on the server in the designated temporary directory and bears the name
of the unique identifier prefixed by sess_
Ex: sess_94bmi92uuclsvmo4bu1ku86qr1

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.

<?php session_start(); ?>

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.

Storing Session Variable


To store and retrieve session variables user the PHP $_SESSION variable:

<?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.

Changing Avatar on Upload


Web Prog & Dev 22
Claudine Narciso
CODE:
connect.php
<?php
$conn=mysqli_connect("localhost","root");
if(!$conn)
die('Cannot connect to the server!'.mysqli_error());
mysqli_select_db($conn,"dbweb") or die ("Cannot connect.");
session_start();
?>

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

You might also like