Web Programming With PHP
Web Programming With PHP
1.1 Background
In this era of technological advances, the website has become a familiar thing to our ears, especially in
the internet world. Although many people have a homepage on the internet, both using an ISP and a
free web server, in general the homepage is static and cannot interact with web visitors.
Most people generally only act as users and only a few know the process behind it because they do not
master web programming. Basically, a homepage that can interact with website visitors or a dynamic
homepage does not require high programming skills.
1. To give an idea that in learning and creating a web using PHP is actually not too difficult.
2. So that internet users in particular can further develop their potential, and not only as users but
can act as creators of a dynamic web address (homepage).
1.4 Scope
In order not to deviate from the problems discussed, in the discussion of this paper the author limits the
subject of making web programs using PHP.
CHAPTER II
DISCUSSION
b. Semicolon (;)
If you look at the previous example, there is a semicolon at the end of the echo command. A semicolon
is a marker for the end of a PHP statement and must be present.
Example:
<html>
<head>
<title>My first PHP page</title>
</head>
<body> <?php
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
?>
</body>
</html>
c. Move Space
As with HTML, changing spaces in PHP will not affect the appearance of the result. In other words, the
whitespace will be ignored by PHP.
Consider the following example. In this example, three different forms of writing PHP code are given but
will produce the same display in a web browser.
Example:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
echo "Hello World! ";
echo "Hello World! “;?>
</body>
</html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World! ";
echo "Hello World! ";
?>
</body>
</html>
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
echo "Hello World! ";
echo "Hello World! "; ?>
</body>
</html>
2.2.2 Data Types in PHP
In PHP, the name of each variable begins with a $ (dollar) sign. For example, the variable "e" is written
with $e. PHP only has 6 data types, namely: integer, double, boolean, string, array and object.
a. Integers are all numbers without decimal points.
b. Double is floating point like 3.14159 or 49.0
c. Boolean has only 2 values, namely TRUE and FALSE
d. Strings are sequences of characters like 'PHP supports string operations'
e. Array is a collection of names and indexes.
f. Objects are examples of programmer-defined classes.
The type of this variable does not need to be determined by the programmer, but is determined at
runtime by PHP depending on the context in which the variable is used. Simple data types in PHP
(integer, double, boolean and string) are familiar. Some programming languages have different sizes for
numeric data types by allowing a larger range of values but also requiring more memory. For example,
the C language has a short type (small integer), a long type (larger integer) and an int type (which is
halfway between short and long).
a. Integer
Is the simplest data type, can be used as a variable or used in expressions such as:
$int_var = 12345;
$another_int = -12345 + 12345;
Integers can be read in 3 formats according to number-based; decimal (base 10), octal (base 8) and hexa
(base 16). Decimal format as default, octal is specified with '0' and hexa prefixed with '0x'. The format
can be preceded by a '-' sign for negative integers.
$integer_10 = 1000;
$integer_8 = – 01000;
$integer_16 = 0×1000;
print("integer_10 : $integer_10<BR>");
print("integer_8 : $integer_8<BR>");
print("integer_16 : $integer_16<BR>");
d. String
Is a collection of characters, as below:
$string_1 = “This is a string in double quotes”;
$string_2 = “This is a somewhat longer, singly quoted string”;
$string_39 = “This is a string has thirty-nine characters”;
$string_0 = " "; //This is a string with zero characters
Strings can be enclosed in single or double quotes. Single quotes are like literals while double quotes
replace variables with their values like interpreting special characters.
$literally = 'My $variable will not print!\n';
print($litrerally);
$win_path = 'C:\\InetPub\\PHP\\';
print("A windows-style pathname: $win_path<BR>");
Will produce output:
My $variable will not print!\n
A windows-style pathname: C:\\InetPub\PHP\
To put single quotes (such as apostrophes) in single quotes, put a backslash:
$singly_quoted = 'This quote mark\'s no big deal either';
Strings delimited by double quotes are processed in 2 ways:
1. Certain characters starting with a backslash ('\') are replaced with special characters
2. The variable name (starting with $) is replaced with a string that represents its value.
send.php
</html>
<form action=”empty.php” method=”post”>
Name: <input><br> // $name variable is created
<input value="Submit">
</form>
</html>
empty.php
<html>
<body>
<? echo $name; ?>
</body>
</html>
To initialize a variable in PHP, simply assign a value to the variable. But for types like arrays and objects it
requires a different mechanism
$name = "Hendra";
$weight = 57.5;
$age = 17;
e. Arrays
The array type in PHP makes it easy for programmers to group different values and index them
numerically (as well as by name). Array elements are listed with indexes in parentheses (the[1], [2],[3]..)
and elements of different types can be designated by the same array.
print("my_array is $my_array<BR>");
print("my_array[0] is $my_array[0]<BR>");
print("my_array[5] is $my_array[5]<BR>");
$my_array[5] = “Slot #6”;
print("my_array is $my_array<BR>");
print("my_array[0] is $my_array[0]<BR>");
print("my_array[5] is $my_array[5]<BR>");
Will produce output:
my_array is
my_array[0] is
my_array[5] is
my_array is Array
my_array[0] is
my_array[5] is Slot #6
Arrays are one of the most useful features in PHP and while they may look like arrays in other
programming languages, the implementation is very different. In many programming languages, we
declare arrays with statements such as:
Int int_array[10]; //NOT PHP! Sets a block of up to 10 integer variables in memory that can be accessed
with an int_array index between 0 – 9. So far only integers are used as indexes, actually string values can
also be used as array indexes. String indexes are used in the same way as numeric indexes, such as:
$tasty['Spanish'] = “paella”;
$tasty['Japanese'] = “sashimi”;
$tasty['Scottish'] = “Haggis?”;
Initializing Array
Arrays can be initialized in two ways: by assigning values directly and using the array() construction. To
assign a value directly to an array, simply assign a value to an array variable with an empty subscript.
The value will be added as the last element of the array. Something to keep in mind is that array
elements start at index 0 (not 1)
$name[ ] = "Aden"; //$name[0] = "Aden"
$name[ ] = "Marsa"; //$name[1] = “Marsa”;
Example Arrays:
array.php
<html> <h1>Creating an array the first way</h1> <?
$a[0] = "abc"; // a is a scalar array
$a[1] = "def";
$b["foo"] = 13; //b is an associative array
echo "Value a[0]=$a[0], value a[1]=$a[1], <br>
value b[\”foo\”]=” . $b["foo"];
?> <h1>Second way</h1> <?
$a[ ] = "hello"; // $a[2] = = "hello"
$a[ ] = “world” // $a[3] = = “world”
echo "Value a[2]=$a[2], Value a[3]=$a[3];
?></html>
multiarray.php
<html><?
$f=101
$a[1] = $f; #one-dimensional example
$a["foo"] = $f;
$b[1][0] = $f; #two dimensional
$b["foo"][2] = $f;
$b[3][“bar”] = $f;
$c[“foo”][4][“bar”][0] = $f; #four dimensions
echo “a[1] = $a[1] and a[\"foo\”]=” . $a["foo"];
echo "b[1][0] = " . $b[1][0] . “ and b[\"foo\"][2]=” . $b["foo"][2];
f. Object
Object is a data type that can be a number, variable or even a function. Object was created with the aim
of helping programmers who are familiar with Object Oriented Programming, although the OOP facilities
provided by PHP are still very lacking. The following is an example of using the object data type.
<? // object.php
class test
{ var $str = "Class Variable";
function set_var($str)
{ $this->str = $str; }
}
$class = new Test;
echo$class->str;
$class->set_var("Object Variable");
echo("<br>$class->str"); ?>
In the object.php program there is a class with the name test, then a test object data is created from the
test class, this data is printed and the output is "Class Variable". The test class also has a method with
the name set_var, this method is used to assign a value to the $str variable. The test object data created
or instance of the test class will have all the properties of the test class, including its methods, so that an
object of type data can also contain a method (function). In the program above, we use the set_var
method on the test object to change the value of the $str variable to "Object Variable" and then print it.
Initializing Object
To initialize an object, you can use the new command. This command is used to initialize an object to a
variable.
Empty class {
Function not() {
echo “does nothing”; } }
$bar = new empty;
$var -> no();
2. Variables
Sometimes it is more convenient to use variables; which is the name of the variable that can be used
dynamically. Normally variables are created with:
$a = "hello"; // normal -> created $a variable containing "hello"
A variable variable will use the value of a variable to be the name of the variable, for example:
$a = "hello"; // normal -> created $a variable containing "hello"
$$a = "world"; // variables -> created $hello variable containing "world"
In the example above, two variables will be formed, namely $a and $hello. Where $a contains "hello"
and $hello contains "world". Next the following command
echo "$a ${$a}"; // returns "hello world"
echo "$a $hello"; // returns "hello world"
3. Determination of Variable Type
Determination does not require an explicit variable declaration, the variable type is determined based
on the context in which it is used at runtime. In other words, if assigning a string value to a variable var,
var becomes a variable of type string. If you assign an integer value to var, it will automatically change to
an integer type. An example of type conversion automation in PHP is the addition operator “+”. If one of
the operands is of type double, then all other operands are evaluated as double and the result is double
$try = “0”; //$try is a string (ASCII 48)
$try++; //$try is the string “1” (ASCII 49)
$try += 1; //$try now is integer (2)
$try = $try + 1.3; //$try now is double(3.3)
$try = 5 + “10 boxes”; //$try is integer (15)
2. Expression
Almost everything written in PHP script is script. The simplest definition of an expression is "anything
that has value". The simplest examples of expressions are constants and variables. When typing “$a=5”
it means assigning the value '5' to $a.
A more complex example of an expression is a function. For more details, consider the example below:
hello() function
{ Returns 5; }
So when you write $c = hello() it is the same as assigning a value of 5 to the $c variable, because the
hello function returns 5. The above is an example of a simple function. PHP supports 3 types of scalar
values: integer, floating point and string values. (A scalar value is a value that cannot be divided into
smaller parts, such as an array). PHP also supports 2 types of non-scalar values, namely arrays and
objects.
3. Branching
a. if
The If command is the most important thing in most programming languages. PHP's If command
resembles the If form of the C language. If (expression) An expression command is something that can
be evaluated to a value of TRUE or FALSE. The following is an example that will print 'a is greater than b'
if the value of $a is greater than $b.
If ($a > $b)
Print “a is greater than b”;
If the command to be executed when the expression TRUE is more than one then the commands need
to be grouped with curly braces { and } can also be formed as a caged if (if in if)
If ($a > $b) {
Print “a is greater than b”;
$b = $a; }
b. Else
Often we need to run another command if the value of the expression is FALSE. For this purpose, the
Else command can be used.
If ($a > $b) {
Print “a is greater than b”;
} else {
Print “a is not greater than b”;
}
c. Elseif
Elseif is a combination of an if and else, it can be used in a choice of multiple conditions.
If ($a > $b) {
Print “a is greater than b”;
} elseif ( $a==$b) {
Print "a equals b";
} else {
Print “a is smaller than b”;
}
d. SWITCH
The SWITCH command resembles a number of IF commands with the same expression. Often we want
to compare a number of variables (or expressions) with a number of values and run a specific command
for each value.
Example1.php
/* example 1 */
if ($I == 0)
{ print "I equals 0"; }
if ($I == 1)
{ print "I is equal to 1"; }
if ($I == 2)
{ print "I is equal to 2"; }
SWITCH commands are executed line by line (actually command by command). At first no code is
executed. Only for a moment when a CASE command is found with a value that matches the value of the
expression in SWITCH, PHP executes the command. PHP continues execution until the end of the
SWITCH block or the first time it encounters a BREAK command. If you don't write a BREAK command at
the end of the list of commands in a case, PHP will continue execution for the next case.
Example2.php
/* example 2 */
switch ($I) {
case 0;
print "I is equal to 0";
case 1;
print "I equals 1";
case 2;
print "I equals 2";
}
Here if $I equals 0, PHP will execute all print! commands. If $I equals 1, PHP will execute the last two
print commands, if and only if $I equals 2 prints 'I equals 2'. So it is very important not to forget the
BREAK command. A special case is the default case. This case will be the same as everything that cannot
be compared to the previous cases.
4. Loop
a. while
While is the simplest loop in PHP. The basic form of the While command is:
WHILE(expression) statement
The statement will be repeated as long as the expression has a value of TRUE. If in the loop it turns out
that the expression evaluates to FALSE, then the loop is never executed. If the command to be repeated
is more than one, then the commands can be grouped by typing them between curly brackets { and } or
using an alternative writing procedure:
WHILE(expression): statement… ENDWHILE;
Here are 2 identical examples that will print values 1 to 10 :
Example3.php :
/*example */
$I = 1;
while ($I <= 10) {
print $I++; /* the value to be printed is the value of $I before adding 1 (post-increment)*/
}
Example 4.php
/*example */
$I = 1;
while ($I <= 10):
print $I;
$I++;
endwhile;
b. Do… While
The DO…WHILE loop is the same as the While loop, only the expression is checked at the end of the
loop. So this type of repetition occurs at least once. Writing procedure for DO…WHILE loop:
$I = 0;
do
{ print $I; }
while($I>0);
c. FOR
The FOR loop is the most complex loop in PHP, and resembles the FOR loop in C. The procedure for
writing the FOR loop is:
FOR (expression1; expression2; expression3) statement
The first expression (expression1) is evaluated (executed) un-conditionally at the start of the loop. At the
start of each iteration, expression2 will be evaluated. If the result of the evaluation is TRUE, the loop will
continue and the statement will be executed. If the evaluation result is FALSE, the loop is terminated. At
the end of each iteration, expression3 will be evaluated (executed). The following example will print the
numbers 1 to 10:
Example5.php
For ($I = 1; $I <= 10; $I++)
{ Print $I; }
Example6.php
For ($I = 1;; $I++) {
If ($I > 10) { Break; }
Print $I; }
Example7.php
$I = 1;
for(;;) {
If ($I > 10) { Break; }
Print $I;
$I++; }
Example8.php
For ($I = 1; $I <= 10; print $I, $I++);
d. BREAK
BREAK out of the current loop:
$I = 0;
while($I < 10) {
if ($arr[$I] == 'stop') { break; }
$I++; }
e. CONTINUE
CONTINUE will jump to the start of the current loop
while(list($key,$value) = each($arr)) {
if ($key % 2) { //skip even members
continue; }
WorkOdd($value); }
2.2.5 REQUIREMENTS
The REQUIRE command replaces the command with a specific file and is almost like the #include
processor in C. This means you can't put the required() command in a loop structure and expect it to
include a different file in each iteration. To do this, use the INCLUDE command.
Require('header.inc');
2.2.6 INCLUDE
The INCLUDE command will include and evaluate certain files. This happens every time the INCLUDEdit
command is found, so you can use the INCLUDE command between a loop structure to include a
number of different files.
$files = array('first.inc','second.inc','third.inc');
for ($I = 0; $I < count($files); $I++) {
include($files[$I]); }
Include() is different from require(). In the include command the evaluation is repeated every time the
command is found (and only when it is executed), while the require() command will be replaced with
the required file the first time it is found, it's up to whether the file will be evaluated or not. Because
INCLUDE is a language-specific construct it must be sandwiched between blocks.
/* This one is FALSE and will not work as expected */
if ($conditon)
include($file);
else include($other);
/* This one is TRUE */
if ($condition)
{ include($file); }
else { include($other); }
3. Bitwise Operators
Bitwise operators can be used to make certain bits of an integer on (1) or off (0).
Bitwise Operator Table
Example Name Results
$a & $b And Bits that are worth 1 in $a and $bwill be set to 1.
$a | $b Or Bits that are worth 1 in $a or $bwill be set to 1.
$a ^ $b Xor Bits that are worth 1 in $a or $b but not bothwill be set to 1.
~ $a Note Bits worth 1 in $awill be set to 0, and vice versa.
$a << $b Shift left Shift the bit $a $b steps to the left (each step means "multiply by two").
$a >> $b Shift right Shift $a bits $b steps to the right(each step means “divided by two”).
4. Logical Operators
Logical Operator Table
Example Name Results
$a and $b And True if $a and $b are true.
$a or $b Or True if one of $a or $b is true.
$a xor Xor True if one of $a or $b is true, but not both.
!$a Note True if $a is not true.
$a && $b And True if $a and $b are true.
$a || $b Or True if one of $a or $b is true.
5. Comparison Operators
The comparison operator allows to compare two values
Comparison Operator Table
Example Name Results
$a == $b Together with True if $aequal to $b.
$a != $b Not equal to True if $a is not equal to $b
$a < $b Less than True if $a is less than $b
$a > $b More than True if $a is greater than $b.
$a <= $b Less than ortogether with True if $a is less than or equal to $b.
$a >= $b More than ortogether with True if $a is greater than or equal to $b.
6. Order of Operators
The order of the operators determines how an expression is executed by PHP. For example, in 1 + 5 * 3,
the answer is 16 instead of 18 because the multiplication operator (*) has a higher order of working than
the addition operator (+).
Operator Order Table
Associativity Operator
Left ,
Left Or
Left Xor
Left And
Right Print
Left ===-=*=/=.=%=&=!=~=<<=>>=
Left ?:
Left ||
Associativity Operator
Left &&
Left |
Left ^
Left &
Non-associative == !=
Non-associative <<=>>=
Left <<>>
Left +-.
Left */ %
Right !~++–(int) (double) (string) (array) (object) @
Right [
Non-associative New
2.2.8 Handling Form, Cookies and Environment Variables
1. Variables on Form
In CGI programming, our program will interact with external variables that are sent through the form
either by the Get method or the POST method. When a form is submitted to a PHP script, all variables of
the form can automatically be processed by the PHP script as normal variables. As an example :
<form action = "empty.php" method="post">
Name : input type = “text” name="name"><br>
<input type="submit" value="Submit">
</form>
Name :
Send
When the form is submitted, PHP creates a $name variable, which contains what was typed in the Name
: field of the form. PHP also supports array variables in the context of forms, but they are limited to only
one dimension, Example:
<form action="array.html" method="post">
Name : <input type = “text” name="personal[name]"><br>
Email : <input type = “text” name="personal[email]"><br>
Beer : <br>
<select multiple name="beer"[]">
<option value="warthog">Warthog
<option value="guinness">Guinness
</select>
<input type="submit">
</form>
Name :
Email :
Beers :
Warthog Submit Query
2. Variables in IMAGE SUBMIT
When submitting a form, it is also possible to use an image instead of the submit button with the
following HTML tag:
<input type name src="image.gif" name="sub">
When the user clicks on the image, the form will be sent to CGI with 2 additional variables, namely
sub_x and sub_y. These two variables are the coordinates where the click is made on the image.
3. Variables in HTTP Cookies
PHP transparently supports HTTP Cookies. Cookies are a remote data storage mechanism on the client
browser. This can be used to identify the user on the next visit. We can use the SetCookie() function.
Cookies are part of the HTTP header, so the SetCookie function must be called before any other output
is sent to the browser. This is the same as for the Header() function. All Cookies sent to us from the
client will be automatically converted into a PHP variable such as methodGET and POST data.
If you want to assign multiple values to a single Cookie, just add [ ] to the Cookie name. As an example :
SetCookie("MyCookie[ ]", "Testing", time() + 360);
Note : that a cookie will overwrite the previous cookie which has the same name in the browser, unless
the path or domain is different. So For a shopping cart application need to save a counter and send it
together. Example :
$count++;
SetCookie("Count", $Count, time() + 3600);
SetCookie("Csrt[$Count]", $item, time() + 3600);
4. Environment Variables
PHP automatically creates its normal environment variables like PHP variables.
echo $HOME; /* Displays environment variables, if set. */
Since information comes with the GET, POST and Cookies mechanisms automatically become HP
variables, it is better to read the variables directly from the environment to get the actual version. The
getenv() function can be used to do this. We can also create an environment variable with the putenv()
function.
CHAPTER III
CLOSING
3.1 Conclusion
Making a web using PHP programming has various advantages and advantages when compared to using
other similar programs. Various kinds of facilities that exist in the PHP program is very flexible and will
provide convenience in its application. For example, data entered in an html form is automatically
variable and can be used directly, so there is no need to parse so-called query strings.
Database connectivity is quite strong with native-driver support for about 15 of the most popular
databases plusODBC. PHP supports a large number of protocols such as POP3, IMAP and LDAP. PHP 4
also has new support for Java and the object distribution architecture (COM and CORBA), making n-time
developments for the first time. PHP does not support closed-source. For example, Apple and Microsoft
computers cannot cooperate with open source projects such as PHP.
Various advantages possessed by PHP play an important role in the development of the world of
technology, especially in the field of internet and information dissemination. Indirectly, these
developments will also affect various aspects of human life.
3.2 Suggestions
Before making a script in PHP, you should first understand about HTML and the basics of programming
(C/C++) because a sufficient understanding of basic programming (C/C++) will make it easier for the
application to create a script in a PHP program.
BIBLIOGRAPHY
Purwanto, yudi. 2001. Web programming with PHP, Elex Media Komputindo, Jakarta.