Why To Learn PHP?: Basic Tutorials

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

BASIC TUTORIALS

Topic Title #1: PHP Overview

The PHP Hypertext Preprocessor (PHP) is a programming language that allows web


developers to create dynamic content that interacts with databases. PHP is basically
used for developing web based software applications. This tutorial helps you to build
your base with PHP.

Why to Learn PHP?

PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.
PHP is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning PHP:
 PHP is a server side scripting language that is embedded in HTML. It is used to
manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
 It is integrated with a number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
 PHP is pleasingly zippy in its execution, especially when compiled as an Apache
module on the Unix side. The MySQL server, once started, executes even very
complex queries with huge result sets in record-setting time.
 PHP supports a large number of major protocols such as POP3, IMAP, and
LDAP. PHP4 added support for Java and distributed object architectures (COM
and CORBA), making n-tier development a possibility for the first time.
 PHP is forgiving: PHP language tries to be as forgiving as possible.
 PHP Syntax is C-Like.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

PHP Example

In this tutorial, you will get a lot of PHP examples to understand the topic well. You must
save the PHP file with a .php extension. Let’s see a simple PHP example.

File name: hello.php

<html>

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

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

</html>

Output:

Hello, World!

Applications of PHP

As mentioned before, PHP is one of the most widely used language over the web. I'm
going to list few of them here:
 PHP performs system functions, i.e. from files on a system it can create, open,
read, write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, through
email you can send data, return data to the user.
 You add, delete, modify elements within your database through PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.

Audience

This PHP tutorial is designed for PHP programmers who are completely unaware of
PHP concepts but they have basic understanding on computer programming.

Prerequisites

Before proceeding with this tutorial you should have at least basic understanding of
computer programming, Internet, Database, and MySQL etc is very helpful.

Topic Title #2: Install PHP

To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software
stack. It is available for all operating systems. There are many AMP options available in
the market that are given below:

 WAMP for Windows


 LAMP for Linux
 MAMP for Mac
 SAMP for Solaris
 FAMP for FreeBSD

XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go
for WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

