0% found this document useful (0 votes)
134 views

Web Programming With PHP

This document provides an introduction and overview of PHP (PHP: Hypertext Preprocessor), a popular server-side scripting language used for web development. Some key points: - PHP is an open-source scripting language that is embedded within HTML and allows developers to create dynamic web content and interact with databases. It runs on the server-side. - PHP has a history dating back to 1995 and has evolved through several versions to become a powerful language used by many websites today. - PHP code is processed on the server and HTML is returned to the browser, so PHP code is hidden from users. It offers advantages like being free, easy to learn, and allowing seamless integration of code within HTML

Uploaded by

Rival Imanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views

Web Programming With PHP

This document provides an introduction and overview of PHP (PHP: Hypertext Preprocessor), a popular server-side scripting language used for web development. Some key points: - PHP is an open-source scripting language that is embedded within HTML and allows developers to create dynamic web content and interact with databases. It runs on the server-side. - PHP has a history dating back to 1995 and has evolved through several versions to become a powerful language used by many websites today. - PHP code is processed on the server and HTML is returned to the browser, so PHP code is hidden from users. It offers advantages like being free, easy to learn, and allowing seamless integration of code within HTML

Uploaded by

Rival Imanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

PHP papers

TEXT ASSIGNMENT "WEB PROGRAMMING WITH PHP"


CHAPTER I
PRELIMINARY

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.2 Aims and Objectives

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.3 Research Method


The research methods used in the preparation of this paper are:
1. Interview method (Interview).
Interview is one of the data collection techniques in which the interviewer is face to face with the
interviewee. This method is used to obtain information and clarity directly about the process that
occurs;
2. Method of observation (Observation).
Observation is one of the data collection techniques by observing directly the object to be studied in
order to obtain complete and real data;
3. Literature Study
Literature Study is one of the data collection techniques by studying, sampling, adapting the contents of
other authors' books that are used to complete writing materials.

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

2.1 PHP introduction


