0% found this document useful (0 votes)
96 views

TIOLE

XAMPP is a free and open source cross-platform web server package that allows you to run PHP, MySQL, Apache, and other web development tools on your computer. To run PHP programs locally using XAMPP, you install XAMPP, place your PHP files in the htdocs folder, start the Apache and MySQL services through the XAMPP control panel, and access your PHP files by entering their file path (e.g. localhost/filename.php) in a web browser. This allows testing PHP programs without uploading them to a live server.

Uploaded by

oz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

TIOLE

XAMPP is a free and open source cross-platform web server package that allows you to run PHP, MySQL, Apache, and other web development tools on your computer. To run PHP programs locally using XAMPP, you install XAMPP, place your PHP files in the htdocs folder, start the Apache and MySQL services through the XAMPP control panel, and access your PHP files by entering their file path (e.g. localhost/filename.php) in a web browser. This allows testing PHP programs without uploading them to a live server.

Uploaded by

oz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

IP2 MATERIALS

FHUFJHKJHHSD

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF
files. You can also output any text, such as XHTML and XML.

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

What's new in PHP 7


 PHP 7 is much faster than the previous popular stable release (PHP 5.6)
 PHP 7 has improved Error Handling
 PHP 7 supports stricter Type Declarations for function arguments
 PHP 7 supports new operators (like the spaceship operator: <=>)
 PHP vs HTML
PHP HTML

Developed by Tim
Developed by Rasmus Lerdorf.
Berners-Lee.

It is used for the development of dynamic websites and It is used to create web
dynamic web applications. pages.

PHP codes are dynamic. HTML codes are static.

PHP is used for server-side programming which will


HTML is used for
interact with databases to retrieve information, storing,
specifying colors, text
email sending, and provides content to HTML pages to
formatting, aligning, etc.
display on the screen.

HTML is very easy to


PHP is easy to learn but not as much as HTML.
learn.

HTML is used for front-


PHP is used for server-side development.
end development

HTML can be used in a


PHP can’t be used in an HTML file.
PHP file.

Extensions of PHP are .php, .php3, .php4, .php7 Extensions of HTML


PHP HTML

are .html, .htm

Steps:
Select your desired location, where you want to install XAMPP and then click
“Next”.

Click “Next” on the coming screens to proceed with the installation process.
Now, you will see the final screen. I would suggest that you keep the “start the
Control Panel” option checked. Click “Finish” to complete the installation
process. A new window will open shortly.
The XAMPP Control Panel has now started. Now, click “Start” button in
Apache and MySQL rows to begin.
You are now ready to start writing the code. Now all you need is an editor
like Notepad++ or Dreamweaver to write the code.

After downloading Notepad++, you can start writing your code


<?php

echo “My first PHP Script”;

?>
Now, save the page as “test.php” in htdocs folder and click “Save” button.

Now, open a web browser and type localhost in the address bar. It will
automatically open the index file but if you type localhost/test.php, it will open
the page that we have saved.

Consider another example.


<!DOCTYPE html>

<html>

<head>

<title>Getting Started With PHP</title>

</head>

<body>

<h1>Beginners Guide For PHP</h1>

<p>Tutorial Series For Learning PHP</p>

<?php

echo “2+3″.”<br/>”;//It will display the output 2+3

print “2+3”;// print will also display the output 2+3

?>

</body>

</html>
In this example, we use echo and print to show the same result. Here is the
output we get.

You can see that the two lines of 2+3 are displayed as output by using
different statements. Most of the professional programmers prefer to use echo
because echo can bring up multiple strings or values at the same time,
whereas print displays one statement at a time. Both echo and print can be
used with or without parentheses; print() or echo(). Also, it is to be noticed that
you can not see the sum of two numbers without using variables. The concept
of variables will be introduced along with PHP data types in the next tutorial.

Consider the example below.

<!DOCTYPE html>

<html>

<head>

<title>Getting Started With PHP</title>

</head>

<body>

<h1>Beginners Guide For PHP</h1>

<p>Tutorial Series For Learning PHP</p>

<?php

$a=99;

$b=”Calculus”;

echo “Numbers you have got in $b are $a”.”<br/>”;

echo ‘Numbers you have got in $b are $a’;

?>

</body>

</html>
In this example, you can see that we have echoed the same string with double
quotes and single quotes. Here is the output.
When we use double quotes, it displays the string along with the values
assigned to variables $a and $b. However, when we use single quotes, it will
treat the whole statement as string and will display variables $a and $b. I will
touch upon the concept of variables in detail in the next tutorial as well.

