0% found this document useful (0 votes)
245 views44 pages

WT Notes - PHP PDF

PHP is an open source, server-side scripting language used for web development. It is interpreted and object-oriented. PHP code can be easily embedded into HTML. Some key features include high performance, being open source, platform independence, and compatibility with servers like Apache. Variables, constants, data types, functions, and arrays are the basic elements of the PHP language. Functions allow reusable blocks of code and can take arguments. Arrays can hold multiple values in a single variable.

Uploaded by

Shashank
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
245 views44 pages

WT Notes - PHP PDF

PHP is an open source, server-side scripting language used for web development. It is interpreted and object-oriented. PHP code can be easily embedded into HTML. Some key features include high performance, being open source, platform independence, and compatibility with servers like Apache. Variables, constants, data types, functions, and arrays are the basic elements of the PHP language. Functions allow reusable blocks of code and can take arguments. Arrays can hold multiple values in a single variable.

Uploaded by

Shashank
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 44

PHP

PHP - Hypertext Preprocessor is an open source, interpreted and object-oriented scripting language i.e.
executed at server side. It is used to develop web applications (an application i.e. executed at server side
and generates dynamic page).

 PHP is a server side scripting language.

 PHP is an interpreted language, i.e. there is no need for compilation.

 PHP is an object-oriented language.

 PHP is an open-source scripting language.

 PHP is simple and easy to learn language.

PHP Features
 Performance: Script written in PHP executes much faster then those scripts written in other

languages such as JSP & ASP.

 Open Source Software: PHP source code is free available on the web, you can developed all

the version of PHP according to your requirement without paying any cost.

 Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating

system. A PHP application developed in one OS can be easily executed in other OS also.

 Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.

 Embedded: PHP code can be easily embedded within HTML tags and script.

PHP Example

File: hello.php

<!DOCTYPE>
<html>
<body>
<?php
echo "<h2>Hello by PHP</h2>";
?>
</body>
</html>
PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with it. But if you
want to use more than one parameters, it is required to use parenthesis.

The syntax of PHP echo is given below:

void echo ( string $arg1 [, string $... ] )


PHP echo statement can be used to print string, multi line strings, escaping characters, variable, array
etc.

<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>

PHP Print

Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument
list. Unlike echo, it always returns 1.

int print(string $arg)

<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
$msg="Hello print() in PHP";
print "Message is: $msg";
?>

PHP Variables

A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is
used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.

$variablename=value;
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>

Output:

string is: hello string


integer is: 200
float is: 44.6

PHP $ and $$ Variables

The $var (single dollar) is a normal variable with the name var that stores any value like string, integer,
float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>
Output:

abc
200
200

PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script. PHP
constants can be defined by 2 ways:

1. Using define() function


2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter or
underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()


Let's see the syntax of define() function in PHP.

define(name, value, case-insensitive)


1. name: specifies the constant name
2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.

<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>

PHP constant: const keyword


The const keyword defines constants at compile time. It is a language construct not a function.

It is bit faster than define().

It is always case sensitive.

<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
PHP Data Types
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types
that can be categorized further in 3 types:

1. Scalar Types
2. Compound Types
3. Special Types

PHP Data Types: Scalar Types


1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


1. array
2. object

PHP Data Types: Special Types


1. resource
2. NULL

PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list and
return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive

function also.

Syntax
function functionname(){
//code to be executed
}
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.

<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>

Output:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But we can do so
by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

Output:

Hello Call By Reference

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function if you don't specify any
argument, it will take the default argument.

<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

Output:

Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

Output:

Cube of 3 is: 27
PHP Variable Length Argument Function

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments
in function. To do so, you need to use 3 ellipses (dots) before the argument name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}

echo add(1, 2, 3, 4);


?>

Output:

10

Recursive Function
PHP also supports recursive function call like C/C++. In such case, we call current function within
function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may smash the
stack and may cause the termination of script.

<?php
function display($number) {
if($number<=5){
echo "$number ";
display($number+1);
}
}
display(1);
?>
Output: 12345
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of
similar type in a single variable.

Advantage
Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

PHP Array Types


There are 3 types of array in PHP.

1. Indexed Array

2. Associative Array

3. Multidimensional Array

Indexed Array
PHP indexed array is an array which is represented by an index number by default. All elements of array
are represented by an index number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric
array.

There are two ways to define indexed array:

1st way:

$season=array("summer","winter","spring","autumn");

2nd way:

$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output: Season are: summer, winter, spring and autumn

Traversing PHP Indexed Array


We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all the
elements of PHP array.

<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>

Output:

Size is: Big


Size is: Medium
Size is: Short

