php

PHP Tutorial For Beginners

PHP Tutorial For Beginners
If you are new in PHP then this tutorials will help you to learn PHP from the beginning.

PHP Basics:

  1. Hello World
  2. Comments
  3. Variables with Strings
  4. Concatenate Strings
  5. Trim Strings
  6. Substrings
  7. Variables with Numbers
  8. Math
  9. Current Date
  10. Date checking
  11. If Statements
  12. Else and ElseIf
  13. If with (OR and AND)
  14. Arrays
  15. while Loop
  16. foreach loop
  17. functions
  18. function arguments
  19. die and exit
  20. Include Files
  21. JSON usage
  22. XML usage
  23. HTML Form Inputs
  24. get_browser function
  25. Session storage
  26. Server Request Method
  27. HTTP POST
  28. Sending Email
  29. Object and Class
  30. Exception Handling

Hello World

The extension of PHP file is .php. tags are used to define PHP code block and using ';' at the end of the line is mandatory for PHP script. Create a new file named 'first.php' to run your first script and save the file in /www/html/htdocs folder. Add the following script to print a simple text, “Hello World”.

//Print text
echo "Hello World";
?>

Output:

Run the file from the browser.

http://localhost/first.php

Top

Comments

Like other standard programming languages, you can use '//' for single line comment and '/* */' for multiple line comment. Create a PHP file named 'comment.php' with the following code to show the use of single and multiple lines comment in PHP.

//Assign a value in the variable $n
$n = 10;
/* Print
the value of $n */
echo "n = $n";
?>

Output:

Run the file from the browser.

http://localhost/comment.php

Top

Variables with strings