Thats it! that is how you start your PHP scripts! In the upcoming weeks, I will
be discussing more about PHP; from the most basic tutorials to the most
advanced. I hope to see you around for more PHP tutorials.

In the meanwhile, you can sign up and deploy PHP on the revolutionary
managed Cloud Hosting Platform. Choose your cloud provider from some of
the best infrastructures around, namely Google Compute Engine,
DigitalOcean and Amazon Web Services. It will take you less than 6 minutes
to sign up, choose the cloud provider and deploy PHP on your selected cloud
provider. It is fast and secure. Plus, you are always covered with a 24/7
support team that never keeps you at bay!

How to run PHP programs ?


akashmomale

 Read

 Discuss

 Courses

 Practice

 Video

XAMPP is a Web development tool, created by Apache, that makes it easy to run PHP
(Personal Home Pages) scripts on your computer locally. Installation of XAMPP Server
on windows is easy as compared to manual installation of a web server and PHP required
a lot of in-depth configuration knowledge. XAMPP package installs MySQL, FileZilla,
Mercury, Perl, and Tomcat along with Web Server and PHP, with these applications you
can test the full website on your desktop. You don’t need to upload it every time on an
online Web server.
Step 1: First of all, open the Apache Friends website and download XAMPP for
Windows, and install it.
Step 2: Start the XAMPP Program Control Panel. Click on the “Start”  button next to the
“Apache” to start your Apache Web Server. Also, start “MySQL” if your PHP programs
depend on a MySQL database to run.
How to run PHP programs ?

Step 3: Place your PHP files in the “htdocs” folder located under the “XAMPP” folder
on your drive (i.e. C/D/E etc). The initial path is “your_drive_letter:\xampp\htdocs” for
your Web server. Make sure that your PHP files are saved as a “.php” file extension.
Example: The “demo.php” file is saved in the htdocs folder.
 PHP

<!DOCTYPE html>
<html>

<body>

  <h1>Hello GFG </h1>

  <?php

    echo "Hello geeksforgeeks";

  ?>

</body>

</html>
How to run PHP programs ?

Step 4: Open up any web browser and enter “localhost/filename”. This will open
the list of all the files and folders stored under the “htdocs” folder on your
computer. Click on the link to a PHP file and open it to run a program.
Example: The file “demo.php” file is placed inside the “htdocs” folder. If you
want to run it, open any web browser and enter “localhost/demo.php” and press
enter. Your program will run.
Syntax: php have special Syntax to write a code, as shown in below 
<?php   
//write your code here  
?>  
demo.php
 PHP
<!DOCTYPE html>

<html>

<body>

  <h1>Hello GFG </h1>

  <?php

    echo "Inside gfgdemo FOLDER Hello geeksforgeeks";

   ?>

</body>

</html>
How to run PHP programs ?

Step 5: You can create any folder to test PHP files under the “htdocs” folder. If
you create a specific folder then you need to use the address as
“localhost/foldername” to open them in your browser.
Example: The “demo.php” file is placed inside the “gfgdemo” folder. Enter
“localhost/gfgdemo/demo.php” in your browser and press enter, your
program will be run.
How to run PHP programs ?

PHP case sensitivity


PHP is case sensitive language, in that variables and functions, tags are case
sensitive but classes are not case sensitive. Below the example of case
sensitivity of php. 
Example 1: echo.php
 PHP

<!DOCTYPE>
  <html>

  <body>

  <?php

  echo "Hello world using echo </br>";

  ECHO "Hello world using ECHO </br>";

  EcHo "Hello world using EcHo </br>";

  ?>

  </body>

  </html>

In above code we write three different types of echo methods, see the output in
the image. 
Output:

How to run PHP programs?

Example 2: color.php
 PHP

<html>

  <body>
  <?php

  $color = "black";

   echo "My car is ". $ColoR ."</br>";

   echo "My dog is ". $color ."</br>";

   echo "My Phone is ". $COLOR ."</br>";

   ?>

  </body>

  </html>

In the above example, the variable name is case sensitive, so it gives error.
Output:
My car is
My dog is black
My Phone is

PHP Notice: Undefined variable: ColoR in HelloWorld.php on line 3


PHP Notice: Undefined variable: COLOR in HelloWorld.php on line 5

Get and Post Methods in PHP


PHP provides two methods through which a client (browser) can send information to the
server. These methods are given below, and discussed in detail:

1. GET method
2. POST method

