You are on page 1of 16

PHP in HTML

PHP is an HTML-embedded server-side scripting language. Much of its syntax is borrowed from C, Java and Perl
with a couple of unique PHP-specific features.

PHP is designed to interact with HTML and PHP scripts can be included in an HTML page without a
problem.

In an HTML page, PHP code is enclosed within special PHP tags.

When a visitor opens the page, the server processes the PHP code and then sends the output (not the PHP code
itself) to the visitor's browser.

A PHP script can be treated as an HTML page, with bits of PHP inserted here and there. Anything in a PHP script
that is not contained within <?php?> tags is ignored by the PHP compiler and passed directly to the web
browser.

Example:

html>
<head><title>Random number</title></head>
<body>
<p>I have chosen

<?php
echo rand (1, 100);
?>

</p>
</body>
</html>
<html>
<head><title>Random</title></head>
<body>
<p>I have randomly selected the number

<?php
$choice = rand (1, 100);
echo $choice;
?>.

Its square root is

<?php
echo sqrt($choice);
?>

</p>
</body>
</html>
<html>
<head><title>Random</title></head>
<body>
<p>I have randomly selected the number
<?php $choice=rand (1,100); echo $choice;

?>.
Its square root is

<?php echo sqrt($choice);

?>.

</p>
</body>
</html>

Accessing user information


Creating forms
Most interesting server-side Web programs involve reacting to information received from the browser
(and ultimately the person using the browser). Before we see how to write PHP to accomplish this, we
first examine how to compose HTML to request information from the user using a form.

Suppose, for example, that we want to prompt the user for the range of numbers from which the server
should select a random number. We decide we want to show the user two different text fields, and a
button the user can click to submit the request.

Range Start:

Range End:

The HTML to generate the above is the following.

<form method="post" action="random.php">


<p>Range Start: <input type="text" name="begin" /></p>
<p>Range End: <input type="text" name="end" /></p>
<p><input type="submit" value="Generate" /></p>
</form>

This uses two element types specific to forms: form and input. The first, the form element, should
encompass the entire form. We'll use two attributes for the form tag, method and action. The method
attribute configures how the browser should send information back to server; as far as we're concerned,
the method attribute should always be present and always have the value post. The action attribute
configures what PHP script should receive the information when the user submits the form; this should
be the URL of the page you are accessing.

An input element places an element as part of the form; normally, this is something with which the user
can interact, such as a text field, radio button, checkbox, or button. It has three attributes that are
important to use.
 The type attribute configures what sort of input element is drawn in the window. Some possible
values are text for a text field, radio for a radio button, checkbox for a checkbox, and submit
for a button.
 The name attribute has no effect on how the element is displayed, but when the browser sends
information to the server (and ultimately your PHP script), it uses the name attribute to tell it
what the user has entered; in our above example, if the user enters 10 and 20 into the text fields
and then clicks the button, the browser will send a message to the server saying that the user
wants to execute the random.php script where begin has been given the value 10 and end has
been given the value 20. Without the name attribute being specified, we would not be able to
access the user's values.
 The value attribute configures the initial appearance of the element. For a text field, it says what
should originally be in that text field: We omitted it, so the text field initially appears empty; but
it might have been nicer to add a value attribute for the begin field saying that it should be 1
when the user first loads the page, since this is probably the most typical value the user wants to
see. For a button, the value attribute configures what letters appear in the button.

As a person browsing the Web, you've seen that HTML has ways of incorporating other user interaction
elements, such as radio buttons, checkboxes, drop-down choice boxes, file selection areas, lists, and
larger text areas. For the moment, though, we'll use just text fields and buttons, which is plenty to be
able to compose interesting PHP scripts.

http://www.toves.org/books/php/ch04-forms/index.html

HTML in PHP

You can also use HTML code in a PHP script. This can be very useful if you have built your whole page
in PHP, but want to include a custom HTML form, for example. All that you need to do is reverse the
order of the HTML and PHP opening tags, opening the page with PHP:

Using HTML in PHP:


<?php
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br /></form>
<?
echo "Hello, ".$Fname." “. $Lname.".<br />";
?>

A lot of code can be saved. Here, we are using the $PHP_SELF super global, which allows us to use the
value of the fields, specified under it, in the same file. Usually, for such forms two files are created - the
first one is the HTML form itself and the second one is the backend PHP file, which does all the work.

<html>
<body>
<form method="post">
Enter First Number:
<input type="number" name="number1" /><br><br>
Enter Second Number:
<input type="number" name="number2" /><br><br>
<input type="submit" name="submit" value="Add">
</form>
<?php
if(isset($_POST['submit']))
{
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$sum = $number1+$number2;
echo "The sum of $number1 and $number2 is: ".$sum;
}
?>
</body>
</html>