Associative Array
The associative arrays are very similar to numeric arrays in term of functionality but they are different in
terms of their index. Associative array will have their index as string so that you can establish a strong
association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice.
Instead, we could use the employees names as the keys in our associative array, and the value would be
their respective salary.

NOTE − Don't keep associative array inside double quote while printing otherwise it would not return
any value.

There are two ways to define associative array:

1st way:

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:

$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>

Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000

Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by row
* column.

$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Example

<html>
<body>

<?php
$marks = array(
"ram" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"pink" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for ram in physics : " ;
echo $marks['ram']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for pink in chemistry : " ;


echo $marks['pink']['chemistry'] . "<br />";
?>

</body>
</html>

This will produce the following result −

Marks for ram in physics : 35


Marks for qadir in maths : 32
Marks for pink in chemistry : 39
PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only 256-
character set and so that it does not offer native Unicode support. There are 4 ways to specify a string
literal in PHP.

1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string
in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use
double backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.

Example

<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>

Output:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.

<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>

Output:

Hello text multiple line text within double quoted string


Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string

Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after
this heredoc <<< operator, and immediately a new line is started to write any text. To close the
quotation, the string follows itself and then again that same identifier is provided. That closing identifier
must begin from the new line without any whitespace or tab.

Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and
underscores, and must start with an underscore or a non-digit character.

Example

<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Misthi, and I live in $city.
DEMO;
echo $str;
?>

Output:

Hello! My name is Misthi, and I live in Delhi.

We cannot use any whitespace or tab before and after the identifier and semicolon, which means
identifier must not be indented. The identifier must begin from the new line.
Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less
than symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e.g.
<<<'EXP'. Newdoc follows the same rule as heredocs.

The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas
heredoc is a double-quoted string.

<?php
$str = <<<'DEMO'
Welcome to bvrit.
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';

echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome to bvrit.
Learn with newdoc example.
Demo;
?>

Output:

Welcome to bvrit. Learn with newdoc example.


Welcome to bvrit. Learn with newdoc example.
PHP Form Handling
We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and
$_POST.

The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post
request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get request is visible on the URL
browser so it is not secured. You can send limited amount of data through get request.

Let's see a simple example to receive data from get request in PHP.

form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>

welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>

PHP Post Form


Post request is widely used to submit form that have large amount of data such as file upload, image
upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send
large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

form1.html
<form action="login.php" method="post">
<table>
<tr>
<td>Name:</td>
<td> <input type="text" name="name"/></td>
</tr>
<tr>
<td>Password:</td>
<td> <input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="login"/></td>
</tr>
</table>
</form>

login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable

echo "Welcome: $name, your password is: $password";


?>
Output:
$_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will
discuss $_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and
POST methods.

Try out following example by putting the source code in test.php script.

<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>

PHP Include File


PHP allows you to include file so that a page content can be reused many times. There are two ways to
include file in PHP.

1. include
2. require

Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or PHP script

in many PHP scripts.

include function: The include() function takes all the text in a specified file and copies it into the file
that uses the include function. If there is any problem in loading a file then the include() function
generates a warning but the script will continue execution.
menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>

include1.php

<?php include("menu.html"); ?>


<h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page

require function:
The require() function takes all the text in a specified file and copies it into the file that uses the include
function. If there is any problem in loading a file then the require() function generates a fatal error and
halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not continue
executing if files are missing or misnamed.

menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>

require1.php

<?php require("menu.html"); ?>


<h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page


PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
user.

Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.

In short, cookie can be created, sent and received at server end.

setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it
by $_COOKIE superglobal variable.

Syntax

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

setcookie("CookieName", "CookieValue");/* defining name and value only*/


setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 sec
onds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);

$_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.

Example

$value=$_COOKIE["CookieName"];//returns cookie value


Cookie Example
<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>

Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: Sonoo

Delete Cookie
If you set the expiration date in past, cookie will be deleted.

<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close
the website).

PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.

session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.

Syntax

bool session_start ( void )

Example

session_start();

$_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session
variable values.
Example: Store information

$_SESSION["user"] = "Sachin";

Example: Get information

echo $_SESSION["user"];

Session Example
session1.php

<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>

session2.php

<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>

Session Counter Example


sessioncounter.php

<?php
session_start();

if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>

Destroying Session
PHP session_destroy() function is used to destroy all session variables completely.

session3.php

<?php
session_start();
session_destroy();
?>

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.

Open File
PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts
two arguments: $filename and $mode. The $filename represents the file to be opended and $mode
represents the file mode for example read-only, read-write, write-only etc.

Syntax

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource
$context ]] )

Open File Mode

Mode Description

r Opens file in read-only mode. It places the file pointer at the beginning of the file.

