Wednesday, December 16, 2015

PHP Basics

This post shows how to create a PHP file with echo/print, variables, if condition, arrays, functions, and server date/time.

Requirements for this post:
1. Install Apache HTTP server
2. Install PHP

Type this command in the terminal:

cd /var/www
sudo nano basics.php

Edit the basics.php file as below:

<html>
<head><title>My Title</title></head>
<body>
<?php
//Use echo or print for printing
?>
<P><?php echo "Hello World!!" ?></P>
<P><?php print "Test<br>new line" ?>
<P><?php

//Variables

$my_str = "This is my string.";
$my_val = 100;

print $my_str;
print $my_val;

?>
<P>1+2+3=<?php print 1+2+3 ?></P>
<P><?php
$my_bool = true;

//if condition
if ($my_bool)
{
    print $my_bool;
}
else
{
    print "Noooooo";

}

$my_number = 123;
//A dot is required before $my_number:
print "<br>number = " . $my_number;
print "<br><br>";

//Array
$my_array = Array("Adam", "Tom", "Peter", "David");

for ($x=0; $x<=3; $x++){
    print "$my_array[$x]<br>";
}

//Function
function MyFunc() {
print "<br>MyFunc() is called!!";
}
print "<br>Before";
MyFunc();
print "<br>After";

//Server Time
print "<br><br>Now is " . Date("h:i:s A D Y/m/d");

?></P>
</body></html>


After editing, press Ctrl and X keys at the same time. Then select Y to save the php file.

========

Open the browser with this URL:

http://192.168.xx.xx/basics.php

The result:

No comments:

Post a Comment