Unit I PHP (BCA)
Unit I PHP (BCA)
Introduction to PHP:
PHP Stands for Personal Home Page (earlier called, PHP) is an HTML-embedded, server-sidescripting
language designed for web development.
It is also used as a general purpose programming language.
It was created by Rasmus Lerdorf in 1994 and appeared in the market in 1995.
PHP started out as a small open source project that evolved as more and more people found out.
Rasmus Lerdorf released the first version of PHP way back in 1994.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to managedynamic
content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, Oracle, Sybase,Informix,
and Microsoft SQL Server.
The MySQL server, once started, executes even very complex queries with huge resultsets in
record-setting time.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP Syntax is C-Like.
Uses of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and closethem. The other
uses of PHP are:
PHP can handle forms, i.e. gather data from files, save data to a file, through email you cansend data,
return data to the user.
You add, delete, and modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
Features of PHP:
The main feature of php is open source scripting language so you can free download this and use. PHP isa server side
scripting language. It is widely used all over the world. It is faster than other scripting language. Some important
features of php are given below:
Simple:
It is very simple and easy to use, compare to other scripting language it is very simple and easy, this iswidely used all
over the world.
Interpreted:
It is an interpreted language, i.e. there is no need for compilation.
Open Source:
Open source means you no need to pay for use php, you can free download and use.
Faster: It is faster than other scripting language e.g. asp and jsp.
Platform Independent:
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.
Case Sensitive:
PHP is case sensitive scripting language at time of variable declaration. In PHP, all keywords (e.g. if, else,while, echo,
etc.), classes, functions, and user-defined functions are NOT case-sensitive.
Advantages of PHP :
Open source: It is developed and maintained by a large group of PHP developers, this will helpsin creating
a support community, abundant extension library.
Speed: It is relative fast since it uses much system resource.
Easy to use: It uses C like syntax, so for those who are familiar with C, it’s very easy for them topick up
and it is very easy to create website scripts.
Stable: Since it is maintained by many developers, so when bugs are found, it can be quicklyfixed.
Powerful library support: You can easily find functional modules you need such as PDF, Graphetc.
Built-in database connection modules: You can connect to database easily using PHP, since many
websites are data/content driven, so we will use database frequently, this will largely reduce the
development time of web apps.
Platform Independent: It can be run on many platforms, including Windows, Linux and Mac, it’seasy for
users to find hosting service providers.
Disadvantages of PHP:
Security: Since it is open sourced, so all people can see the source code, if there are bugs in thesource
code, it can be used by people to explore the weakness of PHP.
Not suitable for large applications: Hard to maintain since it is not very modular.
Weak type: Implicit conversion may surprise unwary programmers and lead to unexpected bugs. For
example, the strings “1000” and “1e3” compare equal because they are implicitly castto floating point
numbers.
Let’s jump straight in with a PHP script. To begin, open your favorite text editor. Like HTML documents,PHP files
are made up of plain text. You can create them with any text editor, and most popular HTML editors and
programming IDEs (integrated development environments) provide support for PHP.
Type in the example in Listing 4.1 and save the file to the document root of your web server, using aname something
like first.php.
Listing 4.1: A Simple PHP Script
<?php
echo “<h1>Hello Web!</h1>”;
?>
If you are not working directly on the machine that will be serving your PHP script, you need to use a File Transfer
Protocol (FTP) or Secure Copy (SCP) client to upload your saved document to the server. When the document is in
place on the server, you should be able to access it using your browser. If allhas gone well, you should see the
script’s output.
FIGURE 4.2
Success: the output from
first.php.
Beginning and Ending a Block of PHP Statements:
When writing PHP, you need to inform the PHP engine that you want it to execute your commands. If
you don’t do this, the code you write will be mistaken for HTML and will be output to the browser.
Youcan designate your code as PHP with special tags that mark the beginning and end of PHP code
blocks.
Single-line comments begin with two forward slashes (//)—the preferred style—or a single hash or pound
sign (#). The PHP engine ignores all text between these marks and either the end of the line orthe PHP
close tag:
// this is a comment this is another comment
Multiline comments begin with a forward slash followed by an asterisk (/*) and end with an
asteriskfollowed by a forward slash (*/):
/*
this is a
commentno
ne of this
will be parsed by the PHP engine
*/
PHP Variable:
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand
side andthe expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in
advancewhether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
The first five are simple types, and the next two (arrays and objects) are compound – the
compound types can package up other arbitrary values of arbitrary type, whereas the
simpletypes cannot.
Superglobal Variables:
In addition to global variables of your own creation, PHP has several predefined variables called
superglobals. These variables are always present, and their values are available to all your scripts.
Each of the following superglobals is actually an array of other variables:
$_GET contains any variables provided to a script through the GET method.
$_POST contains any variables provided to a script through the POST method.
$_SERVER contains information such as headers, file paths, and script locations.
$_ENV contains any variables provided to a script as part of the server environment.
Function Description
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters. String values must be enclosed either within single quotes or in double quotes. But both
are treated differently.
$company = "Javatpoint";
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
PHP Constants:
constant() function:
As indicated by the name, this function will return the value of the constant. This is useful
whenyou want to retrieve value of a constant, but you do not know its name, i.e., it is stored
in a variable or returned by a function.
constant() example
<?php
define("MIN
SIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Note: Only scalar data (boolean, integer, float and string) can be contained in constants.
// Valid constant
names define("ONE",
"first thing");
define("TWO2",
"second thing");
define("THREE_3",
"third thing")
// Invalid constant names define("2TWO", "second thing"); define(" THREE ", "third value");
PHP Operators:
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable. PHP Operators can be categorized in following forms:
o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
Arithmetic Operators:
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction,
etc. with numeric values.
% Modulus $a % $b Remainder of
Assignment Operators:
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".
Comparison Operators:
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
Operator Name Example Explanation
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators:
The string operators are used to perform the operation on strings. There are two string operators in PHP, which
are given below:
If you want to execute some code if a condition is true and another code if a condition is
false,use the if else statement.
Syntax:
if (condition)
code to be executed if condition
is true;else code to be executed
if condition is false; Example:
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwiseit will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice
weekend!";else echo
"Have a nice day!";
?>
</body>
</html>
If you want to execute some code if one of the several conditions is true, then use the
elseifstatement. Syntax:
if (condition)
code to be executed if condition
is true; elseif (condition)
code to be executed if condition
is true;else code to be executed
if condition is false;
Example:
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Havea nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice
day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice
weekend!"; elseif
($d=="Sun")
echo "Have a nice
Sunday!"; echo
"Have a nice
day!";
?>
</body>
</html>
The Switch Statement:-
If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of
if..elseif..else code. Syntax:
switch (expression)
{
case label1:
code to be executed if expression =
label1;break; case label2:
code to be executed if expression = label2;
break; default:
code to be executed
if expression is
different from
both label1 and
label2;
}
Example:
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon": echo "Today is
Monday"; break;
case "Tue": echo "Today
is Tuesday"; break;
case "Wed": echo "Today is
Wednesday"; break;
case "Thu": echo "Today is
Thursday"; break;
case "Fri": echo
"Today is Friday"; break;
case "Sat": echo "Today is
Saturday"; break;
case "Sun": echo "Today
is Sunday"; break;
default: echo "invalid day will be entered, try again";
}
?>
</body>
</html>
It will produce the
following result:
Today is Friday
Loops in PHP are used to execute the same block of code a specified number of times.
PHPsupports following four loop types.
for - loops through a block of code a specified number of times.
while - loops through a block of code if and as long as a specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long
as aspecial condition is true.
foreach - loops through a block of code for each element in an array.
?>
The while statement will execute a block of code if and as long as a test expression is
true. If thetest expression is true, then the code block will be executed.
After the code has executed the test expression will again be evaluated and the loop
willcontinue until the test expression is found to be false.
Syntax:
while (condition)
{
code to be executed;
}
Example:
<?php
$i=1;
//$n=10;
while($i<=5)
{
echo "The
Number=";
echo $i;
echo "<br>";
$i++;//$i=$i+1;
}
?>
The do...while loop statement:-
The do...while statement will execute a block of code at least once - it will then repeat the
loopas long as a condition is true.
Syntax:
do
{
code to be executed;
}while (condition);
Example:
<?php
$i=10; $n=50; do
{
echo $i;
echo " ";
$i++;
}while($i<=$n);
?>
Example:
<?php
$a = array( 1, 2,
3, 4, 5); foreach(
$a as $value )
{
echo "The Value is $value <br />";
}
?>
In PHP, the primary way to "break out" of a control structure is by using the break statement. This statement is
specifically designed to terminate the execution of the current loop or switch statement and resume execution at
the statement immediately following the terminated structure.
Here's how break functions in different scenarios:
1. Breaking out of Loops (for, foreach, while, do-while):
When break is encountered within a loop, the loop immediately terminates, and the program flow continues with
the code after the loop.
Code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
echo $i . " "; // This will print 0 1 2 3 4
}
echo "\nLoop ended.";
?>
2. Breaking out of switch statements:
The break statement is crucial within switch statements to prevent "fall-through," where code from
subsequent case blocks would execute if break were omitted.
Code
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "It's Monday!";
break;
case "Tuesday":
echo "It's Tuesday!";
break; // Prevents fall-through to Wednesday
case "Wednesday":
echo "It's Wednesday!";
break;
default:
echo "Unknown day.";
}
?>
if ($file) {
echo "File opened successfully!";
fclose($file); // Close the file
} else {
echo "Failed to open the file.";
}
?>
File Modes in PHP:
Files can be opened in any of the following modes:
"w" – Opens a file for writing only. If the file does not exist, then a new file is created, and if the file
already exists, then the file will be truncated (the contents of the file are erased).
"r" – File is open for reading only.
"a" – File is open for writing only. The file pointer points to the end of the file. Existing data in the file is
preserved.
"w+" – Opens file for reading and writing both. If the file does not exist, then a new file is created, and if
the file already exists, then the contents of the file are erased.
"r+" – File is open for reading and writing both.
"a+" – File is open for write/read. The file pointer points to the end of the file. Existing data in the file is
preserved. If the file is not there, then a new file is created.
"x" – New file is created for write only.
echo $content;
fclose($file);
?>
2. Reading a File Line by Line
You can use the fgets() function to read a file line by line.
<?php
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
}
?>
Writing to Files:
You can write to files using the fwrite() function. It writes data to an open file in the specified mode.
<?php
if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}
?>
Deleting Files
Use the unlink() function to delete the file in PHP.
<?php
if (file_exists("gfg.txt")) {
unlink("gfg.txt");
echo "File deleted successfully!";
} else {
echo "File does not exist.";
}
?>
unction Description
Locking Files:
File locking in PHP is primarily achieved using the flock() function. This function allows for the implementation of
a simple reader/writer model to manage concurrent access to files, which is crucial in multi-process or multi-user
environments to prevent data corruption.
How to use flock() for file locking:
Open the file: Before locking, the file must be opened using fopen(), which returns a file pointer.
Code
$fp = fopen("path/to/your/file.txt", "w+"); // Open for reading and writing
Acquire the lock: Use flock() with the appropriate lock type.
*LOCK_SH (Shared Lock): Allows multiple processes to read the file concurrently, but prevents exclusive locks
(writing).
*LOCK_EX (Exclusive Lock): Prevents any other process from acquiring a shared or exclusive lock, ideal for
writing.
*LOCK_NB (Non-Blocking): Can be combined with LOCK_SH or LOCK_EX to prevent the flock() call from blocking
if the lock cannot be immediately acquired.
Code
Release the lock: After completing file operations, release the lock using LOCK_UN.
Code
flock($fp, LOCK_UN); // Release the lock
Close the file: Close the file pointer using fclose(). Note that fclose() automatically releases any locks held by
the current process on that file.
Code
fclose($fp);