r+ Opens file in read-write mode. It places the file pointer at the beginning of the
file.

w Opens file in write-only mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.

a Opens file in write-only mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.

a+ Opens file in read-write mode. It places the file pointer to the end of the file. If
file is not found, it creates a new file.

x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.

x+ It is same as x but it creates and opens file in read-write mode.

c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it
is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the
case with 'x'). The file pointer is positioned on the beginning of the file

c+ It is same as c but it opens file in read-write mode.

Example
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>

Read File
PHP provides various functions to read data from file. There are different functions that allow you to
read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

o fread()
o fgets()
o fgetc()

fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file resource
and file size.

Syntax
string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.


$length represents length of byte to be read.

Example
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file

echo "<pre>$contents</pre>";//printing data of file


fclose($fp);//close file
?>

Output

this is first line


this is another line
this is third line

fgets()
The PHP fgets() function is used to read single line from the file.

Syntax
string fgets ( resource $handle [, int $length ] )

Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>

Output

this is first line

fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc()
function, use !feof() function inside the while loop.

Syntax
string fgetc ( resource $handle )
Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>

Output

this is first line this is another line this is third line

Write File
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use
w, r+, w+, x, x+, c or c+ mode.

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

<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);

echo "File written successfully";


?>

Output: data.txt

welcome to php file write

Overwriting File
If you run the above code again, it will erase the previous data of the file and writes the new data. Let's
see the code that writes only new data into data.txt file.
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);

echo "File written successfully";


?>

Output: data.txt

hello

Append to File
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple example that
appends data into data.txt file.

Let's see the data of file first.

data.txt

welcome to php file write

Example

<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);

echo "File appended successfully";


?>

Output: data.txt

welcome to php file write this is additional text appending data

Delete File
In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only:
file name. It is similar to UNIX C unlink() function.
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted
successfully otherwise FALSE.

Syntax

bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

Example
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>

Output

File deleted successfully

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.

$_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 )

File Upload Example


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>

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!";
}
?>
Download File
PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a
file and writes it to the output buffer.

readfile() function
Syntax

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to true to
the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.

Download File Example: Text File


download1.php

<?php
$file_url = 'http://www.javatpoint.com/f.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>

Download File Example: Binary File


download2.php

<?php
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
Directory functions
The directory functions allow you to retrieve information about directories and their contents.

Function Description

chdir() Changes the current directory

chroot() Changes the root directory

closedir() Closes a directory handle

dir() Returns an instance of the Directory class

getcwd() Returns the current working directory

opendir() Opens a directory handle

readdir() Returns an entry from a directory handle

rewinddir() Resets a directory handle

scandir() Returns an array of files and directories of a specified directory

chdir()
<?php
// Get current directory
echo getcwd() . "<br>";

// Change directory
chdir("images");

// Get current directory


echo getcwd();
?>

Result:

/home/php
/home/php/images

chroot()

The chroot() function changes the root directory of the current process to directory, and changes the
current working directory to "/".
Note: This function requires root privileges, and is only available to GNU and BSD systems, and only
when using the CLI, CGI or Embed SAPI.

Note: This function is not implemented on Windows platforms.

<?php
// Change root directory
chroot("/path/to/chroot/");

// Get current directory


echo getcwd();
?>

Result:

closedir()

Example

Open a directory, read its contents, then close:

<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:

filename: cat.gif
filename: dog.gif
filename: horse.gif
dir()

The dir() function returns an instance of the Directory class. This function is used to read a directory,
which includes the following:

The given directory is opened

The two properties handle and path of dir() are available

Both handle and path properties have three methods: read(), rewind(), and close()

Syntax
dir(directory, context)
Example:

<?php
$d = dir(getcwd());

echo "Handle: " . $d->handle . "<br>";


echo "Path: " . $d->path . "<br>";

while (($file = $d->read()) !== false){


echo "filename: " . $file . "<br>";
}
$d->close();
?>

Result:

Handle: Resource id #2
Path: /etc/php
filename: .
filename: ..
filename: ajax.gif
filename: books.xml
filename: cdcatalog.xml
filename: cd_catalog.xml
filename: default.asp
filename: demo_array.asp
filename: demo_array.htm
...
...
...
getcwd()

The getcwd() function returns the current working directory.

<?php
echo getcwd();
?>

Result:

/home/php

opendir()

The opendir() function opens a directory handle.

<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:

filename: cat.gif
filename: dog.gif
filename: horse.gif

readdir()

The readdir() function returns the name of the next entry in a directory.

List all entries in the images directory, then close:

<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:

filename: cat.gif
filename: dog.gif
filename: horse.gif

