SlideShare ist ein Scribd-Unternehmen logo
1 von 40
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is
the latest version of PHP, which was released on 28 November. Some important points need to
be noticed about PHP are as followed
 PHP stands for Hypertext Preprocessor.
 PHP is an interpreted language, i.e., there is no need for compilation.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language.
Why use PHP
PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.
 It handles dynamic content, database as well as session tracking for the website.
 You can create sessions in PHP.
 It can access cookies variable and also set cookies.
 It helps to encrypt the data and apply validation.
 PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
 Using PHP language, you can control the user to access some pages of your website.
 As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
 PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration form.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:
Performance:
PHP script is executed much faster than those scripts which are written in other languages such
as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions
of PHP according to your requirement without paying any cost. All its components are free to
download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at
the time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.
Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic websites easily.
But you must have the basic the knowledge of following technologies for web development as
well.
 HTML
 CSS
 JavaScript
 Ajax
 XML and JSON
 jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So,
learn these technologies for better implementation of PHP.
HTML - HTML is used to design static webpage.
CSS - CSS helps to make the webpage content more effective and attractive.
JavaScript - JavaScript is used to design an interactive website.
Mixing HTML and PHP
PHP code is normally mixed with HTML tags. PHP is an embedded language, meaning that you
can jump between raw HTML code and PHP without sacrificing readability.
In order to embed PHP code with HTML, the PHP must be set apart using PHP start and end
tags. The PHP tags tell the web server where the PHP code starts and ends. The PHP parser
recognizes three styles of start and end tags.
XML Style - TOP
<?php
PHP Code Block
?>
The first style of PHP tags is referred to as the XML tag style and is preferred most. This tag
style works with eXtensible Markup Language (XML) documents. This method should be used
especially when mixing PHP with XML or HTML documents. The examples in this tutorial use
this XML tag format.
Short Style - TOP
<?
PHP Code Block
?>
The short style is the simplest, however, it is not recommended since it could interfere with XML
document declarations.
Short Style - TOP
<script language="php">
PHP Code Block
<script>
This style is the longest and is similar to the tag style used with JavaScript. This style is preferred
when using an HTML editor that does not recognize the other tag styles. Since most new HTML
editors recognize the XML tag style, this style is not recommended.
NOTE: The most common style for denoting a PHP code block is the XML style. You will see it
most often when working with PHP. This is the style that will be used throughout this tutorial.
These script blocks can be placed anywhere in the HTML document, at the location at which the
script produces and displays its output. The following example HTML page illustrates the use of
the three script formats.
<!DOCTYPE html>
<html
<head>
<title>A Web Page</title>
</head>
<body>
<p>
<?php
echo "This is a basic PHP document";
?>
</p>
<p>
<?
print "PHP is fun!";
?>
</p>
<p>
<script language="php">
$myVar = "Hello World";
echo $myVar;
</script>
</p>
</body>
</html>
In the example three different styles of PHP blocks are included in the HTML document. The
first block uses the <?php ... ?> opening and closing tags. The code segment uses the echo
statement to print the text, "This is a basic PHP document", to the browser window.
The second block uses the <? ... ?> tags to mark the begining and end of the PHP code. This
section uses the print statement, an alias for echo, to display the text "Hello World" to the screen.
Finally, the third block uses the <script language="php"> ... </script> style to designate the
beginning and end of the PHP code.
Here the string "Hello World" is assigned to variable $myVar and the echo statement displays
the value of $myVar to the browser window.
This is a basic PHP page PHP is fun! Hello World
The example code above includes HTML tags, PHP tags, PHP statements, and whitespace.
When a PHP page is requested through a web browser by the user, PHP code is processed by the
PHP engine in the web server. Thus, when the PHP page is rendered in the browser window,
only the text between the opening and closing HTML or PHP tags is shown. None of the actual
PHP code is visible when viewing the source code from the browser window. This is because the
PHP interpreter runs through the script on the server and replaces the code with the output from
the script. Only the output is returned to the browser. This is one of the characteristics that make
PHP a server-side scripting language unlike JavaScript, which is a client-side scripting language.
Displaying Content
PHP includes two basic statements to output text to the web browser: echo and print. Both the
echo and print statements should be coded between the opening and closing PHP code block tags
and the PHP code block can be inserted anywhere in the HTML documents.
The echo and print statements appear in the following format:
 echo - used to output one or more strings.
 echo "Text to be displayed";
 print - used to output a string. In some cases the print statement offers greater
functionality than the echo statement. These will be discussed in later sections. For now
print can be considered an alias for echo.
 print "Text to be displayed";