Get and Post methods are the HTTP request methods used inside the <form> tag to
send form data to the server.
HTTP protocol enables the communication between the client and the server where a
browser can be the client, and an application running on a computer system that hosts
your website can be the server.

GET method
The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.

PlayNext

Mute

Current Time 0:07

Duration 18:10

Loaded: 4.40%

 

Fullscreen

Backward Skip 10sPlay VideoForward Skip 10s

The information sent from an HTML form using the GET method is visible to everyone in
the browser's address bar, which means that all the variable names and their values will
be displayed in the URL. Therefore, the get method is not secured to send sensitive
information.

For Example

1. localhost/gettest.php?username=Harry&bloodgroup=AB+  

The bold part in the above URL is the variables name and italic part contains the values
for their corresponding variable.
Note that only a limited amount of information can be sent using the GET method.

With the help of an example, let's understand how the GET method works-

Example
The below code will display an HTML form containing two input fields and a submit
button. In this HTML form, we used the method = "get" to submit the form data.

file: test1.html

1. <html>  
2.    <body>  
3.      
4.       <form action = "gettest.php" method = "GET">  
5.          Username: <input type = "text" name = "username" /> <br>  
6.          Blood Group: <input type = "text" name = "bloodgroup" /> <br>  
7.          <input type = "submit" />  
8.       </form>  
9.         
10.    </body>  
11. </html>  

Create gettest.php file, which will accept the data sent by HTML form.

file: gettest.php

1. <html>  
2.    <body>  
3.      
4.       Welcome <?php echo $_GET["username"]; ?> </br>  
5.       Your blood group is: <?php echo $_GET["bloodgroup"]; ?>  
6.   
7.    </body>  
8. </html>  

When the user will click on Submit button after filling the form, the URL sent to the
server could look something like this:

localhost/gettest.php?username=Harry&bloodgroup=AB-

The output will look like the below output:

Welcome Harry
Your blood group is: AB-

Advantages of GET method (method = "get")


o You can bookmark the page with the specific query string because the data sent by the
GET method is displayed in URL.
o GET requests can be cached.
o GET requests are always remained in the browser history.

Disadvantages of GET Method


o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed
2048 characters.
o For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.
o The GET method cannot be used to send binary data (such as images or word
documents) to the server.

POST method
Similar to the GET method, the POST method is also used to submit the HTML form
data. But the data submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
Unlike the GET method, it does not have a limit on the amount of information to be
sent. The information sent from an HTML form using the POST method is not visible to
anyone.

For Example

1. localhost/posttest.php  

Note that the "post" method is more secure than the "get" method because the data sent
using the POST method is not visible to user.

With the help of an example, let's understand how the POST method works-

Example
The below code will display an HTML form containing two input fields and a submit
button. In this HTML form, we used the method = "post" to submit the form data.

file: test2.html

1. <html>  
2.    <body>  
3.      
4.       <form action = "posttest.php" method = "post">  
5.          Username: <input type = "text" name = "username" /> <br>  
6.          Blood Group: <input type = "text" name = "bloodgroup" /> <br>  
7.          <input type = "submit" />  
8.       </form>  
9.         
10.    </body>  
11. </html>  
Now create posttest.php file to accept the data sent by HTML form.

file: posttest.php

1. <html>  
2.    <body>  
3.      
4.       Welcome <?php echo $_POST["username"]; ?> </br>  
5.       Your blood group is: <?php echo $_POST["bloodgroup"]; ?>  
6.   
7.    </body>  
8. </html>  

When the user will click on Submit button after filling the form, the URL sent to the
server could look something like this:

localhost/posttest.php

The output will look like the below output:

Welcome Harry
Your blood group is: O+

Advantages of POST method (method = "post")


o The POST method is useful for sending any sensitive information because the
information sent using the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a
large amount of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the
POST method goes through the HTTP header. By using secure HTTP, you can ensure that
your data is safe.

Disadvantages of POST Method


o POST requests do not cache.
o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.
$_REQUEST variable
The $_REQUEST variable is a superglobal variable, which can hold the content of both
$_GET and $_POST variable. In other words, the PHP $_REQUEST variable is used to
collect the form data sent by either GET or POST methods. It can also collect the data for
$_COOKIE variable because it is not a method-specific variable.

Form Validation in PHP


An HTML form contains various input fields such as text box, checkbox, radio buttons,
submit button, and checklist, etc. These input fields need to be validated, which ensures
that the user has entered information in all the required fields and also validates that the
information provided by the user is valid and correct.

There is no guarantee that the information provided by the user is always