'$' symbol is used to declare and read any variable in PHP. Create a PHP file named 'strings.php' with the following code. You can use single quote (") or double quote (” “) to declare or print any string variable but the double quote is used to print the value of the string variable with other string data. Different uses of string variables are shown in this example.

$site = 'LinuxHint';
echo "$site is a good blog site.
";
$os = 'Linux';
echo "You can read different topics of $os on $site.";
?>

Output:

Run the file from the browser.

http://localhost/strings.php

Top

Concatenate Strings

'.' operator is used in PHP to combine multiple variables. Create a PHP file named 'concate.php' and add the following code to combine multiple string variables. The sum of two number variables is stored in another variable and the values of three variables are printed by combining with other string.

$a = 30;
$b = 20;
$c = $a + $b;
echo "The sum of ".$a." and ".$b." is ".$c;
?>

Output:

Run the file from the browser.

http://localhost/concate.php

Top

Trim Strings

trim() function is used in PHP to remove any character from left and right side of any string. There are two other functions in PHP for removing character from left or right side. These are ltrim() and rtrim(). Create a PHP file named 'trimming.php' with the following code to show the uses of these three functions. Three trimming functions are used in the script and the character 'a' is removed from the starting or ending or both sides based on applied string.

$text = "aa I like programming aa";
echo "Before trim:$text
";
echo "After trim:".trim($text,'a')."
";
echo "After ltrim:".ltrim($text,'a')."
";
echo "After rtrim:".rtrim($text,'a')."
";
?>

Output:

Run the file from the browser.

http://localhost/trimming.php

You can learn more about trimming from the following tutorial link.

https://linuxhint.com/trim_string_php/

Top

Substrings

substr() function is used in PHP to read a particular part of a string. This function can take three parameters. The first parameter is the main string that you want to cut, the second parameter is the starting index and the third parameter is the length of the string. The third parameter is optional for this method.  Create a PHP file named 'substring.php' with the following code to show the use of this function. In this function, the starting index counts from 0 but negative starting index value counts from 1. And the length value counts from 1. If you omit the third parameter of this function then the characters from the starting index to the end of the main string will be cut.

echo substr("Web Programming",4,7)."
";
echo substr("Web Programming",4)."
";
echo substr("Web Programming",-8,4)."
";
?>

Output:

Run the file from the browser.

http://localhost/substring.php

Top

Variables with Numbers

You can declare different types of number variables in PHP. Number value can be integer or float. Three types of numbers are declared and added in the following script. Create a PHP file named 'numbers.php' to show the use of number variable.

$a = 8;
$b = 10.5;
$c = 0xFF;
echo $a+$b+$c;
?>

Output:

Run the file from the browser.

http://localhost/numbers.php

Top

Math

PHP contains many built-in functions to do various types of mathematical tasks, such as abs(), ceil(), floor(), hexdec(), max(), min(), rand() etc. The use of abs() function is shown in the following script. abs() function returns the absolute value of any number. If you provide any negative number then abs() function will return only the value without any sign.

absval.php

$number = -17.87;
$absnum = abs($number);
echo $absnum;
?>

Output:

Run the file from the browser.

http://localhost/absval.php

Top

Current Date

You can get data and time related all information in PHP in two ways. One way to use date() function and another way to use DateTime class. How you can get the current date by using mentioned two ways is shown in the following script. The script will show the current date in 'day-month-year' format.
currentdate.php

$CurrentDate1 = date('d-m-Y');
echo $CurrentDate1."
";
$CurrentDate2 = new DateTime();
echo $CurrentDate2->format('d-m-Y');
?>

Output:

Run the file from the browser.

http://localhost/currentdate.php

Date checking

checkdate() function is used in PHP to check a date is valid or not. The use of this function is shown in the following script. This script will check a year is a leap year or not based on a date.

leapyear.php

if(checkdate(02, 29, 2018))
echo "The year is leap year";
else
echo "The year is not leap year";
?>

Output:

Run the file from the browser.

http://localhost/leapyear.php

Top

if Statements

if statement is used for declaring conditional statement. The syntax of if statement in PHP is similar to other standard programming languages. The following script shows the use of simple if statement. According to the script, the condition is true and it will print the output, ”You are eligible for this offer”.

if.php

$age = 20;
if ($age >= 18)
echo "You are eligible for this offer";
?>

Output:

Run the file from the browser.

http://localhost/if.php

Top

Else and ElseIf

You can use else and elseif with if statement if you want to execute different statements based on different conditions. Three types of conditions are checked in the following script. The second condition will be true according to the script and it will print “You won the second prize”.
elseif.php

$n = 220;
if ($n == 1010)
echo "You won the first prize";
elseif ($n == 220)
echo "You won the second prize";
else
echo "Try again later";

?>

Output:

Run the file from the browser.

http://localhost/elseif.php

Top

If with (OR and AND)

You can use multiple conditions in if statement by using logical OR and AND. Logical OR returns true when any condition of multiple conditions becomes true. Logical AND returns true when all declared conditions become true. The following script shows the uses of if statement with OR and AND logic. Here, if-else-if statement is used with logical AND that will print the output based on assigned $current_time. Another if statement is used with logical OR that will print the output if any of the conditions becomes true.
orand.php

$current_time = 17;
$break_time = false;
if ($current_time >= 9 AND $current_time <= 12)
echo "Morning
";
elseif ($current_time > 13 AND $current_time <= 16)
echo "Afternoon
";
else

echo "Evening
";
$break_time = true;

if ($current_time > 16 OR $break_time == true)
echo "Go to home
";
?>

Output:

Run the file from the browser.

http://localhost/orand.php

Top

Arrays

When you want to add multiple values in a single variable then you can use array or object variable. Mainly two types of array can be declared in any programming language. These are numeric and associative array. Array can be categorized by one dimensional and multidimensional array also. The following example shows the use of simple numeric and associative array. Here, numeric array, $names is read and printed by using for loop and associative array, $emails is read and printed by foreach loop.

array.php

//Numeric Array
$names = array("Jim", "Riffat", "Ella");
for($i = 0; $iecho "Name: ".$names[$i]."
";
//Associative Array
$emails=array("Jim"=>"[email protected]","Riffat"=>"[email protected]",
"Ella"=>"[email protected]");
foreach($emails as $name=>$email)

echo "
The email address of $name is $email
";

?>

Output:

Run the file from the browser.

http://localhost/array.php

You can visit the following tutorial link to know more about PHP array.

https://linuxhint.com/php-arrays-tutorial/

Top

while Loop

PHP uses three types of loops to iterate a block of code multiple times. while loop is one of them that continues the iteration until the loop reach the termination condition. The syntax of while loop declaration is similar to the other standard programming languages. The following example shows the use of while loop. The loop is used here to find out even numbers from 1 to 10. The loop will iterate for 10 times and check each number is divisible by 2 or not. The numbers which are divisible by 2 will print.

while.php

$n = 1;
echo "Even numbers from 1-10
";
while($n < 11)

if(($n % 2) == 0)
echo "$n
";
$n++;

?>

Output:

Run the file from the browser.

http://localhost/while.php

Top

foreach loop

PHP uses foreach loop to read an array or object variable. This loop can read key/value pair from an associative array. The use of this loop is shown in the following script. Here, an associative array named $books is declared. The index of the array contains the book type and the value of the array contains the book name. foreach loop is used to iterate the array with key and value and print them by concatenating with other string.
foreach.php

$books = array("cms"=>"Wordpress", "framework"=>"Laravel 5","javascript library"=>
"React 16 essentials");
foreach ($books as $type=>$bookName)
echo " $bookName is a popular $type
";

?>

Output:

Run the file from the browser.

http://localhost/foreach.php

Top

functions

If you want to use the same block of code many times in many parts of the same script then it is better to create a function with the common block of code and call the function where the code needs to execute. A simple use of the function is shown in the following example. Here, a function without any argument is declared that will print a text after calling.

function.php

//Declare the function
function WelcomeMessage()
echo "

Welcome to Linuxhint

";

// call the function
WelcomeMessage();
?>

Output:

Run the file from the browser.

http://localhost/function.php

Top

function arguments

You can use a function with arguments or without arguments. The previous example shows the use of argument less function. You can send argument in function by value or reference.  The argument is passed by value to the function in the following example. Here, a function with one argument is defined that will take the radius value of a circle and calculate the area of the circle based on that value. The function is called three times with three different radius values.
circlearea.php

//Declare the function
function circleArea($radius)
$area = 3.14*$radius*$radius;
echo "

The area of the circle is $area

";

// call the function
circleArea(12);
circleArea(34);
circleArea(52);
?>

Output:

Run the file from the browser.

http://localhost/circlearea.php

Top

die and exit

PHP uses die() and exit() functions to exit from the script by displaying an error message. There is no basic difference between these two functions. The uses of these both functions are shown in the following examples.

die() function

The following script will generate an error if newfile.txt doesn't exist in the current location and stops the execution by displaying the error message included in die() method.

dieerr.php

if(!fopen("newfile.txt","r"))
die("Unable to open the file");
echo "Reading the file content… ";
?>

Output:

Run the file from the browser.

http://localhost/dieerr.php

exit() function

The following script will stop the execution of the script by displaying error message if the value of $n not equal to 100.

exiterr.php

$n=10;
if($n != 100)
exit("n is not equal to 100");
else
echo "n is equal to 100";
?>

Output:

Run the file from the browser.

http://localhost/exiterr.php

Top

Include Files

When you need to use the same code in multiple PHP scripts then it is better to save the common script in any file and use the code multiple times by including the file. You can include file in PHP by using four methods. These are require(), require_once(), include() and include_once(). If require() or require_once() fails to include the file then it stops the execution of the script forcibly but include() or include_once() doesn't stop the execution of the script if an error occurs in inclusion. The use of the two methods is shown in the following example. Create a PHP file named “welcome.php” with the following code that will be included later. This script will print a simple text.

welcome.php

echo "Start reading from here
";
?>

Create another PHP file named “include_file.php” and add the following code. Here, include() method will not stop the execution for inclusion error and print the message “Laravel is a very popular PHP framework now”. But require() method will stop the execution for inclusion error and will not print the last two echo messages after require() statement.

include_file.php

include('welcom.php');
echo "Laravel is a very popular PHP framework now
";
require('welcom.php');
echo "You can use Magento for developing ecommerce site
";
echo "Thank you for reading
";
?>

Output:

Run the file from the browser.

http://localhost/include_file.php

Top

JSON Usage

There is a built-in method in PHP to read data from the web server in JSON format and display in the web page. One of the common methods of PHP is json_encode() for creating JSON data. This method is used in the following script to convert PHP array into JSON data.

json.php

$items = array("Pen", "Pencil", "Eraser", "Color Book");
$JSONdata = json_encode($items);
echo $JSONdata;
?>

Output:

Run the file from the browser.

http://localhost/json.php

Top

XML Usage

PHP has an extension named SimpleXML for parsing XML data. simplexml_load_string() is a built-in function of PHP to parse XML file. The following example shows how you can use simplexml_load_string() function to read data from XML content. Here, XML data are stored in a variable, $XMLData and $xml variable is used to read the data of $XMLData. After reading the data, the content is print as an array structure with data type.

xml.php

$XMLData =
"

Easy Laravel 5
W. Jason Gilmore
easylaravelbook.com
";
 
$xml=simplexml_load_string($XMLData) or die("Error in reading");
var_dump($xml);
?>

Output:

Run the file from the browser.

http://localhost/xml.php

Top

HTML Form Inputs

You can use different types of built-in array of PHP to read submitted form data based on the method attribute value of the form. You have to use $_POST array if the form data is submitted using POST method and you have to use $_GET array if the form is submitted using GET method. The following example uses POST method to submit the form data into the server. You have to create two files to test the following script. One is “login.html” and another is “check.php”. HTML file contains a form of two elements. These are username and password. The form data is submitted to check.php file by using post method. PHP script will check the submitted value of username and password. If the username is 'admin' and password is '1234' then it will print 'Valid user' otherwise it will print 'Invalid user'.

login.html




Username:

password:




check.php

if($_POST['username'] == 'admin' && $_POST['pwd'] == '1234')
echo "Valid user";
else
echo "Invalid user";
?>

Output:

Run the file from the browser.

http://localhost/login.html

If the username and password will not match then the following output will appear.

Top

get_browser function

get_browser() is a built-in function of PHP that is used to read all information related to the browser by reading browscap.ini file. The following script shows the output of this function in array format.
getbrowser.php

echo $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser();
print_r($browser);
?>

Output:

Run the file from the browser.

http://localhost/getbrowser.php

Top

Session storage

You can store session information in PHP by using $_SESSION array. PHP has many built-in functions to handle the session. session_start() function is used in the following script to start the session and two session values are stored in $_SESSION array.

session.php

session_start();
$_SESSION["name"] = "John";
$_SESSION["color"] = "Blue";
echo "Session data are stored.";
?>

Output:

Run the file from the browser.

http://localhost/session.php

Top

Server Request Method

It is mentioned earlier that PHP has many super global variables to handle server request. $_SERVER array is one of these variables that are used to get server information. The following script will print the filename of the executing script and the name of the running server.

serverrequest.php

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

Output:

Run the file from the browser.

http://localhost/serverrequest.php

Top

HTTP POST

HTTP protocol is used to communicate between the server and the client. Any browser works as a client to send HTTP request to the server and the server sends the response to the client based on the request. HTTP request can be sent by using POST and GET method. The following example shows the use of HTTP POST request in PHP. Here, an HTML form is designed to take height and width value of any rectangle and send to the server. $_POST array is used to read the values and calculate the area of the rectangle and print.
httppost.php




Height:


Width:




 


if( $_POST["ht"] || $_POST["wd"] )

$area = $_POST["ht"] * $_POST["wd"];
echo "The area of the rectangle is $area";

?>

Output:

Run the file from the browser.

http://localhost/httppost.php

If the user types 10 and 20 as height and width then the following output will occur.

Top

Sending Email

PHP has a built-in function named mail() for sending an email. It has four arguments. First three arguments are mandatory and last argument is optional. The first argument takes the receiver's email address, the second argument takes email subject, the third argument takes email body and forth argument takes header content. But this function works in the live server only. How you can use this function is shown in the following script.
email.php

$to = '[email protected]';
$subject = 'Thank you for contacting us';
$message = 'We will solve your problem soon';
mail($to, $subject, $message);
?>

If you want to send email from local server by using PHP then you can use PHPMailer class. You can visit the following tutorial link to know more about this class.

https://linuxhint.com/how-to-send-email-from-php/

Top

Class and Object

Object-oriented programming feature is added in PHP from version 5.  Class and object are the major parts of any object-oriented programming. A class is a collection of variables and methods and an object is an instance of a class.  How you can create and use a simple class and object is shown in the following example. Here, a class named Customer is defined with three public variables and one method. After creating the object named $custobj, variables are initialized by calling setValue method and printed later.
classobject.php

class Customer

//Declare  properties/variables
public $name;
public $address;
public $phone;
 
//Set the customer data
public function setValue($name, $addr, $phone)
$this->name = $name;
$this->address = $addr;
$this->phone = $phone;


// Create a new object of Customer
$custobj = new Customer;
// Set the properties values
echo $custobj->setValue("Alia","Dhaka, Bangladesh","+8801673434456");
// Print the customer value
echo "Name: ".$custobj->name."
";
echo "Address: ".$custobj->address."
";
echo "Phone: ".$custobj->phone."
";
?>

Output:

Run the file from the browser.

http://localhost/classobject.php

Top

Exception Handling

One of the important features of object-oriented programming is exception handling. Exception handling has two parts. These are try block and catch block. Try block contains the script and when any error appears in the script then an exception is thrown by try block to catch block.  A simple use of exception handling is shown in the following example. Here, try block will check the value of $number. If $number is greater than 9 then it will throw an exception with the message “You have to select one digit number” otherwise the script will print the value of $number with other text.
exception.php

$number = 15;
//try block
try
if($number > 10)
throw new Exception("You have to select one digit number
");

//Print the output if no exception occurs
echo "Selected number is $number
";

//catch exception
catch(Exception $e)
echo 'Error Message: ' .$e->getMessage();

?>

Output:

Run the file from the browser.

http://localhost/exception.php

Top

Conclusion

The basic PHP programming is explained in this tutorial by using 30 examples. If you want to learn PHP or want to become a web developer in the future then this tutorial will assist you to start writing scripts in PHP.

5 najlepszych ergonomicznych myszy komputerowych dla systemu Linux
Czy długotrwałe korzystanie z komputera powoduje ból nadgarstka lub palców?? Cierpisz na sztywne stawy i ciągle musisz uścisnąć dłonie? Czy czujesz pa...
Jak zmienić ustawienia myszy i touchpada za pomocą Xinput w systemie Linux?
Większość dystrybucji Linuksa jest domyślnie dostarczana z biblioteką „libinput” do obsługi zdarzeń wejściowych w systemie. Może przetwarzać zdarzenia...
Remap your mouse buttons differently for different software with X-Mouse Button Control
Maybe you need a tool that could make your mouse's control change with every application that you use. If this is the case, you can try out an applica...