The following examples demonstrate the use and placement of the echo and print commands in
an HTML document.
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<body>
<p>
<?php
echo "This Is a basic PHP document";
?>
</p>
</html>
In most cases, it is necessary to display entire paragraphs in the browser window or create line
breaks when displaying content. By default, the echo and print statements do not create
automatic line breaks. With both the echo and print statements, it is necessary to use a <p> or
<br> tag to create paragraphs or line breaks. Whitespaces and new line characters that are created
in the HTML editor by using carriage returns, spaces, and tabs are ignored by the PHP engine.
In the example below, the HTML paragraph tag is included inside of the PHP echo statement. In
PHP, HTML tags (e.g., <p>>, <div>, <span>, and so on) can be used with the print and echo
statements to format output content. In these cases, the HTML tags should be surrounded by
double quotes ("") so that the PHP interpreter does not try to interpret the tags and consider them
as a part of the output string.
echo <p>This is paragraph 1.</p>;
echo <p> This Is paragraph 2.</p>;
Without the use of the HTML paragraph tag, the preceding echo statements would render the
content in the following format:
This is paragraph 1.This is paragraph 2.
By including the paragraph tags, the statements are displayed as two separate paragraphs.
This is paragraph 1.
This is paragraph 2.
Instruction Terminator
Each line of code in PHP must end with an instruction terminator also know as the semicolon (;).
The instruction terminator is used to distinguish one set of instructions from another.
Failure to include the instruction terminator causes the PHP interpreter to become confused and
display errors in the browser window. The following code segment shows a common instruction
terminator error:
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<body>
<p>
<?php
echo "This line will produce an error";
echo "The previous line does Not include an instruction terminator";
?>
</p>
</body>
</html>
In this example, the first echo statement is missing the instruction terminator. Because the PHP
interpreter cannot determine the end of the first echo statement and the beginning of the second,
an error occurs. Depending on the interpreter's Error Handling settings, an error will be displayed
or the browser simply displays a blank page.
The following is a typical error displayed when the instruction terminator is omitted:
Parse error: syntax error, unexpected T_PRINT in C:ApacheRoottest.php on line 11
As you can see, PHP error messages tend to be rather cryptic in nature. The omission of the
instruction terminator is common among developers new to PHP. Over time, it will become
common practice to check each line for an instruction terminator.
Commenting your Code
Comments are used in PHP to allow you to write notes to yourself during the development
process. Such comments may define the purpose of a code segment or to comment blocks of
code while testing scripts.
Comments are ignored by the PHP parser. PHP comments can be defined in one of the following
ways:
// - simple PHP comment
# - alternative simple PHP comment
/*...*/ - multi-line comment blocks.
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<body>
<p>
<?php
// This is a simple PHP comment
# This is a second simple PHP comment
/* This is a PHP multi-line
comment block. It can span as
many lines as necessary */
?>
</p>
</body>
</html>
PHP Variables, Operators and Data types
PHP is easy to learn compared to the other language like Java and ASP.NET.PHP has a quite
easy to parse and human-friendly syntax.In this tutorial, we will learn PHP programming
concepts such as Datatypes,variables, and Operators.
What is Data Types in PHP
Data Types data types are a core component of programming language.A Data type refers to the
type of data a variable can store.
PHP supports eight primitive types:
Four scalar types:
1. Boolean
Booleans were introduced for the first time in PHP 4. A Boolean value can be either true or false.
2. integer
Integers can be written in decimal, hexadecimal, and octal notation.
3. float
Floating-point numbers is also known as real numbers.
4. string
Strings are a sequence of characters in PHP.
Two compound types:
5. array
An array in PHP is a collection of key/value pairs.
6. object
And finally three special types:
7. resource
Resources is a special data type which represents a PHP resource such as a database query, an
open file, a database connection.
8. NULL
Null is a data type with only one possible value is the NULL value.
PHP is a loosely coupled language so you don’t need to define data types explicitly. PHP
determines the data types by data assigned to the variable. PHP implicitly supports the following
data types.PHP also allows you to cast the data type. This is known as explicit casting.In below
section, we have explained type casting with an example.
Now let’s first discuss variables in PHP.
What is Variable in PHP
Variables are the core of part for your code which makes your value flexible.Variables are used
for storing values, like text strings, numbers or arrays.
Variables are denoted by $ symbol followed by the variable’s name in PHP. .A variable is a
name of the value that stores data at run-time. The variable scope determines its visibility. A
global variable is accessible to all the scripts in an application. A local variable is only accessible
to the script that it was defined in.
Variables are used to store data and provide stored data when needed and to assign a value to a
variable in PHP is quite easy.To assign a value to a variable, use an equals sign (=).
Variable Naming Rules
1. All variable names must start with the dollar sign.
1
2
3
<?php echo $var_name; ?>
2. Names of variables are case sensitive this means $var_name is different from
$VAR_NAME.
1
2
3
$var_name != $VAR_NAME
3. All variables names must start with a letter follow other characters
e.g. $var_name
1. $1var_name is not a legal variable name.
4. Variable names must not contain any spaces
$var name is not a legal variable name. You can use an underscore in place of the space
e.g.$var_name.
Let’s now look at how PHP determines the data type depending on the attributes of the supplied
data
Example:
1
2
3
4
<?php
$str = "Hello World!"
$var = 3.14;
5
6
7
8
echo '$var: '.is_double($a)."<br>";
echo '$str."<br>";
?>
Variable Type Casting
To Perform arithmetic operations using variables,you require the variables to be of the same data
type.Type casting is converting a variable or value into the desired data type. This is very useful
when performing arithmetic operations that require variables to be of the same datatype.
Here is the example of Variable
1
2
3
4
5
6
7
8
<?php
$var1 = 3.14;
$var2 = 5;
$var1_cast = (int)$var1;
echo $var1 + $var2;
?>
Type casting in PHP is performed by the interpreter. PHP also allows you to cast the data type.
This is known as explicit casting.The var_dump function is used to determine the data type.
Here we use the same code used above in variable section to demonstrates the var_dump
function.
1
2
3
4
5
6
<?php
$var = 3.14;
var_dump($var);
?>
What is Constant?
A constant is an identifier (variable) for a simple value. The value cannot be changed during the
script.Suppose you are developing a program that uses the value of PI 3.14, you can use a
constant to store its value.
Let’s see the example of constant to assign value 3.14 to PI
1
2
3
define('PI',3.14); //creates a constant with a value of 3.14
Once you define PI as 3.14 and if you try to reassign value to constant,it will generate an error.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.
There are two built-in constants, TRUE and FALSE (case-insensitive), which represent the two
possible boolean values.
What is Operators?
PHP offers several types of Operators and we will learn here
Arithmetic operators
Arithmetic operators are used to performing arithmetic operations on numeric data. The
concatenate operator works on strings values too. PHP supports the following operators.
OPERATOR DESCRIPTION EXAMPLE RESULT
+ Addition x=2,x+2 4
– Subtraction x=2,5-x 3
* Multiplication x=4,x*5 20
/ Division 15/5,5/2 32.5
% Modulus(division remainder) 5%2,10%8 12
++ Increment x=5,x++ 6
— Decrement x=5,x– 4
Assignment Operators
Assignment operators are used to assigning values to variables. They can also be used together
with arithmetic operators.
Operator Name Description Example Output
OPERATOR EXAMPLE IS THE SAME AS
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= X%=y x=x%y
Comparison operators
Comparison operators are used to comparing values and data types.
OPERATOR DESCRIPTION EXAMPLE
== is equal to 5==8 return false
!= is not equal 5!=8 return true
<> is not equal 5<>8 return true
> is greater than 5>8 return false
< is less than 5<8 return true
>= is greater than orequal to 5>=8 return false
<= is less than or equal to 5<=8 return true
Logical operators
When working with logical operators, any number greater than or less than zero (0)evaluates to
true. Zero (0) evaluates to false.
OPERATOR DESCRIPTION EXAMPLE
&& and x=6,y=3(x < 10 && y > 1) return true
|| or x=6,y=3(x==5 || y==5) return false
! not x=6,y=3!(x==y) return true
PHP Variables
Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!,
the variable $x will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Think of variables as containers for storing data.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
ADVERTISEMENT
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
The following example will output the sum of two variables:
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
Note: You will learn more about the echo statement and how to output data to the screen in the
next chapter.
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically associates a data type to the variable, depending on its value. Since the data
types are not set in a strict sense, you can do things like adding a string to an integer without
causing an error.
In PHP 7, type declarations were added. This gives an option to specify the data type expected
when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on
a type mismatch.
PHP Variables Scope
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
 local
 global
 static
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example
Variable with global scope:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
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 above can be rewritten like this:
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
Note: The variable is still local to the function.
PHP Data Types
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
ADVERTISEMENT
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.
Let's assume we have a class named Car. A Car can have properties like model, color, etc. We
can define variables like $model, $color, and so on, to hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.
Example
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.
A common example of using the resource data type is a database call.
We will not talk about the resource type here, since it is an advanced topic.
PHP Strings
A string is a sequence of characters, like "Hello world!".
PHP String Functions
In this chapter we will look at some commonly used functions to manipulate strings.
strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
ADVERTISEMENT
strrev() - Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Tip: The first character position in a string is 0 (not 1).
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
Complete PHP String Reference
For a complete reference of all string functions, go to our complete PHP String Reference.
The PHP string reference contains description and example of use, for each function!
PHP Operators
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result Show it
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y
Result of raising $x to the $y'th
power
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.
Assignment Same as... Description Show it
x = y x = y
The left operand gets set to the value of the
expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
ADVERTISEMENT
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result Show it
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y,
and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y
Returns true if $x is not equal to
$y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>=
Greater than or
equal to
$x >= $y
Returns true if $x is greater than or
equal to $y
<= Less than or equal to $x <= $y
Returns true if $x is less than or
equal to $y
<=> Spaceship $x <=> $y
Returns an integer less than, equal
to, or greater than zero, depending
on if $x is less than, equal to, or
greater than $y. Introduced in PHP
7.
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name Description Show it
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result Show it
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y
True if either $x or $y is true, but
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP String Operators
PHP has two operators that are specially designed for strings.
Operator Name Example Result Show it
. Concatenation $txt1 . $txt2
Concatenation of $txt1
and $txt2
.=
Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
PHP Array Operators
The PHP array operators are used to compare arrays.
Operator Name Example Result
Show
it
+ Union $x + $y Union of $x and $y
== Equality $x == $y
Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y
Returns true if $x and $y have the same
key/value pairs in the same order and of
the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:
Operator Name Example Result
?: Ternary
$x = expr1 ?
expr2 : expr3
Returns the value of $x.
The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE
?? Null coalescing
$x = expr1 ??
expr2
Returns the value of $x.
The value of $x is expr1 if expr1
exists, and is not NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
Introduced in PHP 7
Unit II
Dynamic Web content with PHP
Web sites are generally more compelling and useful when content is dynamically controlled.
Learn the basics of generating dynamic content with this simple file-driven example in PHP and
lay the groundwork for creating a more sophisticated Web experience.
Today, Web sites strive to deliver the ultimate user experience. Beyond user-friendliness, good
service, and meaningful information, custom and dynamic content can improve the usefulness of
your site and enhance visitor functions, making users more likely to return in the future. In this
article, we’ll start with an overview of dynamic information. Then, we’ll explain how to use PHP
to create dynamic content within a Web page and look at a sample script that demonstrates the
process.
Dynamic information theory
According to Merriam-Webster Online, dynamic means “marked by usually continuous and
productive activity or change.” So when we talk about dynamic data, we mean that the
information to be sent to the client as a Web page is a variable compilation of source data. This
contrasts with static Web pages, which are made up of content that is not dependent on variable
input and that are generally parsed directly to the user. There are three main types of dynamic
information on the Web:
 Dynamic data—Variables within a Web page are generated.
 Dynamic Web pages—An entire Web page is generated.
 Dynamic content—Portions of a Web page are generated.