2.1.1 Understanding PHP
Based on information from the official PHP website, “PHP.net”. PHP (PHP: Hypertext Processor) is a web
programming language that is embedded in an HTML script (Hypertext Markup Language) and the
syntax in it is similar to C, Java and Perl. The purpose of this language is to help web developers to create
dynamic web quickly.
PHP is a server-side scripting language that is usually used with HTML or its documents together to
create applications on the web that are very useful. PHP is the language used in HTML and works on the
server side, meaning that the syntax and commands given will be executed on the server but are
included on ordinary HTML pages so that the script does not appear on the client side.
HTML (Hyper Text Markup Language) is a web language that is very dominant as a liaison language
between (web server) and its client (web browser) around the world. PHP is a server-side scripting
language that can be used with HTML or its documents simultaneously to build applications on the web
that are very useful. PHP is designed to be able to work with database servers and is made in such a way
that the creation of HTML documents that can access the database becomes so easy. The purpose of
this scripting language is to create applications that run on web browser technology, but the whole
process is run on a web server.
PHP's main strength is database connectivity with the web. The database systems that are currently
supported by PHP are:
• Oracle • Generic ODBC • Adabas D • Sybase • PostgreSQL
• FilePro • mSQL 1.x and 2.x • Empress • Velocis • MySQL
• InterBase • Database interface ODBC • Solid • Informix
• dBase
PHP also supports communication with other services via IMAP, SNMP, NNTP, POP3 or even HTTP
protocols.
And now a web server does not only contain pictures and text compositions that contain information
about an organization but is required to be able to relate directly to the database, serve requests from
clients, create documents containing important information and so on. With such guidance, an
additional language is needed that can really interact widely with supporting applications for the
dynamic needs of the web server.
2.1.2 PHP History
PHP (Hypertext Preprocessor) was created by Rasmus Lerdorf a C programmer, and is used to record the
number of visitors on his homepage. In early 1995 released PHP / FI (Form Interpreter) which has the
basic ability to build web applications, process forms and support mySQL data.
Due to the great enthusiasm of internet users, finally in mid 1997 Rasmus Ledorf handed over its
development to a programming team in an open source framework and by Zeev Suraski and Andi
Gutmans, the parser was rewritten back into a new parser program, namely PHP 3.0 which has wider
support. Again against existing databases including MySQL and Oracle.
PHP version 4.0 was released after that using the Zend scripting engine (an acronym for the developers
Zeev Suraski and Andi Gutmas) and has been able to support Apache servers and is built-in capable of
handling session management. There are two kinds of PHP which are now widely known among web
developers, namely PHP 3 and PHP 4. PHP 3 is the first PHP language created and is suitable for creating
websites that are not too complex and large. While PHP 4 (version-4) is a PHP language. which is already
equipped with Zend engine so that it is faster, stronger, stable, easy to interact with various types of
other supporting applications such as mySQL, java, FTP client, ODBC etc.
PHP version 4 has extensions that are simpler and easier to use and are compatible with PHP version 3.
PHP 4 is often used to build web content because it can handle large, complex websites and receive
millions of hits per day.
2.1.3 How PHP Works
As mentioned before, PHP is an application on the server side or in other words, the workload is on the
server, not on the client. When the browser requests a PHP document, the web server directly uses the
PHP module to process the document. If the document contains a function that accesses the database,
the PHP module contacts the relevant database server. Documents in PHP format are returned by the
web server in HTML format, so that the PHP source code does not appear on the browser side.
2.1.4 Advantages of PHP
In its development, PHP applications have various kinds of conveniences and advantages compared to
other similar products. This is the reason people use PHP in making web programming, here are some of
the advantages that PHP has:
1. PHP is open source
PHP is a web language application that can be obtained for free and the PHP program code is provided
free of charge. Table 1.1 shows a comparison between PHP and similar products:
Table 1.1 Comparison of costs of several PHP-like products
Type ASP ColdFusion JSP PHP
Development $0-480 $395 $0 $0
Servers $620 $1,295 $0-595 $0
RDBMS $1,220-$4,220 $0-$10,000 $0-10,000 $0
Support Incident $0-245 $0-75 $0-75 $0
2. PHP is easy
PHP is easy to learn, compared to other products that have the same functionality. Unlike Java Server
Page or C based CGI, there is no requirement to learn some other programming language. Unlike Perl
which is often referred to as a "write-only-language", PHP has a very easy and user-friendly syntax. And
unlike Active Server Page, PHP does not make us to learn two different programming languages for two
needs.
3.PHP embedded
PHP script writing is integrated with HTML making it easier to manufacture. In other words PHP pages
are usually HTML pages. Similar products are Microsoft Active Server Page, Allaire Cold Fusion and Sun
JavaServer Page. PHP is sometimes referred to as “the open source ASP” because its functionality is
similar to that of Microsoft's products.
To distinguish between HTML and PHP syntax, an agreement was made: PHP scripts begin with the <?
And ends with ?>. Example :
<HTML>
<HEAD> <TITLE>A greeting</TITLE> </HEAD>
<BODY>
<P>Hi,
<?php
/* now switch to PHP mode*/
$firstname=”Eyes”;
$lastname=”Day”;
$title=”Ms.”;
PRINT($title $lastname");
//back to HTML now.
?>>
May I call you <?php PRINT(“$firstname”); ?>?</P>
</BODY></HTML>
When the client requests this page, the Web server processes it. Means going through the page from
top to bottom, looking for PHP sections, which will try to solve them. The parser will check all marked
variables (with a $ sign) and try to add them to the PHP command (print() function). If everything goes
well, the preprocessor will return to a normal HTML page to the client browser. If you want to see the
source code from the client browser (select "Source" or "Page Source" from the View menu or right-click
on AOL), it will look like:
<HTML>
<HEAD><TITLE>A greeting</TITLE></HEAD>
<BODY>
<P>Hi, Ms. Day. May I call you Mata ? </P>
</BODY> </HTML>
The code above is the same as if we were to write an HTML program by hand. HTML
Embedding with PHP has several consequences:
• PHP can be quickly added to code generated by a WYSIWYG editor.
• Every line of HTML does not need to be rewritten into the programming language.
4. PHP runs on multiple platforms
PHP that is integrated in HTML documents can be accessed by all browsers on all existing platforms. In
other words, applications built with PHP are universally applicable. PHP can be run under UNIX and
Windows operating systems. Most HTTP servers run on one of these two operating system classes. PHP
is compatible with the top 3 Web Servers: Apache HTTP Server for UNIX and Windows, Microsoft
Internet Information Server and Netscape Enterprise Server (iPlanet Server). PHP also works on some
lesser known Servers including Alex Belits's fhttpd, Microsoft's Personal Web Server, AOLServer and
Omnicentrix's Omniserver Application Server. PHP is not supported on the Macintosh platform.
Table 1.2 Operating System and Web Server for PHP
Variable UNIX Windows
Operating system AIX, A/UX, BSDI, Digital UNIX/Tru64, FreeBSD, HP-UX, IRIX, Linux, NetBSD,
Openbsd, SCO, Unixware, Solaris, Sunos, Ultrix, Xenix Windows 95 Windows 98
Windows NT
Windows 2000
Web Server Apache, fhttpd, Netscape IIS, PWS, Netscape, Apache, Omni
Even though PHP doesn't run on Macintosh, BeOS or some other platforms, we can develop on this
client using this tool and then upload the PHP script to a UNIX or Windows Server.
5. PHP is not Tag based
PHP is a pure programming language, in PHP we can define functions by writing their names and
definitions.
6. PHP is stable
The word stable means 2 different things:
• Server does not require reboot.
• Software does not change radically & is compatible from release to release.
Both exist in PHP. Currently the Apache server is the most stable Web server with its reputation. While
not the fastest nor the easiest, the Apache HTTP server never seems to crash. And there's also no need
to reboot the server every time the settings are changed (at least on the UNIX side). PHP inherits this
state plus its robust implementation. Apache server with PHP outperforms IIS/Visual Studio and
Netscape Enterprise Server/Java for environmental stability. The PHP development team is trying to
improve such as adding a parser to run faster, communicating with other databases or adding better
session support. Very few functions were removed from previous PHP versions.
7. PHP is fast (PHP increases the speed of the script process)
PHP is fun to execute, especially when compiled as an Apache module on the UNIX side. Currently PHP 4
is faster for almost all CGI scripting uses. Although some CGI scripts are written in C, one of the lowest-
level languages and the fastest among many programming languages. Can be limited to the number of
concurrent processes running at one time. Other CGI scripting languages like Perl and Tcl are relatively
slow.
Most Websites thrive on using CGI for reasons of reliability and security. When compiling, PHP becomes
part of the http daemon. Since there are no transfers to and from different application servers (as in
ColdFusion) requests can be fulfilled more efficiently. PHP is at least as fast as ASP on many applications.
8. PHP is open source
Apart from the cost advantage, open source software also has the consequence that the complete
source code of the software must be included in its distribution.
Table 1.3 Source/Fee . Spectrum
Fee Structure Closed Source Controlled Source Open Source
Fee for all usage Allaire ColdFusion - -
Charges for multiple uses Corel WordPerfect Sun Java MySQL
No fee Microsoft IE Sun Star Office GPLed Software
9. PHP works well with other applications
PHP makes it easy to communicate with other programs and protocols. The PHP development team
seems to agree to provide maximum flexibility for a large number of users. Database connectivity is
quite strong with native-driver support for about 15 of the most popular databases plus ODBC. 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
work with open source projects such as PHP.
10. PHP is popular and growing
PHP became one of the most popular choices for two development periods (Web plus data). Since the
website is popular, PHP is expected to achieve rapid growth in a large number of users. While it's a bit
more difficult to get a company profile, PHP is in a relatively strong position for a product of its kind.
Microsoft Active Server Pages technology is used by 12% of Web Servers, ColdFusion is implemented in
about 4% of domains. PHP is used by 12% of all Web Servers as evidenced by most of the samples. ASP
and ColdFusion PHP have an advantage over their competitors in the development category.
11. PHP Community
PHP is jointly developed and supported by a worldwide user community. The main advantage of new
users is free and unlimited technical support. The people on the mailing list are willing to answer
questions and there is help debug A real support for PHP users. The PHP community members look at
the program and tell it what's wrong and even help design an application.
2.1.5 PHP Capabilities
In CGI applications (Common Gateway Interface a program that can receive input from the browser,
process it and then send back the output), which is programmed with Perl or C, then with PHP we will
get conveniences. For example, data entered in an html form is automatically variable and can be used
directly, so there is no need to parse what is called a querystring.
PHP3 Capabilities and Advantages:
• Accessing GIF files with PHP
PHP is not limited to just generating HTML page output. PHP can also be used to generate GIF image
files or even to generate more GIF image files that stream from the server to the browser.
• File Upload
PHP is capable of accepting uploaded files from any RFC-1867 compliant browser. This capability allows
users to upload text or binary files
• HTTP Cookies
PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data on the browser so
that we can track or identify the user.
• Connection to Database
PHP supports multiple databases in native mode and via ODBC.
• HTTP Authentication.
The HTTP Authentication advantage in PHP is only available if PHP is running as an Apache Web Server
module.
• Regular Expressions
Regular Expressions are used for complex string manipulation in PHP
• Error handling
All PHP expressions can be called with the prefix '@' which will turn off error reporting for that
expression.
2.2 Creating web programs with PHP
In the world of internet-based information, all kinds of information contained in it are made using a
technology called HTML, but because the function of HTML itself is only to display information or in
other words only display results in the form of ordinary writing, then comes technology that can reduce
the rigidity of HTML, which is called server side scripting and client side scripting, each of which has
advantages, for example, javascript which is the client side can perform writing animation techniques on
HTML pages, and PHP which is the server side can perform connectivity on the HTML page. database
where it can't be done using just plain HTML syntax.
2.2.1 PHP writing syntax
PHP code is written between the following signs:
<?php …


?> <? …


?> <% …


%> <script> …


</script>
If you create PHP code and plan to distribute it to other parties/people, then try to use the <?php … ?>
syntax. This is due to the use of code that uses <? ?> sometimes can't run on certain servers.
a. Saving PHP Files
If you have PHP code embedded in HTML in a file and want the web server to be able to run it, then the
file must be saved in the .php extension. If you save it with the .html or htm extension, then the PHP
code will not be processed and will be displayed in a web browser as is (in the form of codes).
Example:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

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

Will produce output:


Integer_10 : 1000
Integer_8 : -512
Integer_16 : 4096
Integer PHP is the same as type long in C, depending on the word size of the computer machine, it is
difficult to answer the exact range for this type. On most platforms the range is:
231 – 1 or (2,147,483,647) to –(231 – 1) or (-2,147,483,647)
b. Double
Is floating point like:
$first_double = 123,456;
$second_double = 0.456;
$even_double = 2.0;
Integers and doubles are stored in different formats and the result of the expression:
$five = $even_double + 3;
Will be a double, not an integer, even if it prints '5'. As default double prints with the minimum number
of spaces needed, for example
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few<BR>");
Will produce output:
2.28888 + 2.21112 = 4.5
The double format is –XY where – is specified optionally as negative and X and Y as digits between 0-9
$small_positive = 0.12345;
$small_negative = -.12345;
$even_double = 200000;
$still_doube = 2;
Double is specified in scientific notation by adding the letter e, for example 2.2e-3 will equal 2.2_10-3.
$small_positive = 5.5e-3;
print("small_positive is $small_positive<BR>");
$large_positive = 2.8e+16;
print("large_positive is $large_positive<BR>");
$small_negative = -2222e-10;
print("small_ negative is $small_ negative <BR>");
$large_negative = -0.00189e6;
print("large_negative is $large_negative <BR>");
Will produce output:
small_positive is 0.0055
large_positive is 2.8E+16
small_negative is –2.222E-07
large_negative is –1890
c. Boolean
Is the value true or false, used as a control such as to test an if statement. Boolean "truth" values can be
combined using logical operators to create more complete boolean expressions.
PHP provides a pair of constants in particular for use as Booleans: TRUE and FALSE. Rules for
determining the "truth" of a non-existent value of type boolean:
1.If value is a number, false if equal to zero and otherwise true
2.If value is string, false if string contains empty character or string “0” otherwise true
3. If the value is a composite data type (array or object) false if it does not contain a value other than
true
Example :
Each of the following variables will have a Truth value embedded in their name, used in a boolean
context
$true_num = 3 + 0.14159;
$true_str = "tried and true"
$true_array[49] = "an array element";
$false_num = 999 – 999;
$false_str = " "; // empty string character

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.2.3 Variables in PHP


1. Variable Range
The range of a variable is dependent on where the variable is defined. In general, all PHP variables only
have a range. Every variable used in a function, by default the range is local. As an example :
$a = 1; /*global reach*/
Function try() {
echo $a; /*refer to local range variable*/
}
try();
The script above doesn't output anything, because the $a in the Try function refers to the local $a which
doesn't have any value. This is in contrast to the C language where every global variable becomes visible
to all functions, unless defined as local. In PHP, global variables must be declared as global inside a
function if they are to be used in the function. Example :
$a = 1;
$b = 2;
function count() {
Global $a, $b;
$b = $a + $b; }
count();
echo $b;
The script above will output "3". By declaring $a and $b as global inside the function. The second way to
access a variable as a global reference is to use the $GLOBAL definition. The previous example can also
be written as:
$a = 1;
$b = 2;
function count()
{
$GLOBALS[“b”] = $GLOBALS[“a”] + $GLOBALS[“b”];
}
count();
echo $b;
$GLOBALS array is an array association where key is the name of the global variable. Another important
thing about the range is the "static" variable. A variable exists only in the local range of a function, and
its value will be retained.
Function try() {
$a = 0;
echo $a;
$a++; }
In the above function the value of $a returns to 0 for each call. This means that the value of $a will be
lost as soon as the program exits the function. The following example uses a static variable. Each time
the try() function is called the value of $a in the previous call.
Function try() {
Static $a = 0;
echo $a;
$a++; }

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)