Download and Install WAMP Server (https://www.wampserver.com/en/)

Download and Install LAMP Server


(http://csg.sph.umich.edu/abecasis/LAMP/download/)

Download and Install MAMP Server (https://www.mamp.info/en/downloads/)

Download and Install XAMPP Server (https://www.apachefriends.org/download.html)


Topic Title #3: 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 echo: printing string

File: echo1.php

<?php
echo "Hello by PHP echo";
?>

Output:

Hello by PHP echo

PHP echo: printing multi line string

File: echo2.php

<?php
echo "Hello by PHP echo
this is multi line
text printed by
PHP echo statement
";
?>

Output:

Hello by PHP echo this is multi line text printed by PHP echo statement
PHP echo: printing escaping characters

File: echo3.php

<?php
echo "Hello escape \"sequence\" characters";
?>

Output:

Hello escape "sequence" characters

PHP echo: printing variable value

File: echo4.php

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

Output:

Message is: Hello Skyapper PHP

Topic Title #4: 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.


Syntax of declaring a variable in PHP is given below:

$variablename=value;

PHP Variable: Declaring string, integer and float

Let's see the example to store string, integer and float values in PHP variables.

File: variable1.php

<?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 Variable: Sum of two variables

File: variable2.php

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

Output:

11
PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different from
Color, COLOR, COLor etc.

File: variable3.php

<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

Output:

My car is red

Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4

My house is

Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5

My boat is

PHP Variable: Rules

PHP variables must start with letter or underscore only. PHP variable can't be start with
numbers and special symbols.

File: variablevalid.php

<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>

Output:

hello
hello

File: variableinvalid.php

<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)

echo "$4c <br/> $*d";


?>

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable


(T_VARIABLE) or '$' in C:\wamp\www\variableinvalid.php on line 2

PHP: Loosely typed language

PHP is a loosely typed language, it means PHP automatically converts the variable to
its correct data type.

Topic Title #5: 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:

 Using define() function


 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.

Let's see the example to define PHP constant using define().

File: constant1.php

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

Output:

Hello Skyapper PHP

File: constant2.php

<?php
define("MESSAGE","Hello Skyapper PHP",true);//not case sensitive
echo MESSAGE;
echo message;
?>

Output:

Hello Skyapper PHPHello Skyapper PHP


File: constant3.php

<?php
define("MESSAGE","Hello Skyapper PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>

Output:

Hello Skyapper PHP

Notice: Use of undefined constant message - assumed 'message' in


C:\wamp\www\vconstant3.php on line 4 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.

File: constant4.php

<?php
const MESSAGE="Hello const by Skyapper PHP";
echo MESSAGE;
?>

Output:

Hello const by Skyapper PHP


Topic Title #6: 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:

 Scalar Types
 Compound Types
 Special Types

PHP Data Types: Scalar Types

There are 4 scalar data types in PHP.

 boolean
 integer
 float
 string

PHP Data Types: Compound Types

There are 2 compound data types in PHP.

 array
 object

PHP Data Types: Special Types

There are 2 special data types in PHP.

 resource
 NULL
Topic Title: Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9.


Here 4 and 5 are called operands and + is called operator. PHP language supports
following type of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −
Show Examples

Operato Description Example


r

+ Adds two operands A + B will give


30

- Subtracts second operand from the first A - B will give


-10

* Multiply both operands A * B will give


200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer B % A will give 0


division
++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples

Operato Description Example


r

== Checks if the value of two operands are equal or not, if (A == B) is


yes then condition becomes true. not true.

!= Checks if the value of two operands are equal or not, if (A != B) is


values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.

< Checks if the value of left operand is less than the value (A < B) is
of right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or (A >= B) is


equal to the value of right operand, if yes then condition not true.
becomes true.

<= Checks if the value of left operand is less than or equal (A <= B) is
to the value of right operand, if yes then condition true.
becomes true.
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples

Operato Description Example


r

and Called Logical AND operator. If both the operands are (A and B) is
true then condition becomes true. true.

or Called Logical OR Operator. If any of the two operands (A or B) is


are non zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are (A && B) is
non zero then condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands (A || B) is


are non zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.

Assignment Operators
There are following assignment operators supported by PHP language −
Show Examples

Operato Description Example


r

= Simple assignment operator, Assigns values C = A + B will assign


from right side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right C += A is equivalent
operand to the left operand and assign the result to C = C + A
to left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent


right operand from the left operand and assign to C = C - A
the result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent


right operand with the left operand and assign to C = C * A
the result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the to C = C / A
result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent


modulus using two operands and assign the to C = C % A
result to left operand

Conditional Operator
There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements
depending upon the result of the evaluation. The conditional operator has this syntax −
Show Examples

Operato Description Example


r

?: Conditional If Condition is true ? Then value X : Otherwise


Expression value Y

Operators Categories
All the operators we have discussed above can be categorised into following
categories −
 Unary prefix operators, which precede a single operand.
 Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.
 The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.
 Assignment operators, which assign a value to a variable.

Precedence of PHP Operators


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right


Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left


ADVANCED TUTORIALS

Topic Title #1: 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.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times.
By the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of
functions.

User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare
user-defined functions.

Syntax

function functionname(){
//code to be executed
}

Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
PHP Functions Example

File: function1.php

<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>

Output:

Hello PHP 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.

Let's see the example to pass single argument in PHP function.

File: functionarg.php

<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Output:

Hello Sonoo

Hello Vimal

Hello John
Let's see the example to pass two argument in PHP function.

File: functionarg2.php

<?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.

Let's see a simple example of call by reference in PHP.

File: functionref.php

<?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. Let's see a simple example
of using default argument value in PHP function.

File: functiondefaultarg.php

<?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

Let's see an example of PHP function that returns value.

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

Output:

Cube of 3 is: 27

Topic Title #2: 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 of PHP Array

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.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

 Indexed Array
 Associative Array
 Multidimensional Array
PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string
and object in the PHP array. All PHP array elements are assigned to an index number
by default.

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

File: array1.php

<?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

File: array2.php

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

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

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

File: arrayassociative1.php

<?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

File: arrayassociative2.php

<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["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

Topic Title #3: 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.

 include
 require
Advantage

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

PHP include example

PHP include is used to include file on the basis of given path. You may use relative or
absolute path of the file. Let's see a simple PHP include example.

File: menu.html

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

File: include1.php

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


<h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page


PHP require example

PHP require is similar to include. Let's see a simple PHP require example.

File: menu.html

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

File: require1.php

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


<h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page

PHP include vs PHP require

If file is missing or inclusion fails, include allows the script to continue but require halts
the script producing a fatal E_COMPILE_ERROR level error.

Topic Title #4: 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.

Note: PHP Cookie must be used before <html> tag.

PHP 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 seconds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com",
1);

PHP $_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.

Example

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


PHP Cookie Example

File: cookie1.php

<?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

PHP 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
?>
Topic Title #5: 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.

PHP 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();

PHP $_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"];

PHP Session Example

File: 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>

File: session2.php

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

PHP Session Counter Example

File: sessioncounter.php

<?php
session_start();

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

PHP Destroying Session

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

File: session3.php

<?php
session_start();
session_destroy();
?>
Topic Title #6: 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!";
}
?>

You might also like