The more granular control you want to have, as with dynamic data, the more complicated the
data handling will be. And the greater the scope of the information you want to generate, as with
dynamic Web pages, the more complicated the logic will be. Dynamic content is a happy
medium between the two and gives us an opportunity to look at two very useful PHP functions,
include() and require().
Remember, the more cranking you have to do on the back end, the bigger the performance hit
your site will experience. Fortunately, PHP does a good job of streamlining the preprocessing
time, so I try to use PHP’s functions as much as possible when dealing with dynamic content and
data.
Data sources and PHP functions
All dynamic content has one thing in common: It comes from a data source outside the
originating page. Figure A lists some common data sources and the PHP functions that handle
them.
Figure A
Data
source
PHP functions Comments
User $HTTP_POST_VARS
$HTTP_GET_VARS
These functions handle
data that is entered
directly by the user via a
Web form.
Database
(local or
remote)
<dbtype>_connect()
<dbtype>_pconnect()
<dbtype>_close()
<dbtype>_<function>()
example:
mysql_fetch_array()
These are just a few of
PHP’s many database
functions, which are
written specifically for
each database. You can
find a complete list of
these in the PHP Manual
Function Reference.
Remote
file
fopen(), fclose()
fgets(), fputs()
These functions handle
data in a file on a remote
server, which is
accessible via FTP.
Local
file
include(), require()
fopen(), fclose()
These functions handle
data in a file on the same
server, such as a
configuration file.
Common data sources and PHP functions to handle them
In the article “Tutorial: Getting started with PHP,” we looked at a sample script that asked users
to enter their favorite number. Based on the results, we displayed a message. That is a simple
example of user-driven dynamic content. The results from a Web form are used to determine
what content to show. A more sophisticated example would be a “click-stream” application that
is used to determine what ads to show a user based on which pages he or she has visited within
the site.
Once data is entered, by a user or otherwise, it is stored in a database and then recalled. If it is
used to determine what content to show, it is considered to be “database-driven dynamic
content.” We’ll take a closer look at this type of dynamic information in our next article.
For now, let’s look at an example of file-driven dynamic content using a simple script. We will
be using logic based on a configuration file to determine what body style and font to show on the
Web page. The chosen style will then be displayed when our Web page is requested. (A note
about the example include files: You really should use style sheets for functionality like that used
in the example.)
Sample script: Display.php
The Display.php script uses a separate configuration file containing variable values and several
include files that contain the variable portion of the HTML. While this may not seem very
dynamic, you could easily ask the user to create the configuration file with a Web form and use
logic to determine which configuration file to load, etc. (The techniques we discuss in
“Understanding functions and classes in PHP” will help you accomplish this.)
For our purposes here, we’ll skip that aspect of the process and keep it simple. Listing A shows
our main script, and the page you would call in your browser, Display.php. (PHP code appears in
bold.)
Listing A
<!– display.php
This is a Web page whose style is determined by a configuration file. –>
<html>
<head>
<title>Mood Page</title>
</head>
<?php
include(“displayconf.php”);
$required_file = $display.”.php”;
require $required_file;
?>
<br><br>
<center>This is the best “mood page” ever!</center>
</font>
</body>
</html>
This simple code must do three things:
 Use the PHP include() function to include and evaluate variables in the file
Displayconf.php.
 Create a variable representing the name of the file to be required. In our case, the variable
$display, which is defined in the Displayconf.php file, is evaluated and then appended
with .php. (This is our logic step.)
 Use the PHP require() function to display the content from the appropriate included file.
Note that in our example, the PHP require() and include() functions are completely
interchangeable. The main difference between these two functions is in how the target files are
handled. A require() statement will be replaced by the file it has called. That means that the
remote file is literally called only once, in the case of a loop. The include() function, on the other
hand, will be evaluated every time it is encountered. This means that in a loop, the file will be
accessed each time, and any variables that are set in the included file will be updated.
In the example, I have tried to give an indication of when it is appropriate to call each function.
In the case of the file Displayconf.php, it’s likely that values within it have changed. It is, after
all, a configuration file. Therefore, I have opted to use the include() function. On the other hand,
the file $required_file will most likely not change on the fly. If different body tags are required, a
new file will probably be created for inclusion, so I used the require() function.
Advanced users may want to review the PHP manual regarding the functions require_once() and
include_once() for even better control of file handling and configuration file variable
management.
Listing B shows our configuration file, Displayconf.php. (For the sake of simplicity, we’ll put all
the files in the same directory on our Web server.) All we do here is set the variable $display to
one of the optional values.
Listing B
<?php
# displayconf.php
# Configuration file for display.php
# ————————————————-
# Set the variable $display to one of the following:
# happy, sad, or generic
$display = “happy”;
?>
Finally, we need some content files—one for each option in the configuration file. Since the
content is static HTML, we don’t need the PHP ear tags in the file. When you use the include()
or require() functions in PHP, the affected file is escaped out of PHP at the beginning and back
into it at the end.
“Happy” file content (happy.php)
<body bgcolor=pink text=yellow>
<font size=”+5″>
“Sad” file content (sad.php)
<body bgcolor=blue text=white>
<font face=”arial, helvetica” size=”+5″>
“Generic” file content (generic.php)
<body bgcolor=white text=black>
<font face=”courier” size=”+5″>
When you hit the page, Display.php, the look and feel should change based on the value you
entered into the configuration file.
PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message and
attachment with message using PHP mail() function.
PHP mail() function
Syntax
1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, str
ing $additional_parameters ]] )
$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.
 user@example.com
 user@example.com, anotheruser@example.com
 User <user@example.com>
 User <user@example.com>, Another User <anotheruser@example.com>
$subject: represents subject of the mail.
$message: represents message of the mail to be sent.
Note: Each line of the message should be separated with a CRLF ( rn ) and lines should not
be larger than 70 characters.
$additional_headers (optional): specifies the additional headers such as From, CC, BCC etc.
Extra additional headers should also be separated with CRLF ( rn ).
PHP Mail Example
File: mailer.php
1. <?php
2. ini_set("sendmail_from", "sonoojaiswal@javatpoint.com");
3. $to = "sonoojaiswal1987@gmail.com";//change receiver address
4. $subject = "This is subject";
5. $message = "This is simple text message.";
6. $header = "From:sonoojaiswal@javatpoint.com rn";
7.
8. $result = mail ($to,$subject,$message,$header);
9.
10. if( $result == true ){
11. echo "Message sent successfully...";
12. }else{
13. echo "Sorry, unable to send mail...";
14. }
15. ?>
If you run this code on the live server, it will send an email to the specified receiver.
PHP Mail: Send HTML Message
To send HTML message, you need to mention Content-type text/html in the message header.
1. <?php
2. $to = "abc@example.com";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:xyz@example.com rn";
7. $header .= "MIME-Version: 1.0 rn";
8. $header .= "Content-type: text/html;charset=UTF-8 rn";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>
PHP Mail: Send Mail with Attachment
To send message with attachment, you need to mention many header information which is used
in the example given below.
1. <?php
2. $to = "abc@example.com";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert rn after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:xyz@example.comrn";
25. $header .= "MIME-Version: 1.0rn";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$numrn";
28. $header .= "--$numrn";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plainrn";
32. $header .= "Content-Transfer-Encoding:8bitrnn";
33. $header .= "$messagern";
34. $header .= "--$numrn";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name="test.txt"rn";
39. $header .= "Content-Transfer-Encoding:base64rn";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename="test.txt"rnn";
42. $header .= "$encoded_contentrn";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>
PHP File Handling
PHP File System allows us to create file, read file line by line, read file character by character,
write file, append file, delete file and close file.
PHP Filesystem Introduction
The filesystem functions allow you to access and manipulate the filesystem.
Installation
The filesystem functions are part of the PHP core. There is no installation needed to use these
functions.
Unix / Windows Compatibility
When specifying a path on Unix platforms, a forward slash (/) is used as directory separator.
On Windows platforms, both forward slash (/) and backslash () can be used.
Runtime Configuration
The behavior of the filesystem functions is affected by settings in php.ini.
Name Default Description Changeable
allow_url_fopen "1"
Allows fopen()-type functions to work
with URLs
PHP_INI_SYSTEM
allow_url_include "0" (available since PHP 5.2) PHP_INI_SYSTEM
user_agent NULL Defines the user agent for PHP to send PHP_INI_ALL
(available since PHP 4.3)
default_socket_timeout "60"
Sets the default timeout, in seconds, for
socket based streams (available since
PHP 4.3)
PHP_INI_ALL
from ""
Defines the email address to be used on
unauthenticated FTP connections and in
the From header for HTTP connections
when using ftp and http wrappers
PHP_INI_ALL
auto_detect_line_endings "0"
When set to "1", PHP will examine the
data read by fgets() and file() to see if it
is using Unix, MS-Dos or Mac line-
ending characters (available since PHP
4.3)
PHP_INI_ALL
sys_temp_dir "" (available since PHP 5.5) PHP_INI_SYSTEM
ADVERTISEMENT
PHP Filesystem Functions
Function Description
basename() Returns the filename component of a path
chgrp() Changes the file group
chmod() Changes the file mode
chown() Changes the file owner
clearstatcache() Clears the file status cache
copy() Copies a file
delete() See unlink()
dirname() Returns the directory name component of a path
disk_free_space() Returns the free space of a filesystem or disk
disk_total_space() Returns the total size of a filesystem or disk
diskfreespace() Alias of disk_free_space()
fclose() Closes an open file
feof() Checks if the "end-of-file" (EOF) has been reached for an open file
fflush() Flushes buffered output to an open file
fgetc() Returns a single character from an open file
fgetcsv() Returns a line from an open CSV file
fgets() Returns a line from an open file
fgetss()
Deprecated from PHP 7.3. Returns a line from an open file -
stripped from HTML and PHP tags
file() Reads a file into an array
file_exists() Checks whether or not a file or directory exists
file_get_contents() Reads a file into a string
file_put_contents() Writes data to a file
fileatime() Returns the last access time of a file
filectime() Returns the last change time of a file
filegroup() Returns the group ID of a file
fileinode() Returns the inode number of a file
filemtime() Returns the last modification time of a file
fileowner() Returns the user ID (owner) of a file
fileperms() Returns the file's permissions
filesize() Returns the file size
filetype() Returns the file type
flock() Locks or releases a file
fnmatch() Matches a filename or string against a specified pattern
fopen() Opens a file or URL
fpassthru()
Reads from the current position in a file - until EOF, and writes the
result to the output buffer
fputcsv() Formats a line as CSV and writes it to an open file
fputs() Alias of fwrite()
fread() Reads from an open file (binary-safe)
fscanf() Parses input from an open file according to a specified format
fseek() Seeks in an open file
fstat() Returns information about an open file
ftell() Returns the current position in an open file
ftruncate() Truncates an open file to a specified length
fwrite() Writes to an open file (binary-safe)
glob()
Returns an array of filenames / directories matching a specified
pattern
is_dir() Checks whether a file is a directory
is_executable() Checks whether a file is executable
is_file() Checks whether a file is a regular file
is_link() Checks whether a file is a link
is_readable() Checks whether a file is readable
is_uploaded_file() Checks whether a file was uploaded via HTTP POST
is_writable() Checks whether a file is writable
is_writeable() Alias of is_writable()
lchgrp() Changes the group ownership of a symbolic link
lchown() Changes the user ownership of a symbolic link
link() Creates a hard link
linkinfo() Returns information about a hard link
lstat() Returns information about a file or symbolic link
mkdir() Creates a directory
move_uploaded_file() Moves an uploaded file to a new location
parse_ini_file() Parses a configuration file
parse_ini_string() Parses a configuration string
pathinfo() Returns information about a file path
pclose() Closes a pipe opened by popen()
popen() Opens a pipe
readfile() Reads a file and writes it to the output buffer
readlink() Returns the target of a symbolic link
realpath() Returns the absolute pathname
realpath_cache_get() Returns realpath cache entries
realpath_cache_size() Returns realpath cache size
rename() Renames a file or directory
rewind() Rewinds a file pointer
rmdir() Removes an empty directory
set_file_buffer()
Alias of stream_set_write_buffer(). Sets the buffer size for write
operations on the given file
stat() Returns information about a file
symlink() Creates a symbolic link
tempnam() Creates a unique temporary file
tmpfile() Creates a unique temporary file
touch() Sets access and modification time of a file
umask() Changes file permissions for files
unlink() Deletes a file
PHP Open File - fopen()
The PHP fopen() function is used to open a file.
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, reso
urce $context ]] )
Example
1. <?php
2. $handle = fopen("c:folderfile.txt", "r");
3. ?>
Click me for more details...
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.
Syntax
1. ool fclose ( resource $handle )
Example
1. <?php
2. fclose($handle);
3. ?>
PHP Read File - fread()
The PHP fread() function is used to read the content of the file. It accepts two arguments:
resource and file size.
Syntax
1. string fread ( resource $handle , int $length )
Example
1. <?php
2. $filename = "c:myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>
Output
hello php file
Click me for more details...
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the string into file.
Syntax
int fwrite ( resource $handle , string $string [, int $length ] )
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output
File written successfully
Click me for more details...
PHP Delete File - unlink()
The PHP unlink() function is used to delete file.
Syntax
bool unlink ( string $filename [, resource $context ] )
Example
<?php
unlink('data.txt');
echo "File deleted successfully";
?>
PHP File Upload
PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both. Moreover, you can have
the full control over the file to be uploaded through PHP authentication and file operation
functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we
can get file name, file type, file size, temp file name and errors associated with file.
Here, we are assuming that file name is filename.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
bool move_uploaded_file ( string $filename , string $destination )
PHP File Upload Example
File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
File: uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
PHP File Upload
With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
 Make sure that the form uses method="post"
 The form also needs the following attribute: enctype="multipart/form-data". It specifies