correct. PHP validates the data at the server-side, which is submitted by HTML form. You
need to validate a few things:

1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length

Empty String
The code below checks that the field is not empty. If the user leaves the required field
empty, it will show an error message. Put these lines of code to validate the required
field.

1. if (emptyempty ($_POST["name"])) {  
2.     $errMsg = "Error! You didn't enter the Name.";  
3.              echo $errMsg;  
4. } else {  
5.     $name = $_POST["name"];  
6. }  
Validate String
The code below checks that the field will contain only alphabets and whitespace, for
example - name. If the name field does not receive valid input from the user, then it will
show an error message:

PlayNext

Unmute

Current Time 0:00

Duration 18:10

Loaded: 0.37%

 

Fullscreen

Backward Skip 10sPlay VideoForward Skip 10s

1. $name = $_POST ["Name"];  
2. if (!preg_match ("/^[a-zA-z]*$/", $name) ) {  
3.     $ErrMsg = "Only alphabets and whitespace are allowed.";  
4.              echo $ErrMsg;  
5. } else {  
6.     echo $name;  
7. }  

Validate Number
The below code validates that the field will only contain a numeric value. For example
- Mobile no. If the Mobile no field does not receive numeric data from the user, the code
will display an error message:

1. $mobileno = $_POST ["Mobile_no"];  
2. if (!preg_match ("/^[0-9]*$/", $mobileno) ){  
3.     $ErrMsg = "Only numeric value is allowed.";  
4.     echo $ErrMsg;  
5. } else {  
6.     echo $mobileno;  
7. }  

Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate
the email address. Here, we will use regular expressions to validate the email address.

The below code validates the email address provided by the user through HTML form. If
the field does not contain a valid email address, then the code will display an error
message:

1. $email = $_POST ["Email"];  
2. $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";  
3. if (!preg_match ($pattern, $email) ){  
4.     $ErrMsg = "Email is not valid.";  
5.             echo $ErrMsg;  
6. } else {  
7.     echo "Your valid email address is: " .$email;  
8. }  

Input Length Validation


The input length validation restricts the user to provide the value between the specified
range, for Example - Mobile Number. A valid mobile number must have 10 digits.

The given code will help you to apply the length validation on user input:

1. $mobileno = strlen ($_POST ["Mobile"]);  
2. $length = strlen ($mobileno);  
3.   
4. if ( $length < 10 && $length > 10) {  
5.     $ErrMsg = "Mobile must have 10 digits.";  
6.             echo $ErrMsg;  
7. } else {  
8.     echo "Your Mobile number is: " .$mobileno;  
9. }  

Validate URL
The below code validates the URL of website provided by the user via HTML form. If the
field does not contain a valid URL, the code will display an error message, i.e., "URL is
not valid".

1. $websiteURL = $_POST["website"];  
2. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website)) {  
3.   $websiteErr = "URL is not valid";  
4.   echo $websiteErr;  
5. } else {  
6.     echo "Website URL is: " .$websiteURL;  
7. }  

Button Click Validate


The below code validates that the user click on submit button and send the form data to
the server one of the following method - get or post.