4. Knowing the Type of a Variable


Since PHP determines the type of a variable according to the context in which it is used, the following
function can be used to check the type
on a variable gettype(), is_long(), is_double(), is_string(), is_array() and is_object.
variable.php
<h1>integer</h1>
<?
$a = 1234; # decimal number
$b = -123; # negative numbers
$c = 0123; # decimal octal number (equal to 83 decimal)
$d = 0×12; #hex decimal number (equal to 18 decimal)
echo "A=$a, b=$b, c(decimal)=$c, <br>
Value d(decimal)=$d <br>”;
?>
<h1>floating points</h1>
<?
$a = 1,234;
$b = 1.2e3;
echo "A = $a, b = $b <br>";
?>
If the string is enclosed in double quotes (".."), then the variables contained in the brackets will be
expanded, meaning that the contents of the variable will be removed. An example is the line containing
the echo( ) function in the previous exercise.
Table 4.1 Special characters in PHP3 (escape character)
Sequence Meaning Sequence Meaning
\n Newline (new line) \\ Backlash
\r Carriage \$ Double quote
\t Horizontal tab \" dollar sign
5. Casting Type
Type casting in PHP works like in C, the name of the desired type is written in brackets before the
variable to be cast.
$try = 10; //$try is an integer
$bar = (double) $try //$bar is a double
Allowed casts:
• (int), (integer) – cast to integer
• (real), (double), (float) – cast to double
• (string) – cast to string
• (array) – cast to array
• (object) – cast to object
6. Expression
Expression is "everything that has a price". For example constants and variables. When typing “$a=5”,
we enter the number '5' into $a. Actually '5' has the value 5, or in other words '5' is an expression with
the value 5 (in this case, '5' is an integer constant). After this assignment, the value of $a will also be 5 so
if you write $b=$a, the effect will be the same if you write $b = 5. In other words, $a is an expression
with a value of 5 too.
An example of a more complex expression is a function. For example, consider the example below:
Function foo ( )
{
returns 5;
}
Writing $c = foo ( ) is actually the same as writing $c = 5, because function is an expression with the
value of something it returns (return value ). Since foo ( ) returns 5, the value of the expression foo ( ) is
5. But usually the function doesn't return something static like that, but something that was calculated
beforehand.
A PHP script consists of a number of sequential commands. A command can be a value giver, function
calls, loops, conditional commands and blank lines. Each command ends with a semicolon (;). And
multiple commands can be grouped together in curly braces { and }. Note: each command ends with a
semicolon (;).
2.2.4 Control in PHP
1. Constant
PHP has a number of constants that have been defined and given the opportunity to create constants as
needed. The defined constants are _FILE_ (name of file being processed) _LINE_ (line number of file
being processed)
Example :
<?php
function report_error($file, $line, $message)
{ echo "An error occurred in the file $file bari $line: $message."; }
report_error(_FILE_,_LINE_,"An error has occurred!");
?>
Creation constants can be defined using the define() function. Example :
<?php
define("CONSTANT","Hello world.");
echo CONSTANT; //will print "Hello world."
?>

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

2.2.7 Operators in PHP


1 Arithmetic Operators
Arithmetic Operator Table
Example Name Results
$a + $b Sum Sum of $a and $b
$a – $b Subtraction The remainder of subtracting $a by $b
$a * $b Multiplication Multiply $a by $b
$a / $b Distribution The quotient of $a divided by $b
$a % $bModulus The remainder of the quotient of $a divided by $b
The division operator (“/”) returns an integer value (the result of an integer division) if both operands
are integers (or strings converted to integers). If one of the operands is a floating-point value, floating
point division is performed.
2. String Operators
There is only one string operator, namely the concatenation operator (“.”).
$a = "Hello";
$b = $a . “ World! "; // now $b = “ Hello World! "
Assignment Operators
The assignment operator is "=". This means that the operand on the left is filled with the value of the
expression on the right. The value of the assignment expression is the specified value. As a result, the
value of "$a = 3" is 3. Thus the following is true:
$a = ($b=4) + 5; // $a now contains 9, and $b contains 4.

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.

You might also like