which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
 The type="file" attribute of the <input> tag shows the input field as a file-select control,
with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
ADVERTISEMENT
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP script explained:
 $target_dir = "uploads/" - specifies the directory where the file is going to be placed
 $target_file specifies the path of the file to be uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message
is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Limit File Size
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types
gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Complete Upload File PHP Script
The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

Weitere ähnliche Inhalte

Ähnlich wie PHP.docx (20)

PHP
PHPPHP
PHP
 
Php1
Php1Php1
Php1
 
Php1
Php1Php1
Php1
 
Php1
Php1Php1
Php1
 
Php
PhpPhp
Php
 
Php unit i
Php unit i Php unit i
Php unit i
 
Php unit i
Php unit iPhp unit i
Php unit i
 
PhP Training Institute In Delhi
PhP Training Institute In DelhiPhP Training Institute In Delhi
PhP Training Institute In Delhi
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
PHP Training In Chandigarh.docx
PHP Training In Chandigarh.docxPHP Training In Chandigarh.docx
PHP Training In Chandigarh.docx
 
chapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdfchapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdf
 
Php tizag tutorial
Php tizag tutorialPhp tizag tutorial
Php tizag tutorial
 
PHP learning
PHP learningPHP learning
PHP learning
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
Php tizag tutorial
Php tizag tutorial Php tizag tutorial
Php tizag tutorial
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
Php tizag tutorial
Php tizag tutorialPhp tizag tutorial
Php tizag tutorial
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Kürzlich hochgeladen (20)

Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

