PHP Example for beginners and professionals with examples, php file, php session, php date, php array, php form, functions, time, xml, ajax, php mysql, regex, string, oop
Generally, a PHP file contains HTML tags and some PHP scripting code. It’s easy to create a simple PHP example. Just create a file, write HTML tags + PHP code, and save it with a .php
extension. 💻
Note: PHP statements end with a semicolon (;
).
All PHP code goes between the PHP tag: <?php
(start) and ?>
(end).
<?php
// your code here
?>
File: first.php
<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>Hello First PHP</h2>";
?>
</body>
</html>
Output:
Hello First PHP
PHP is a popular backend programming language. You can write PHP programs in any text editor like Notepad, Notepad++, Dreamweaver, etc., and save them with a .php
extension (e.g., filename.php
) inside the htdocs
folder in XAMPP.
For example: p1.php
.
If you’re using Windows and have XAMPP installed on your D drive, the path for the htdocs
directory will be:
D:\xampp\htdocs
.
PHP programs run in a web browser like Chrome, Internet Explorer, Firefox, etc. Below are the steps to run a PHP program.
<?php
echo "Hello World!";
?>
hello.php
in the htdocs
folder (inside the XAMPP folder).Note: Make sure the PHP program is saved in the htdocs
folder; otherwise, you’ll get an error: Object Not Found.
http://localhost/hello.php
in the browser window.Hello World!
Most of the time, PHP programs run as a web server module. However, PHP can also be executed via the Command Line Interface (CLI).
In PHP:
echo
, if
, else
, while
), functions, and user-defined functions are NOT case-sensitive.<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello world using echo </br>";
ECHO "Hello world using ECHO </br>";
EcHo "Hello world using EcHo </br>";
?>
</body>
</html>
Output:
Hello world using echo
Hello world using ECHO
Hello world using EcHo
<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>
Output:
Notice: Undefined variable: ColoR in D:\xampp\htdocs\program\p2.php on line 8
My car is
My dog is black
Notice: Undefined variable: COLOR in D:\xampp\htdocs\program\p2.php on line 10
My Phone is
Only the $color
variable printed its value, while $ColoR
and $COLOR
were treated as undefined variables. 🚨
That’s it! Now you’re ready to create and run PHP code in XAMPP! 😎