Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

UNIT-I

Introduction to PHP:

 PHP is one of the most widely used server side scripting language for web
development. Popular websites like Facebook, Yahoo, Wikipedia etc, and our very
own Studytonight, are developed using PHP.
 PHP is so popular because it's very simple to learn, code and deploy on server, hence
it has been the first choice for beginners since decades.

Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

What is PHP?
PHP stands for Hypertext Pre-Processor. PHP is a scripting language used to develop static &
dynamic webpages & web applications. Here are a few important things you must know
about PHP

1. PHP is an interpreted language; hence it doesn’t need a compiler.


2. To run & execute PHP code, we need a web server on which PHP must be installed.
3. PHP is a server side scripting language, which means that PHP is executed on the
server & the result is sent to the browser in plain HTML.
4. PHP is open source & free.

Uses of PHP

 PHP is cross platform; this means you can deploy your application on a number of
different operating systems such as windows, Linux, Mac OS etc.
 PHP is open source and free.
 Short learning curve compared to other languages such as JSP, ASP etc.
 PHP has in built support for working hand in hand with MySQL; this doesn’t mean
you can’t use PHP with other database management systems.

"Hello World" Script in PHP

To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this −
Live Demo
<html>

<head>
<title>Hello World</title>
</head>

<body>
<?php echo "Hello, World!";?>
</body>

</html>

It will produce following result −


Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is
not present in the file sent from the server to your Web browser. All of the PHP present in
the Web page is processed and stripped from the page; the only thing returned to the
client from the Web server is pure HTML output.

Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back
to their own work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code

There are two types of comments

Single line- They are generally used for short explanations or notes relevant to the local
code. Here are the examples of single line comments.

<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment


?>

</body>
</html>

Multi line- They are generally used to provide pseudocode algorithms and more detailed
explanations when necessary. The multiline style of commenting is the same as in C. Here are the
example of multi lines comments.

<!DOCTYPE html>
<html>
<body>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

Variable Naming

Rules for naming a variable is −


 Variable names must begin with a letter or underscore character.
 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
There is no size limit for variables.

Variables
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
and the 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 advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
PHP has a total of eight data types which we use to construct our variables −
 Integers − are whole numbers, without a decimal point, like 4195.
 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'

Integers

They are whole numbers, without a decimal point, like 4195. They are the simplest type
.they correspond to simple whole numbers, both positive and negative. Integers can be
assigned to variables, or they can be used in expressions, like so −
$int_var = 12345;
$another_int = -12345 + 12345;

Doubles

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code −
Live Demo

<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;

print("$many + $many_2 = $few <br>");


?>

It produces the following browser output −


2.28888 + 2.21112 = 4.5

Boolean

They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so −
if (TRUE)
print("This will always print<br>");

else
print("This will never print<br>");

NULL

NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −

$my_var = null;

Strings

They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string

$string_1 = "This is a string in double quotes";


$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
Live Demo

<?php
$variable = "name";
$literally = 'My $variable will not print!';

print($literally);
print "<br>";

$literally = "My $variable will print!";


print($literally);
?>

This will produce following result −


My $variable will not print!
My name will print
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both

Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
 Local variables- A variable declared in a function is considered local; that is, it can
be referenced only in that function. Any assignment outside of that function will be
considered to be an entirely different variable from the one contained in the
function −
Live Demo

<?php
$x = 4;

function assignx () {
$x = 0;
print "\$x inside function is $x. <br />";
}

assignx();
print "\$x outside of function is $x. <br />";
?>

This will produce the following result −


$x inside function is 0.
$x outside of function is 4.

 Function parameters- Function parameters are declared after the function name
and inside parentheses. They are declared much like a typical variable would be −
Live Demo

<?php
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}

$retval = multiply (10);


Print "Return value is $retval\n";
?>

This will produce the following result −


Return value is 100

 Global variables- In contrast to local variables, a global variable can be accessed in


any part of the program. However, in order to be modified, a global variable must
be explicitly declared to be global in the function in which it is to be modified. This is
accomplished, conveniently enough, by placing the keyword GLOBAL in front of the
variable that should be recognized as global. Placing this keyword in front of an
already existing variable tells PHP to use the variable having that name. Consider an
example −
Live Demo

<?php
$somevar = 15;

function addit() {
GLOBAL $somevar;
$somevar++;

print "Somevar is $somevar";


}

addit();
?>

This will produce the following result −


Somevar is 16

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.

The example can be like this:

<?php
$x = 5;
$y = 10;

function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

They are two different things.

global is a keyword which tells that the variable is from a global scope. E.g. if you're
about to access a variable inside a function that's defined outside you'll need to use the
global keyword to make it accessible in the function.
$GLOBALS is a superglobal array. Superglobal simply means that it is available in all
scopes throughout a script without the need of using the global keyword

 Static variables- The final type of variable scoping that I discuss is known as static.
In contrast to the variables declared as function parameters, which are destroyed
on the function's exit, a static variable will not lose its value when the function exits
and will still hold that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the
variable name.
Live Demo

<?php
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}

keep_track();
keep_track();
keep_track();
?>

This will produce the following result −


1
2
3

Constant-
Constants are like variables except that once they are defined they cannot be changed or undefined.

A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant

To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive)

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false

Example

Create a constant with a case-sensitive name:

<?php
define("GREETING", "Welcome to PHP World!");
echo GREETING;
?>

Output

Welcome to PHP World!

Example

Create a constant with a case-insensitive name:

<?php
define("GREETING", "Welcome to PHP World!", true);
echo greeting;
?>

Output

Welcome to PHP World!

PHP Constant Arrays

In PHP, you can create an Array constant using the define() function.


Example

Create an Array constant:

<?php
define("cars", [
  "Alfa Romeo",
  "BMW",
  "Toyota"
]);
echo cars[0];
?>

Output

Alfa Romeo

Constants are Global

Constants are automatically global and can be used across the entire script.

Example

This example uses a constant inside a function, even if it is defined outside the function:

<?php
define("GREETING", "Welcome to PHP Programs!");

function myTest() {
  echo GREETING;
}
 
myTest();

?>

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
he following table lists the most important elements that can go inside $_SERVER:

Element/Code Description

$_SERVER['PHP_SELF'] Returns the filename of the currently executing script

$_SERVER['REQUEST_METHO Returns the request method used to access the page


D'] (such as POST)

$_SERVER['HTTP_HOST'] Returns the Host header from the current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not


reliable because not all user-agents support it)

$_SERVER['SCRIPT_NAME'] Returns the path of the current script

You might also like