rewinddir()

The rewinddir() function resets the directory handle created by opendir().

Example
Open a directory, list its files, reset directory handle, list its files once again, then close:

<?php

$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
// List files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
rewinddir();
// List once again files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}

?>

Result:

filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif
scandir()

The scandir() function returns an array of files and directories of the specified directory.

Example

List files and directories inside the images directory:

<?php

$dir = "/images/";

// Sort in ascending order - this is default


$a = scandir($dir);

// Sort in descending order


$b = scandir($dir,1);

print_r($a);
print_r($b);

?>

Result:

Array
(
[0] => .
[1] => ..
[2] => cat.gif
[3] => dog.gif
[4] => horse.gif
[5] => myimages
)
Array
(
[0] => myimages
[1] => horse.gif
[2] => dog.gif
[3] => cat.gif
[4] => ..
[5] => .
)
PHP MySQL
MySQL is an open-source relational database management system (RDBMS). It is the most popular
database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation.

 The data in a MySQL database are stored in tables which consists of columns and rows.

 MySQL is a database system that runs on a server.

 MySQL is ideal for both small and large applications.

 MySQL is very fast, reliable, and easy to use database system. It uses standard SQL

 MySQL compiles on a number of platforms.

How to connect PHP with MySQL Database?

PHP 5 and later can work with a MySQL database using:

1. MySQLi extension.

2. PDO (PHP Data Objects).

Difference Between MySQLi and PDO


 PDO works on 12 different database systems, whereas MySQLi works only with MySQL
databases.

 Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural API.

 If at some point of development phase, the user or the development team wants to change the
database then it is easy to that in PDO than MySQLi as PDO supports 12 different database
systems. He would have to only change the connection string and a few queries. With MySQLi,
he will need to rewrite the entire code including the queries.

MySQL Connect
Since PHP 5.5, mysql_connect() extension is deprecated we use mqsqli_connect() to connect.

PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if
connection is established or null.
Syntax

resource mysqli_connect (server, username, password)

PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection
is closed or false.

Syntax
bool mysqli_close(resource $resource_link)

Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>

Output:

Connected successfully

In MySQLi procedural approach instead of creating an instance we can use the mysqli_connect() function
available in PHP to establish a connection. This function takes the information as arguments such as host,
username, password, database name etc. This function returns MySQL link identifier on successful
connection or FALSE when failed to establish a connection.

Create Database
If the MySQL connection is established using procedural procedure then we can use the mysqli_query()
function of PHP to execute our query as described in the below syntax.

Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = 'CREATE Database mydb';

if(mysqli_query( $conn,$sql)){
echo "Database mydb created successfully.";
}else{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>

Output:

Connected successfully
Database mydb created successfully.

Create Table
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';

$conn = mysqli_connect($host, $user, $pass,$dbname);


if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = "create table emp(id INT AUTO_INCREMENT, name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL, primary key (id))";
if(mysqli_query($conn, $sql)){
echo "Table emp created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}

mysqli_close($conn);
?>

Output:

Connected successfully
Table emp created successfully

Insert Record
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';

$conn = mysqli_connect($host, $user, $pass,$dbname);


if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = 'INSERT INTO emp(name,salary) VALUES ("sonoo", 9000)';


if(mysqli_query($conn, $sql)){
echo "Record inserted successfully";
}else{
echo "Could not insert record: ". mysqli_error($conn);
}

mysqli_close($conn);
?>

Output:

Connected successfully
Record inserted successfully
Update Record
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';

$conn = mysqli_connect($host, $user, $pass, $dbname);


if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$id = 2;
$name = "Rahul";
$salary = 80000;
$sql = "update emp set name=\"$name\", salary=$salary where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
}else{
echo "Could not update record: ". mysqli_error($conn);
}

mysqli_close($conn);
?>

Output:

Connected successfully
Record updated successfully

Delete Record
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';

$conn = mysqli_connect($host, $user, $pass, $dbname);


if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$id=2;
$sql = "delete from emp where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully";
}else{
echo "Could not deleted record: ". mysqli_error($conn);
}

mysqli_close($conn);
?>

Output:

Connected successfully
Record deleted successfully

Select Query
There are two other MySQLi functions used in select query.

 mysqli_num_rows(mysqli_result $result): returns number of rows.

 mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the


array represents the column name of the table. It returns NULL if there are no more rows.

Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
$conn = mysqli_connect($host, $user, $pass, $dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = 'SELECT * FROM emp';


$retval=mysqli_query($conn, $sql);

if(mysqli_num_rows($retval) > 0){


while($row = mysqli_fetch_assoc($retval)){
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>

Output:

Connected successfully
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------

You might also like