1. if (isset ($_POST['submit']) {  
2.     echo "Submit button is clicked.";  
3.     if ($_SERVER["REQUEST_METHOD"] == "POST") {  
4.         echo "Data is sent using POST method ";  
5.     }  
6. } else {  
7.     echo "Data is not submitted";  
8. }  
Note: Remember that validation and verification both are different from each other.

Now we will apply all these validations to an HTML form to validate the fields. Thereby
you can learn in detail how these codes will be used to validation form.

Create a registration form using HTML and perform server-side validation. Follow the


below instructions as given:

Create and validate a Registration form


1. <!DOCTYPE html>  
2. <html>  
3. <head>  
4. <style>  
5. .error {color: #FF0001;}  
6. </style>  
7. </head>  
8. <body>    
9.   
10. <?php  
11. // define variables to empty values  
12. $nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";  
13. $name = $email = $mobileno = $gender = $website = $agree = "";  
14.   
15. //Input fields validation  
16. if ($_SERVER["REQUEST_METHOD"] == "POST") {  
17.       
18. //String Validation  
19.     if (emptyempty($_POST["name"])) {  
20.          $nameErr = "Name is required";  
21.     } else {  
22.         $name = input_data($_POST["name"]);  
23.             // check if name only contains letters and whitespace  
24.             if (!preg_match("/^[a-zA-Z ]*$/",$name)) {  
25.                 $nameErr = "Only alphabets and white space are allowed";  
26.             }  
27.     }  
28.       
29.     //Email Validation   
30.     if (emptyempty($_POST["email"])) {  
31.             $emailErr = "Email is required";  
32.     } else {  
33.             $email = input_data($_POST["email"]);  
34.             // check that the e-mail address is well-formed  
35.             if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  
36.                 $emailErr = "Invalid email format";  
37.             }  
38.      }  
39.     
40.     //Number Validation  
41.     if (emptyempty($_POST["mobileno"])) {  
42.             $mobilenoErr = "Mobile no is required";  
43.     } else {  
44.             $mobileno = input_data($_POST["mobileno"]);  
45.             // check if mobile no is well-formed  
46.             if (!preg_match ("/^[0-9]*$/", $mobileno) ) {  
47.             $mobilenoErr = "Only numeric value is allowed.";  
48.             }  
49.         //check mobile no length should not be less and greator than 10  
50.         if (strlen ($mobileno) != 10) {  
51.             $mobilenoErr = "Mobile no must contain 10 digits.";  
52.             }  
53.     }  
54.       
55.     //URL Validation      
56.     if (emptyempty($_POST["website"])) {  
57.         $website = "";  
58.     } else {  
59.             $website = input_data($_POST["website"]);  
60.             // check if URL address syntax is valid  
61.             if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {  
62.                 $websiteErr = "Invalid URL";  
63.             }      
64.     }  
65.       
66.     //Empty Field Validation  
67.     if (emptyempty ($_POST["gender"])) {  
68.             $genderErr = "Gender is required";  
69.     } else {  
70.             $gender = input_data($_POST["gender"]);  
71.     }  
72.   
73.     //Checkbox Validation  
74.     if (!isset($_POST['agree'])){  
75.             $agreeErr = "Accept terms of services before submit.";  
76.     } else {  
77.             $agree = input_data($_POST["agree"]);  
78.     }  
79. }  
80. function input_data($data) {  
81.   $data = trim($data);  
82.   $data = stripslashes($data);  
83.   $data = htmlspecialchars($data);  
84.   return $data;  
85. }  
86. ?>  
87.   
88. <h2>Registration Form</h2>  
89. <span class = "error">* required field </span>  
90. <br><br>  
91. <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >    
92.     Name:   
93.     <input type="text" name="name">  
94.     <span class="error">* <?php echo $nameErr; ?> </span>  
95.     <br><br>  
96.     E-mail:   
97.     <input type="text" name="email">  
98.     <span class="error">* <?php echo $emailErr; ?> </span>  
99.     <br><br>  
100.     Mobile No:   
101.     <input type="text" name="mobileno">  
102.     <span class="error">* <?php echo $mobilenoErr; ?> </span>  
103.     <br><br>  
104.     Website:   
105.     <input type="text" name="website">  
106.     <span class="error"><?php echo $websiteErr; ?> </span>  
107.     <br><br>  
108.     Gender:  
109.     <input type="radio" name="gender" value="male"> Male  
110.     <input type="radio" name="gender" value="female"> Female  
111.     <input type="radio" name="gender" value="other"> Other  
112.     <span class="error">* <?php echo $genderErr; ?> </span>  
113.     <br><br>  
114.     Agree to Terms of Service:  
115.     <input type="checkbox" name="agree">  
116.     <span class="error">* <?php echo $agreeErr; ?> </span>  
117.     <br><br>                            
118.     <input type="submit" name="submit" value="Submit">   
119.     <br><br>                             
120. </form>  
121.   
122. <?php  
123.     if(isset($_POST['submit'])) {  
124.     if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" 
&& $websiteErr == "" && $agreeErr == "") {  
125.         echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";  
126.         echo "<h2>Your Input:</h2>";  
127.         echo "Name: " .$name;  
128.         echo "<br>";  
129.         echo "Email: " .$email;  
130.         echo "<br>";  
131.         echo "Mobile No: " .$mobileno;  
132.         echo "<br>";  
133.         echo "Website: " .$website;  
134.         echo "<br>";  
135.         echo "Gender: " .$gender;  
136.     } else {  
137.         echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";  
138.     }  
139.     }  
140. ?>  
141.   
142. </body>  
143. </html>  

When the above code runs on a browser, the output will be like the screenshot below:
Fill the registration form and click on the Submit button. If all required information is
provided correctly, the output will be displayed on the same page below the submit
button. See the screenshot below:
Remember that we have not used a database to store the data for registered users.

You might also like