<form name="form1" method="post" action="<?php echo


$_SERVER['PHP_SELF']; ?>">

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

1. bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example


File: uploadform.html

1. <form action="uploader.php" method="post" enctype="multipart/form-data">


2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
File: uploader.php

1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10. ?>

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

PHP readfile() function


Syntax

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

PHP Download File Example: Text File


File: download1.php

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

PHP Download File Example: Binary File


File: download2.php

1. <?php
2. $file_url = 'http://www.myremoteserver.com/file.exe';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: Binary");
5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

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 [, string
$additional_parameters ]] )

$to: specifies receiver or receivers of the mail. The receiver must be specified one of the following
forms.

o user@example.com
o user@example.com, anotheruser@example.com
o User <user@example.com>
o 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 ( \r\n ) 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 ( \r\n ).

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 \r\n";
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 \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
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 \r\n 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.com\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
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 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

1. bool session_start ( void )

Example

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

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

Example: Get information

1. echo $_SESSION["user"];

PHP Session Example


File: session1.php

1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php

1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>

PHP Session Counter Example


File: sessioncounter.php

1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>

PHP Destroying Session


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

File: session3.php

1. <?php
2. session_start();
3. session_destroy();
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

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

Example

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


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

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example

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

PHP Cookie Example


File: cookie1.php

1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </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.

File: cookie1.php

1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>

Hypertext Transfer Protocol (HTTP) is the standard protocol used to transfer data between your browser
and the various Web sites you visit.

What you may not know, however, is that HTTP is a “Stateless” Protocol, which treats each request for a
Web page as a unique and independent transaction, with no relationship.

To work around this problem, most Web sites use cookies or sessions to “maintain state,” in order to offer
enhanced services.

for example, shopping carts or automatic restoration of personal settings — to site users.

cookies are: text files stored on a user’s system that help a Web site recognize the
user and retrieve specific information about him or her.

The problem with cookies is that they’re not very secure: because ther are stored on the client, it’s possible
for any user to open the cookie file and read or modify the information stored within it.

That’s why many Web sites prefer to use sessions . Sessions work much like cookies, except that the
information used to maintain state is stored on the server, rather than on the client.

The main difference between a session and acookie is that session data is stored on the
server, whereas cookies store data in the visitor's browser. ... Data stored in cookie can be
stored for months or years, depending on the life span of the cookie. But the data in
the session is lost when the web browser is closed.
Difference Between Session and Cookie in PHP

Cookies are stored in browser as a text file format. It is stored limit amount of data.It is only allowing

4kb[4096bytes]. It is not holding the multiple variable in cookies.

Sessions are stored in server side. It is stored unlimited amount of data.It is holding the multiple

variable in sessions. we cannot accessing the cookies values in easily.So it is more secure.

Cookies Sessions
Cookies are stored in browser as text file
Sessions are stored in server side.
format.
It is stored limit amount of data. It is stored unlimited amount of data
It is only allowing 4kb[4096bytes]. It is holding the multiple variable in sessions.
It is not holding the multiple variable in
It is holding the multiple variable in sessions.
cookies.
we can accessing the cookies values in we cannot accessing the session values in easily.So it is more
easily. So it is less secure. secure.
setting the cookie time to expire the
using session_destory(), we we will destroyed the sessions.
cookie.
The setcookie() function must appear The session_start() function must be the very first thing in
BEFORE the <html> tag. your document. Before any HTML tags.

Example of Cookie

Example of Cookie

<?php

setcookie(name, value, expire,


path,domain, secure, httponly);

$cookie_uame = "user";

$cookie_uvalue= "Hitesh Kumar";

//set cookies for 1 hour time


setcookie($cookie_uname,
$cookie_uvalue, 3600, "/");

//expire cookies
setcookie($cookie_uname,"",-3600);

?>

Example of Session
Example of Session

<?php

session_start();

//session variable
$_SESSION['user'] = 'Hitesh';

//destroyed the entire sessions

session_destroy();

//Destroyed the session


variable "user".
unset($_SESSION['user']);
?>

session_unset() vs session_destroy() in PHP


There are two very similar PHP function session_destroy() & session_unset(). Both seem to
delete all variables registered to a session but there is difference between them.
session_destroy() function: It destroys all of the data associated with the current session.
Syntax:
bool session_destroy( void )
session_unset() function: It deletes only the variables from session and session still exists.
Only data is truncated.

session_destroy() function: It destroys the whole session rather destroying the variables. When
session_start() is called, PHP sets the session cookie in browser. We need to delete the cookies also to
completely destroy the session.
The main difference between a session and a cookie is that session data is stored on the server,
whereas cookies store data in the visitor's browser. Sessions are more secure than cookies as it is
stored in server.

You might also like