PHP.docx

  • 1. PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an application that executes on the server and generates the dynamic page.). PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is the latest version of PHP, which was released on 28 November. Some important points need to be noticed about PHP are as followed  PHP stands for Hypertext Preprocessor.  PHP is an interpreted language, i.e., there is no need for compilation.  PHP is faster than other scripting languages, for example, ASP and JSP.  PHP is a server-side scripting language, which is used to manage the dynamic content of the website.  PHP can be embedded into HTML.  PHP is an object-oriented language.  PHP is an open-source scripting language.  PHP is simple and easy to learn language. Why use PHP PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL database.  It handles dynamic content, database as well as session tracking for the website.  You can create sessions in PHP.  It can access cookies variable and also set cookies.  It helps to encrypt the data and apply validation.  PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.  Using PHP language, you can control the user to access some pages of your website.
  • 2.  As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn.  PHP can handle the forms, such as - collect the data from users using forms, save it into the database, and return useful information to the user. For example - Registration form. PHP Features PHP is very popular language because of its simplicity and open source. There are some important features of PHP given below: Performance: PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster processing speed and better performance. Open Source: PHP source code and software are freely available on the web. You can develop all the versions of PHP according to your requirement without paying any cost. All its components are free to download and use. Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding with it. Embedded:
  • 3. PHP code can be easily embedded within HTML tags and script. Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also. Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc. Error Reporting - PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of execution based on the type of data it contains on its value. Web servers Support: PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc. Security: PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and malicious attacks. Control: Different programming languages require long script or code, whereas PHP can do the same work in a few lines of code. It has maximum control over the websites like you can make changes easily whenever you want. A Helpful PHP Community: It has a large community of developers who regularly updates documentation, tutorials, online help, and FAQs. Learning PHP from the communities is one of the significant benefits. Web Development PHP is widely used in web development nowadays. PHP can develop dynamic websites easily. But you must have the basic the knowledge of following technologies for web development as well.  HTML  CSS  JavaScript  Ajax  XML and JSON  jQuery Prerequisite Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So, learn these technologies for better implementation of PHP. HTML - HTML is used to design static webpage. CSS - CSS helps to make the webpage content more effective and attractive. JavaScript - JavaScript is used to design an interactive website. Mixing HTML and PHP PHP code is normally mixed with HTML tags. PHP is an embedded language, meaning that you can jump between raw HTML code and PHP without sacrificing readability.
  • 4. In order to embed PHP code with HTML, the PHP must be set apart using PHP start and end tags. The PHP tags tell the web server where the PHP code starts and ends. The PHP parser recognizes three styles of start and end tags. XML Style - TOP <?php PHP Code Block ?> The first style of PHP tags is referred to as the XML tag style and is preferred most. This tag style works with eXtensible Markup Language (XML) documents. This method should be used especially when mixing PHP with XML or HTML documents. The examples in this tutorial use this XML tag format. Short Style - TOP <? PHP Code Block ?> The short style is the simplest, however, it is not recommended since it could interfere with XML document declarations. Short Style - TOP <script language="php"> PHP Code Block <script> This style is the longest and is similar to the tag style used with JavaScript. This style is preferred when using an HTML editor that does not recognize the other tag styles. Since most new HTML editors recognize the XML tag style, this style is not recommended. NOTE: The most common style for denoting a PHP code block is the XML style. You will see it most often when working with PHP. This is the style that will be used throughout this tutorial. These script blocks can be placed anywhere in the HTML document, at the location at which the script produces and displays its output. The following example HTML page illustrates the use of the three script formats. <!DOCTYPE html> <html <head> <title>A Web Page</title> </head> <body> <p> <?php echo "This is a basic PHP document"; ?> </p> <p>
  • 5. <? print "PHP is fun!"; ?> </p> <p> <script language="php"> $myVar = "Hello World"; echo $myVar; </script> </p> </body> </html> In the example three different styles of PHP blocks are included in the HTML document. The first block uses the <?php ... ?> opening and closing tags. The code segment uses the echo statement to print the text, "This is a basic PHP document", to the browser window. The second block uses the <? ... ?> tags to mark the begining and end of the PHP code. This section uses the print statement, an alias for echo, to display the text "Hello World" to the screen. Finally, the third block uses the <script language="php"> ... </script> style to designate the beginning and end of the PHP code. Here the string "Hello World" is assigned to variable $myVar and the echo statement displays the value of $myVar to the browser window. This is a basic PHP page PHP is fun! Hello World The example code above includes HTML tags, PHP tags, PHP statements, and whitespace. When a PHP page is requested through a web browser by the user, PHP code is processed by the PHP engine in the web server. Thus, when the PHP page is rendered in the browser window, only the text between the opening and closing HTML or PHP tags is shown. None of the actual PHP code is visible when viewing the source code from the browser window. This is because the PHP interpreter runs through the script on the server and replaces the code with the output from the script. Only the output is returned to the browser. This is one of the characteristics that make PHP a server-side scripting language unlike JavaScript, which is a client-side scripting language. Displaying Content PHP includes two basic statements to output text to the web browser: echo and print. Both the echo and print statements should be coded between the opening and closing PHP code block tags and the PHP code block can be inserted anywhere in the HTML documents. The echo and print statements appear in the following format:  echo - used to output one or more strings.  echo "Text to be displayed";
  • 6.  print - used to output a string. In some cases the print statement offers greater functionality than the echo statement. These will be discussed in later sections. For now print can be considered an alias for echo.  print "Text to be displayed"; The following examples demonstrate the use and placement of the echo and print commands in an HTML document. <!DOCTYPE html> <html> <head> <title>A Web Page</title> </head> <body> <p> <?php echo "This Is a basic PHP document"; ?> </p> </html> In most cases, it is necessary to display entire paragraphs in the browser window or create line breaks when displaying content. By default, the echo and print statements do not create automatic line breaks. With both the echo and print statements, it is necessary to use a <p> or <br> tag to create paragraphs or line breaks. Whitespaces and new line characters that are created in the HTML editor by using carriage returns, spaces, and tabs are ignored by the PHP engine. In the example below, the HTML paragraph tag is included inside of the PHP echo statement. In PHP, HTML tags (e.g., <p>>, <div>, <span>, and so on) can be used with the print and echo statements to format output content. In these cases, the HTML tags should be surrounded by double quotes ("") so that the PHP interpreter does not try to interpret the tags and consider them as a part of the output string. echo <p>This is paragraph 1.</p>; echo <p> This Is paragraph 2.</p>; Without the use of the HTML paragraph tag, the preceding echo statements would render the content in the following format: This is paragraph 1.This is paragraph 2. By including the paragraph tags, the statements are displayed as two separate paragraphs. This is paragraph 1. This is paragraph 2. Instruction Terminator Each line of code in PHP must end with an instruction terminator also know as the semicolon (;). The instruction terminator is used to distinguish one set of instructions from another. Failure to include the instruction terminator causes the PHP interpreter to become confused and display errors in the browser window. The following code segment shows a common instruction terminator error:
  • 7. <!DOCTYPE html> <html> <head> <title>A Web Page</title> </head> <body> <p> <?php echo "This line will produce an error"; echo "The previous line does Not include an instruction terminator"; ?> </p> </body> </html> In this example, the first echo statement is missing the instruction terminator. Because the PHP interpreter cannot determine the end of the first echo statement and the beginning of the second, an error occurs. Depending on the interpreter's Error Handling settings, an error will be displayed or the browser simply displays a blank page. The following is a typical error displayed when the instruction terminator is omitted: Parse error: syntax error, unexpected T_PRINT in C:ApacheRoottest.php on line 11 As you can see, PHP error messages tend to be rather cryptic in nature. The omission of the instruction terminator is common among developers new to PHP. Over time, it will become common practice to check each line for an instruction terminator. Commenting your Code Comments are used in PHP to allow you to write notes to yourself during the development process. Such comments may define the purpose of a code segment or to comment blocks of code while testing scripts. Comments are ignored by the PHP parser. PHP comments can be defined in one of the following ways: // - simple PHP comment # - alternative simple PHP comment /*...*/ - multi-line comment blocks. <!DOCTYPE html> <html> <head> <title>A Web Page</title> </head> <body> <p>
  • 8. <?php // This is a simple PHP comment # This is a second simple PHP comment /* This is a PHP multi-line comment block. It can span as many lines as necessary */ ?> </p> </body> </html> PHP Variables, Operators and Data types PHP is easy to learn compared to the other language like Java and ASP.NET.PHP has a quite easy to parse and human-friendly syntax.In this tutorial, we will learn PHP programming concepts such as Datatypes,variables, and Operators. What is Data Types in PHP Data Types data types are a core component of programming language.A Data type refers to the type of data a variable can store. PHP supports eight primitive types: Four scalar types: 1. Boolean Booleans were introduced for the first time in PHP 4. A Boolean value can be either true or false. 2. integer Integers can be written in decimal, hexadecimal, and octal notation. 3. float Floating-point numbers is also known as real numbers. 4. string Strings are a sequence of characters in PHP. Two compound types: 5. array An array in PHP is a collection of key/value pairs. 6. object And finally three special types: 7. resource
  • 9. Resources is a special data type which represents a PHP resource such as a database query, an open file, a database connection. 8. NULL Null is a data type with only one possible value is the NULL value. PHP is a loosely coupled language so you don’t need to define data types explicitly. PHP determines the data types by data assigned to the variable. PHP implicitly supports the following data types.PHP also allows you to cast the data type. This is known as explicit casting.In below section, we have explained type casting with an example. Now let’s first discuss variables in PHP. What is Variable in PHP Variables are the core of part for your code which makes your value flexible.Variables are used for storing values, like text strings, numbers or arrays. Variables are denoted by $ symbol followed by the variable’s name in PHP. .A variable is a name of the value that stores data at run-time. The variable scope determines its visibility. A global variable is accessible to all the scripts in an application. A local variable is only accessible to the script that it was defined in. Variables are used to store data and provide stored data when needed and to assign a value to a variable in PHP is quite easy.To assign a value to a variable, use an equals sign (=). Variable Naming Rules 1. All variable names must start with the dollar sign. 1 2 3 <?php echo $var_name; ?> 2. Names of variables are case sensitive this means $var_name is different from $VAR_NAME. 1 2 3 $var_name != $VAR_NAME 3. All variables names must start with a letter follow other characters e.g. $var_name 1. $1var_name is not a legal variable name. 4. Variable names must not contain any spaces $var name is not a legal variable name. You can use an underscore in place of the space e.g.$var_name. Let’s now look at how PHP determines the data type depending on the attributes of the supplied data Example: 1 2 3 4 <?php $str = "Hello World!" $var = 3.14;
  • 10. 5 6 7 8 echo '$var: '.is_double($a)."<br>"; echo '$str."<br>"; ?> Variable Type Casting To Perform arithmetic operations using variables,you require the variables to be of the same data type.Type casting is converting a variable or value into the desired data type. This is very useful when performing arithmetic operations that require variables to be of the same datatype. Here is the example of Variable 1 2 3 4 5 6 7 8 <?php $var1 = 3.14; $var2 = 5; $var1_cast = (int)$var1; echo $var1 + $var2; ?> Type casting in PHP is performed by the interpreter. PHP also allows you to cast the data type. This is known as explicit casting.The var_dump function is used to determine the data type. Here we use the same code used above in variable section to demonstrates the var_dump function. 1 2 3 4 5 6 <?php $var = 3.14; var_dump($var); ?> What is Constant? A constant is an identifier (variable) for a simple value. The value cannot be changed during the script.Suppose you are developing a program that uses the value of PI 3.14, you can use a constant to store its value. Let’s see the example of constant to assign value 3.14 to PI 1 2 3 define('PI',3.14); //creates a constant with a value of 3.14 Once you define PI as 3.14 and if you try to reassign value to constant,it will generate an error.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. There are two built-in constants, TRUE and FALSE (case-insensitive), which represent the two possible boolean values. What is Operators?
  • 11. PHP offers several types of Operators and we will learn here Arithmetic operators Arithmetic operators are used to performing arithmetic operations on numeric data. The concatenate operator works on strings values too. PHP supports the following operators. OPERATOR DESCRIPTION EXAMPLE RESULT + Addition x=2,x+2 4 – Subtraction x=2,5-x 3 * Multiplication x=4,x*5 20 / Division 15/5,5/2 32.5 % Modulus(division remainder) 5%2,10%8 12 ++ Increment x=5,x++ 6 — Decrement x=5,x– 4 Assignment Operators Assignment operators are used to assigning values to variables. They can also be used together with arithmetic operators. Operator Name Description Example Output OPERATOR EXAMPLE IS THE SAME AS = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= X%=y x=x%y Comparison operators Comparison operators are used to comparing values and data types. OPERATOR DESCRIPTION EXAMPLE == is equal to 5==8 return false
  • 12. != is not equal 5!=8 return true <> is not equal 5<>8 return true > is greater than 5>8 return false < is less than 5<8 return true >= is greater than orequal to 5>=8 return false <= is less than or equal to 5<=8 return true Logical operators When working with logical operators, any number greater than or less than zero (0)evaluates to true. Zero (0) evaluates to false. OPERATOR DESCRIPTION EXAMPLE && and x=6,y=3(x < 10 && y > 1) return true || or x=6,y=3(x==5 || y==5) return false ! not x=6,y=3!(x==y) return true PHP Variables Variables are "containers" for storing information. Creating (Declaring) PHP Variables In PHP, a variable starts with the $ sign, followed by the name of the variable: Example <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?> After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5. Note: When you assign a text value to a variable, put quotes around the value. Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
  • 13. Think of variables as containers for storing data. PHP Variables A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for PHP variables:  A variable starts with the $ sign, followed by the name of the variable  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive ($age and $AGE are two different variables) Remember that PHP variable names are case-sensitive! ADVERTISEMENT Output Variables The PHP echo statement is often used to output data to the screen. The following example will show how to output text and a variable: Example <?php $txt = "W3Schools.com"; echo "I love $txt!"; ?> The following example will produce the same output as the example above: Example <?php $txt = "W3Schools.com"; echo "I love " . $txt . "!"; ?> The following example will output the sum of two variables: Example <?php $x = 5; $y = 4; echo $x + $y; ?> Note: You will learn more about the echo statement and how to output data to the screen in the next chapter. PHP is a Loosely Typed Language In the example above, notice that we did not have to tell PHP which data type the variable is.
  • 14. PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch. PHP Variables Scope PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes:  local  global  static Global and Local Scope A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: Example Variable with global scope: <?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: Example Variable with local scope: <?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest();
  • 15. // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?> You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. PHP The global Keyword The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function): Example <?php $x = 5; $y = 10; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // outputs 15 ?> 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 above can be rewritten like this: Example <?php $x = 5; $y = 10; function myTest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $y; // outputs 15 ?> PHP The static Keyword Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword when you first declare the variable:
  • 16. Example <?php function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); myTest(); ?> Then, each time the function is called, that variable will still have the information it contained from the last time the function was called. Note: The variable is still local to the function. PHP Data Types PHP Data Types Variables can store data of different types, and different data types can do different things. PHP supports the following data types:  String  Integer  Float (floating point numbers - also called double)  Boolean  Array  Object  NULL  Resource PHP String A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use single or double quotes: Example <?php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; ?> PHP Integer
  • 17. An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. Rules for integers:  An integer must have at least one digit  An integer must not have a decimal point  An integer can be either positive or negative  Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation In the following example $x is an integer. The PHP var_dump() function returns the data type and value: Example <?php $x = 5985; var_dump($x); ?> ADVERTISEMENT PHP Float A float (floating point number) is a number with a decimal point or a number in exponential form. In the following example $x is a float. The PHP var_dump() function returns the data type and value: Example <?php $x = 10.365; var_dump($x); ?> PHP Boolean A Boolean represents two possible states: TRUE or FALSE. $x = true; $y = false; Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial. PHP Array An array stores multiple values in one single variable. In the following example $cars is an array. The PHP var_dump() function returns the data type and value: Example <?php $cars = array("Volvo","BMW","Toyota");
  • 18. var_dump($cars); ?> You will learn a lot more about arrays in later chapters of this tutorial. PHP Object Classes and objects are the two main aspects of object-oriented programming. A class is a template for objects, and an object is an instance of a class. When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. Let's assume we have a class named Car. A Car can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties. When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Example <?php class Car { public $color; public $model; public function __construct($color, $model) { $this->color = $color; $this->model = $model; } public function message() { return "My car is a " . $this->color . " " . $this->model . "!"; } } $myCar = new Car("black", "Volvo"); echo $myCar -> message(); echo "<br>"; $myCar = new Car("red", "Toyota"); echo $myCar -> message(); ?> PHP NULL Value Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to NULL:
  • 19. Example <?php $x = "Hello world!"; $x = null; var_dump($x); ?> PHP Resource The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP. A common example of using the resource data type is a database call. We will not talk about the resource type here, since it is an advanced topic. PHP Strings A string is a sequence of characters, like "Hello world!". PHP String Functions In this chapter we will look at some commonly used functions to manipulate strings. strlen() - Return the Length of a String The PHP strlen() function returns the length of a string. Example Return the length of the string "Hello world!": <?php echo strlen("Hello world!"); // outputs 12 ?> str_word_count() - Count Words in a String The PHP str_word_count() function counts the number of words in a string. Example Count the number of word in the string "Hello world!": <?php echo str_word_count("Hello world!"); // outputs 2 ?> ADVERTISEMENT strrev() - Reverse a String The PHP strrev() function reverses a string. Example Reverse the string "Hello world!":
  • 20. <?php echo strrev("Hello world!"); // outputs !dlrow olleH ?> strpos() - Search For a Text Within a String The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE. Example Search for the text "world" in the string "Hello world!": <?php echo strpos("Hello world!", "world"); // outputs 6 ?> Tip: The first character position in a string is 0 (not 1). str_replace() - Replace Text Within a String The PHP str_replace() function replaces some characters with some other characters in a string. Example Replace the text "world" with "Dolly": <?php echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! ?> Complete PHP String Reference For a complete reference of all string functions, go to our complete PHP String Reference. The PHP string reference contains description and example of use, for each function! PHP Operators PHP Operators Operators are used to perform operations on variables and values. PHP divides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators  Conditional assignment operators PHP Arithmetic Operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
  • 21. Operator Name Example Result Show it + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y ** Exponentiation $x ** $y Result of raising $x to the $y'th power PHP Assignment Operators The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. Assignment Same as... Description Show it x = y x = y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus ADVERTISEMENT PHP Comparison Operators The PHP comparison operators are used to compare two values (number or string): Operator Name Example Result Show it == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y,
  • 22. and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y <> Not equal $x <> $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y <=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7. PHP Increment / Decrement Operators The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value. Operator Name Description Show it ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one PHP Logical Operators The PHP logical operators are used to combine conditional statements. Operator Name Example Result Show it and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both
  • 23. && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true PHP String Operators PHP has two operators that are specially designed for strings. Operator Name Example Result Show it . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1 PHP Array Operators The PHP array operators are used to compare arrays. Operator Name Example Result Show it + Union $x + $y Union of $x and $y == Equality $x == $y Returns true if $x and $y have the same key/value pairs === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types != Inequality $x != $y Returns true if $x is not equal to $y <> Inequality $x <> $y Returns true if $x is not equal to $y !== Non-identity $x !== $y Returns true if $x is not identical to $y PHP Conditional Assignment Operators The PHP conditional assignment operators are used to set a value depending on conditions: Operator Name Example Result ?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x. The value of $x is expr2 if expr1 = TRUE. The value of $x is expr3 if expr1 = FALSE
  • 24. ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2. Introduced in PHP 7 Unit II Dynamic Web content with PHP Web sites are generally more compelling and useful when content is dynamically controlled. Learn the basics of generating dynamic content with this simple file-driven example in PHP and lay the groundwork for creating a more sophisticated Web experience. Today, Web sites strive to deliver the ultimate user experience. Beyond user-friendliness, good service, and meaningful information, custom and dynamic content can improve the usefulness of your site and enhance visitor functions, making users more likely to return in the future. In this article, we’ll start with an overview of dynamic information. Then, we’ll explain how to use PHP to create dynamic content within a Web page and look at a sample script that demonstrates the process. Dynamic information theory According to Merriam-Webster Online, dynamic means “marked by usually continuous and productive activity or change.” So when we talk about dynamic data, we mean that the information to be sent to the client as a Web page is a variable compilation of source data. This contrasts with static Web pages, which are made up of content that is not dependent on variable input and that are generally parsed directly to the user. There are three main types of dynamic information on the Web:  Dynamic data—Variables within a Web page are generated.  Dynamic Web pages—An entire Web page is generated.  Dynamic content—Portions of a Web page are generated. The more granular control you want to have, as with dynamic data, the more complicated the data handling will be. And the greater the scope of the information you want to generate, as with dynamic Web pages, the more complicated the logic will be. Dynamic content is a happy medium between the two and gives us an opportunity to look at two very useful PHP functions, include() and require(). Remember, the more cranking you have to do on the back end, the bigger the performance hit your site will experience. Fortunately, PHP does a good job of streamlining the preprocessing time, so I try to use PHP’s functions as much as possible when dealing with dynamic content and data.
  • 25. Data sources and PHP functions All dynamic content has one thing in common: It comes from a data source outside the originating page. Figure A lists some common data sources and the PHP functions that handle them. Figure A Data source PHP functions Comments User $HTTP_POST_VARS $HTTP_GET_VARS These functions handle data that is entered directly by the user via a Web form. Database (local or remote) <dbtype>_connect() <dbtype>_pconnect() <dbtype>_close() <dbtype>_<function>() example: mysql_fetch_array() These are just a few of PHP’s many database functions, which are written specifically for each database. You can find a complete list of these in the PHP Manual Function Reference. Remote file fopen(), fclose() fgets(), fputs() These functions handle data in a file on a remote server, which is accessible via FTP. Local file include(), require() fopen(), fclose() These functions handle data in a file on the same server, such as a configuration file. Common data sources and PHP functions to handle them In the article “Tutorial: Getting started with PHP,” we looked at a sample script that asked users to enter their favorite number. Based on the results, we displayed a message. That is a simple example of user-driven dynamic content. The results from a Web form are used to determine what content to show. A more sophisticated example would be a “click-stream” application that is used to determine what ads to show a user based on which pages he or she has visited within the site. Once data is entered, by a user or otherwise, it is stored in a database and then recalled. If it is used to determine what content to show, it is considered to be “database-driven dynamic content.” We’ll take a closer look at this type of dynamic information in our next article. For now, let’s look at an example of file-driven dynamic content using a simple script. We will be using logic based on a configuration file to determine what body style and font to show on the Web page. The chosen style will then be displayed when our Web page is requested. (A note about the example include files: You really should use style sheets for functionality like that used in the example.) Sample script: Display.php The Display.php script uses a separate configuration file containing variable values and several
  • 26. include files that contain the variable portion of the HTML. While this may not seem very dynamic, you could easily ask the user to create the configuration file with a Web form and use logic to determine which configuration file to load, etc. (The techniques we discuss in “Understanding functions and classes in PHP” will help you accomplish this.) For our purposes here, we’ll skip that aspect of the process and keep it simple. Listing A shows our main script, and the page you would call in your browser, Display.php. (PHP code appears in bold.) Listing A <!– display.php This is a Web page whose style is determined by a configuration file. –> <html> <head> <title>Mood Page</title> </head> <?php include(“displayconf.php”); $required_file = $display.”.php”; require $required_file; ?> <br><br> <center>This is the best “mood page” ever!</center> </font> </body> </html> This simple code must do three things:  Use the PHP include() function to include and evaluate variables in the file Displayconf.php.  Create a variable representing the name of the file to be required. In our case, the variable $display, which is defined in the Displayconf.php file, is evaluated and then appended with .php. (This is our logic step.)  Use the PHP require() function to display the content from the appropriate included file. Note that in our example, the PHP require() and include() functions are completely interchangeable. The main difference between these two functions is in how the target files are handled. A require() statement will be replaced by the file it has called. That means that the remote file is literally called only once, in the case of a loop. The include() function, on the other hand, will be evaluated every time it is encountered. This means that in a loop, the file will be accessed each time, and any variables that are set in the included file will be updated. In the example, I have tried to give an indication of when it is appropriate to call each function. In the case of the file Displayconf.php, it’s likely that values within it have changed. It is, after all, a configuration file. Therefore, I have opted to use the include() function. On the other hand, the file $required_file will most likely not change on the fly. If different body tags are required, a new file will probably be created for inclusion, so I used the require() function.
  • 27. Advanced users may want to review the PHP manual regarding the functions require_once() and include_once() for even better control of file handling and configuration file variable management. Listing B shows our configuration file, Displayconf.php. (For the sake of simplicity, we’ll put all the files in the same directory on our Web server.) All we do here is set the variable $display to one of the optional values. Listing B <?php # displayconf.php # Configuration file for display.php # ————————————————- # Set the variable $display to one of the following: # happy, sad, or generic $display = “happy”; ?> Finally, we need some content files—one for each option in the configuration file. Since the content is static HTML, we don’t need the PHP ear tags in the file. When you use the include() or require() functions in PHP, the affected file is escaped out of PHP at the beginning and back into it at the end. “Happy” file content (happy.php) <body bgcolor=pink text=yellow> <font size=”+5″> “Sad” file content (sad.php) <body bgcolor=blue text=white> <font face=”arial, helvetica” size=”+5″> “Generic” file content (generic.php) <body bgcolor=white text=black> <font face=”courier” size=”+5″> When you hit the page, Display.php, the look and feel should change based on the value you entered into the configuration file. PHP Mail PHP mail() function is used to send email in PHP. You can send text message, html message and attachment with message using PHP mail() function. PHP mail() function Syntax 1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, str ing $additional_parameters ]] ) $to: specifies receiver or receivers of the mail. The receiver must be specified one of the following forms.  user@example.com  user@example.com, anotheruser@example.com  User <user@example.com>  User <user@example.com>, Another User <anotheruser@example.com> $subject: represents subject of the mail.
  • 28. $message: represents message of the mail to be sent. Note: Each line of the message should be separated with a CRLF ( rn ) and lines should not be larger than 70 characters. $additional_headers (optional): specifies the additional headers such as From, CC, BCC etc. Extra additional headers should also be separated with CRLF ( rn ). PHP Mail Example File: mailer.php 1. <?php 2. ini_set("sendmail_from", "sonoojaiswal@javatpoint.com"); 3. $to = "sonoojaiswal1987@gmail.com";//change receiver address 4. $subject = "This is subject"; 5. $message = "This is simple text message."; 6. $header = "From:sonoojaiswal@javatpoint.com rn"; 7. 8. $result = mail ($to,$subject,$message,$header); 9. 10. if( $result == true ){ 11. echo "Message sent successfully..."; 12. }else{ 13. echo "Sorry, unable to send mail..."; 14. } 15. ?> If you run this code on the live server, it will send an email to the specified receiver. PHP Mail: Send HTML Message To send HTML message, you need to mention Content-type text/html in the message header. 1. <?php 2. $to = "abc@example.com";//change receiver address 3. $subject = "This is subject"; 4. $message = "<h1>This is HTML heading</h1>"; 5.
  • 29. 6. $header = "From:xyz@example.com rn"; 7. $header .= "MIME-Version: 1.0 rn"; 8. $header .= "Content-type: text/html;charset=UTF-8 rn"; 9. 10. $result = mail ($to,$subject,$message,$header); 11. 12. if( $result == true ){ 13. echo "Message sent successfully..."; 14. }else{ 15. echo "Sorry, unable to send mail..."; 16. } 17. ?> PHP Mail: Send Mail with Attachment To send message with attachment, you need to mention many header information which is used in the example given below. 1. <?php 2. $to = "abc@example.com"; 3. $subject = "This is subject"; 4. $message = "This is a text message."; 5. # Open a file 6. $file = fopen("/tmp/test.txt", "r" );//change your file location 7. if( $file == false ) 8. { 9. echo "Error in opening file"; 10. exit(); 11. } 12. # Read the file into a variable 13. $size = filesize("/tmp/test.txt"); 14. $content = fread( $file, $size); 15. 16. # encode the data for safe transit 17. # and insert rn after every 76 chars. 18. $encoded_content = chunk_split( base64_encode($content)); 19. 20. # Get a random 32 bit number using time() as seed. 21. $num = md5( time() ); 22. 23. # Define the main headers. 24. $header = "From:xyz@example.comrn"; 25. $header .= "MIME-Version: 1.0rn"; 26. $header .= "Content-Type: multipart/mixed; "; 27. $header .= "boundary=$numrn"; 28. $header .= "--$numrn"; 29. 30. # Define the message section
  • 30. 31. $header .= "Content-Type: text/plainrn"; 32. $header .= "Content-Transfer-Encoding:8bitrnn"; 33. $header .= "$messagern"; 34. $header .= "--$numrn"; 35. 36. # Define the attachment section 37. $header .= "Content-Type: multipart/mixed; "; 38. $header .= "name="test.txt"rn"; 39. $header .= "Content-Transfer-Encoding:base64rn"; 40. $header .= "Content-Disposition:attachment; "; 41. $header .= "filename="test.txt"rnn"; 42. $header .= "$encoded_contentrn"; 43. $header .= "--$num--"; 44. 45. # Send email now 46. $result = mail ( $to, $subject, "", $header ); 47. if( $result == true ){ 48. echo "Message sent successfully..."; 49. }else{ 50. echo "Sorry, unable to send mail..."; 51. } 52. ?> PHP File Handling PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file. PHP Filesystem Introduction The filesystem functions allow you to access and manipulate the filesystem. Installation The filesystem functions are part of the PHP core. There is no installation needed to use these functions. Unix / Windows Compatibility When specifying a path on Unix platforms, a forward slash (/) is used as directory separator. On Windows platforms, both forward slash (/) and backslash () can be used. Runtime Configuration The behavior of the filesystem functions is affected by settings in php.ini. Name Default Description Changeable allow_url_fopen "1" Allows fopen()-type functions to work with URLs PHP_INI_SYSTEM allow_url_include "0" (available since PHP 5.2) PHP_INI_SYSTEM user_agent NULL Defines the user agent for PHP to send PHP_INI_ALL
  • 31. (available since PHP 4.3) default_socket_timeout "60" Sets the default timeout, in seconds, for socket based streams (available since PHP 4.3) PHP_INI_ALL from "" Defines the email address to be used on unauthenticated FTP connections and in the From header for HTTP connections when using ftp and http wrappers PHP_INI_ALL auto_detect_line_endings "0" When set to "1", PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Mac line- ending characters (available since PHP 4.3) PHP_INI_ALL sys_temp_dir "" (available since PHP 5.5) PHP_INI_SYSTEM ADVERTISEMENT PHP Filesystem Functions Function Description basename() Returns the filename component of a path chgrp() Changes the file group chmod() Changes the file mode chown() Changes the file owner clearstatcache() Clears the file status cache copy() Copies a file delete() See unlink() dirname() Returns the directory name component of a path disk_free_space() Returns the free space of a filesystem or disk disk_total_space() Returns the total size of a filesystem or disk diskfreespace() Alias of disk_free_space() fclose() Closes an open file feof() Checks if the "end-of-file" (EOF) has been reached for an open file fflush() Flushes buffered output to an open file fgetc() Returns a single character from an open file fgetcsv() Returns a line from an open CSV file fgets() Returns a line from an open file fgetss() Deprecated from PHP 7.3. Returns a line from an open file - stripped from HTML and PHP tags file() Reads a file into an array file_exists() Checks whether or not a file or directory exists
  • 32. file_get_contents() Reads a file into a string file_put_contents() Writes data to a file fileatime() Returns the last access time of a file filectime() Returns the last change time of a file filegroup() Returns the group ID of a file fileinode() Returns the inode number of a file filemtime() Returns the last modification time of a file fileowner() Returns the user ID (owner) of a file fileperms() Returns the file's permissions filesize() Returns the file size filetype() Returns the file type flock() Locks or releases a file fnmatch() Matches a filename or string against a specified pattern fopen() Opens a file or URL fpassthru() Reads from the current position in a file - until EOF, and writes the result to the output buffer fputcsv() Formats a line as CSV and writes it to an open file fputs() Alias of fwrite() fread() Reads from an open file (binary-safe) fscanf() Parses input from an open file according to a specified format fseek() Seeks in an open file fstat() Returns information about an open file ftell() Returns the current position in an open file ftruncate() Truncates an open file to a specified length fwrite() Writes to an open file (binary-safe) glob() Returns an array of filenames / directories matching a specified pattern is_dir() Checks whether a file is a directory is_executable() Checks whether a file is executable is_file() Checks whether a file is a regular file is_link() Checks whether a file is a link is_readable() Checks whether a file is readable is_uploaded_file() Checks whether a file was uploaded via HTTP POST is_writable() Checks whether a file is writable is_writeable() Alias of is_writable() lchgrp() Changes the group ownership of a symbolic link lchown() Changes the user ownership of a symbolic link link() Creates a hard link
  • 33. linkinfo() Returns information about a hard link lstat() Returns information about a file or symbolic link mkdir() Creates a directory move_uploaded_file() Moves an uploaded file to a new location parse_ini_file() Parses a configuration file parse_ini_string() Parses a configuration string pathinfo() Returns information about a file path pclose() Closes a pipe opened by popen() popen() Opens a pipe readfile() Reads a file and writes it to the output buffer readlink() Returns the target of a symbolic link realpath() Returns the absolute pathname realpath_cache_get() Returns realpath cache entries realpath_cache_size() Returns realpath cache size rename() Renames a file or directory rewind() Rewinds a file pointer rmdir() Removes an empty directory set_file_buffer() Alias of stream_set_write_buffer(). Sets the buffer size for write operations on the given file stat() Returns information about a file symlink() Creates a symbolic link tempnam() Creates a unique temporary file tmpfile() Creates a unique temporary file touch() Sets access and modification time of a file umask() Changes file permissions for files unlink() Deletes a file PHP Open File - fopen() The PHP fopen() function is used to open a file. Syntax 1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, reso urce $context ]] ) Example
  • 34. 1. <?php 2. $handle = fopen("c:folderfile.txt", "r"); 3. ?> Click me for more details... PHP Close File - fclose() The PHP fclose() function is used to close an open file pointer. Syntax 1. ool fclose ( resource $handle ) Example 1. <?php 2. fclose($handle); 3. ?> PHP Read File - fread() The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size. Syntax 1. string fread ( resource $handle , int $length ) Example 1. <?php 2. $filename = "c:myfile.txt"; 3. $handle = fopen($filename, "r");//open file in read mode 4. 5. $contents = fread($handle, filesize($filename));//read file 6. 7. echo $contents;//printing data of file 8. fclose($handle);//close file 9. ?> Output hello php file Click me for more details... PHP Write File - fwrite()
  • 35. The PHP fwrite() function is used to write content of the string into file. Syntax int fwrite ( resource $handle , string $string [, int $length ] ) Example 1. <?php 2. $fp = fopen('data.txt', 'w');//open file in write mode 3. fwrite($fp, 'hello '); 4. fwrite($fp, 'php file'); 5. fclose($fp); 6. 7. echo "File written successfully"; 8. ?> Output File written successfully Click me for more details... PHP Delete File - unlink() The PHP unlink() function is used to delete file. Syntax bool unlink ( string $filename [, resource $context ] ) Example <?php unlink('data.txt'); echo "File deleted successfully"; ?> PHP File Upload PHP allows you to upload single and multiple files through few lines of code only. PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full control over the file to be uploaded through PHP authentication and file operation functions. PHP $_FILES The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file. Here, we are assuming that file name is filename. $_FILES['filename']['name'] returns file name. $_FILES['filename']['type'] returns MIME type of the file. $_FILES['filename']['size'] returns size of the file (in bytes). $_FILES['filename']['tmp_name'] returns temporary file name of the file which was stored on the server.
  • 36. $_FILES['filename']['error'] returns error code associated with this file. move_uploaded_file() function The move_uploaded_file() function moves the uploaded file to a new location. The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request. Syntax bool move_uploaded_file ( string $filename , string $destination ) PHP File Upload Example File: uploadform.html <form action="uploader.php" method="post" enctype="multipart/form-data"> Select File: <input type="file" name="fileToUpload"/> <input type="submit" value="Upload Image" name="submit"/> </form> File: uploader.php <?php $target_path = "e:/"; $target_path = $target_path.basename( $_FILES['fileToUpload']['name']); if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) { echo "File uploaded successfully!"; } else{ echo "Sorry, file not uploaded, please try again!"; } ?> PHP File Upload With PHP, it is easy to upload files to the server. However, with ease comes danger, so always be careful when allowing file uploads! Configure The "php.ini" File First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On: file_uploads = On Create The HTML Form Next, create an HTML form that allow users to choose the image file they want to upload: <!DOCTYPE html> <html> <body>
  • 37. <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html> Some rules to follow for the HTML form above:  Make sure that the form uses method="post"  The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice:  The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next. ADVERTISEMENT Create The Upload File PHP Script The "upload.php" file contains the code for uploading a file: <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?> PHP script explained:  $target_dir = "uploads/" - specifies the directory where the file is going to be placed  $target_file specifies the path of the file to be uploaded
  • 38.  $uploadOk=1 is not used yet (will be used later)  $imageFileType holds the file extension of the file (in lower case)  Next, check if the image file is an actual image or a fake image Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there. Check if File Already Exists Now we can add some restrictions. First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0: // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } Limit File Size The file input field in our HTML form above is named "fileToUpload". Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0: // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } Limit File Type The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0: // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } Complete Upload File PHP Script The complete "upload.php" file now looks like this: <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
  • 39. // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  • 40. } else { echo "Sorry, there was an error uploading your file."; } } ?>