PHP html_entity_decode – convert to characters

PHP html_entity_decode function is used for covert the HTML entities to its corresponding characters.This function can be used for decode the string maid by htmlentities function.

Its Syntax Will be :
html_entity_decode ( String , Quote Style, Character Set ) ;
First parameter is the string to be converted to characters
Second paramters is an optional will , which will specify how to deal with Single and double quotes
Available quote styles are
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.

Third parameter is also optional, where we can specify the character set used in conversion

See a Sample PHP program using html_entity_decode function

<?php
$data="mysqlbrain's tutorials are very <b>good</b>";
$data_1 = htmlentities($data,ENT_QUOTES);
echo html_entity_decode($data_1);
echo "<br>";
echo html_entity_decode($data_1,ENT_QUOTES);
?>

Its output will be :

mysqlbrain’s tutorials are very good
mysqlbrain’s tutorials are very good

We can see that in html_entity_decode with ENT_QUOTES parameter convert the single quote html entity to character .

PHP htmlentities() – convert characters to html entities

PHP htmlentities function is used for covert the characters to its HTML entities. This function will automatically identify the characters which have an equivalent HTML entity , and then convert to it.

Its Synatx will be ;
htmlentities ( string , quote style , Character set );

First parametrer will be the string to convert
Second parameter is optional. Here we can specify how to deal with single quotes (‘) and double quotes (“)
Available quote styles are

  • ENT_COMPAT : Will convert double-quotes and leave single-quotes alone.
  • ENT_QUOTES : Will convert both double and single quotes.
  • ENT_NOQUOTES : Will leave both double and single quotes unconverted.

Third parameter is also optional , which defines the character set used in conversion. By default character set will be ISO-8859-1

Now look at some sample PHP programs using htmlentities function

<?php
$data="mysqlbrain's tutorials are very <b>good<b>";
echo htmlentities($data);
echo "<br>";
echo htmlentities($data,ENT_QUOTES)
?>

Now look at the source code of the ouput in browser , it will be

mysqlbrain’s tutorials are very <b>good<b>
mysqlbrain’s tutorials are very <b>good<b>

We can see that first htmlentities statement leaves the single quote , and second time it covert the single quote to html entity.

Its a good practise to use this function before storing the data to mysql tables. And we can use PHP html_entity_decode function to decode the string.

PHP search in array

In this tutorial we are going to learn how to search in array. In PHP we can use mainly two functions for this

  • in_array()
  • array_search()

PHP array search using in_array() function
This function will check the specified value is present in an array or not. It will return TRUE if the value is present in array, otherwise it will return FALSE
Its Syntax will be :
in_array(Value to search , array , strict Boolean);
First parameter will be the value to search in an array
Second parameter will the array to search
Third parameter is optional. If we specify it as TRUE function will check the type of value also. Type of the value should also match in the array value, then only it will return TRUE. By default this strict parameter will be FALSE ( wont check the type )
Now look at a sample PHP program using in_array search

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (in_array($key_search,$age))
{
echo "VALUE EXIST without strict parameter search";
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (in_array($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search";
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search
VALUE NOT PRESENT with strict parameter search

In this case we can see that without strict parameter function found the value in array. But when we used the strict parameter it will check the type also. Here we declared the value to search as a string , and in array the value is in type integer. So no match is there and the function will return FALSE.

PHP array search using array_search() function

This function will search for the specified value in an array and will return the corresponding key of the value if the search is successful.
Its syntax also similar to in_array:
array_search(Value to search , array , strict Boolean);

Now look at a sample PHP program using array_search function :

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (array_search($key_search,$age))
{
echo "VALUE EXIST without strict parameter search and its key is ".array_search($key_search,$age);
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (array_search($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search and its key is ".array_search($key_search,$age,TRUE);
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search and its key is Binu
VALUE NOT PRESENT with strict parameter search

Difference between these two functions:

  • array_search function will return the key or index
  • in_array function will return TRUE or false according to search match

PHP array_key_exists – checking a key exist in array

PHP array_key_exists function is used for checking a specified key or index exists in an array. It will return TRUE if the specified key exists in array or it will return FALSE if that key is not present in the array.Its using for a key search in an array. We don’t need to use loop through complete array and check each time with the key.Just need to use this function for this purpose.

Its Syntax will be :
array_key_exists function( Key value to search , array )

Now look at a sample PHP program with array_key_exists function for searching a key in array

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="Bob";
if (array_key_exists($key_search,$age))
{
echo "KEY EXISTS IN ARRAY";
}
else
{
echo "KEY CANNOT BE FOUND";
}
?>

Its output will be :

KEY EXISTS IN ARRAY

In this example our key is “Bob” and that key is there in the declared array. So our
array_key_exists() function will return TRUE in this example.

PHP mail() – send email

PHP mail() function is used for sending emails from your website.

Syntax of mail() function is :

  • mail (to email , Subject of email , email message , header , additional parameters );
  • Here First parameter will be the email address of the receiver
  • Second parameter will be the Subject ( title ) of your email
  • Third parameter will be the content of your email , you can use html tags and all for proper formatting
  • Third parameter is the header of your email, it will contain all the properties and setting for that email , sender email address also should specify in header , we can also add reply to address , format of email etc in header. Using detailed header is a good practice .

Sample of a header
$header = “From: from@gmail.comrnContent-type: text/htmlrnReply-To: from@gmail.com”;

In this header we have specified the from address, reply address and content type of the message.

Now look at a simple example of mail() function

<?php
$from="kssyam@gmail.com";
$to="to@gmail.com";
$subject="Test Mail";
$message="Hi ,<br />".
"This is my test email for learning how to send email using PHP mail function <br />".
"Thank You";
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In most of the cases we need to send email from a contact form in our website. Most of the business websites need this functionality , that their user can send and enquiry or messages by filling a contact form in their website.

Now look at a sample PHP program for sending email from a HTML contact form

Consider page contact.html contains the HTML contact form , and mail.php file contains the PHP scripts for sending email.
So contact.html will look like

<form method="post" action="mail.php" name="contact"><br />
Your name :<input type="text" name="username" /><br />
Email :<input type="text" name="useremail" /><br />
Message :<textarea cols="5" rows="5" name="message"></textarea><br />
<input type="submit" value="SEND EMAIL" name="submit" /><br />
</form>

When the user fills the data in form press SUBMIT button , the data is passed to the page mail.php where our mail(0 function is there . Now look at the code in mail.php

<?php
$username=$_POST['username'];
$from=$_POST['useremail'];
$to="to@gmail.com";
$subject="New Enquiry from ".$username;
$message=$_POST['message'];
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In this case, when a user submit the data an email will sent to “to@gmail.com” with a subject like “New Enquiry from JOHN” and content which is typed by the user in form.

This is only a basic introduction tutorial about mail function in PHP. In our later posts we will learn to send attachments and other advanced headers along with email.

PHP explode() – split a string by string into array

PHP explode() function is used for split a string by another string into an array. This function is used when we need to split a string using a specific character or string present in that string.
Its Syntax will be :
explode (delimiter string , string to explode , LIMIT );

Here delimiter string will declare at which string occurrence the split process should happen . And LIMIT is an optional parameter for specifying the maximum count of splitting. If we specify LIMIT parameter , maximum number of splitting will be the LIMIT value and the rest of string will be the last element in array.

We will get more clear picture about explode() function after seeing some examples.

Sample PHP program using explode() function

<?php
$data="How to split a string using explode";
$splittedstring=explode(" ",$data);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = How
splittedstring[1] = to
splittedstring[2] = split
splittedstring[3] = a
splittedstring[4] = string
splittedstring[5] = using
splittedstring[6] = explode

Here , we are trying to split the string at blank spaces with out optional parameter LIMIT value. And we can see that string is split at the positions where blank space occurred and stored in the array $splittedstring. We can retrieve the values splittedstring[0] for first split string and splittedstring[1] for the second part etc..
Here in this example I am looping through the array and output all the results.

Now look at a sample program with optional parameter LIMIT count with explode()

<?php
$data="How to split a string using explode";
$splittedstring=explode(" ",$data,3);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = How
splittedstring[1] = to
splittedstring[2] = split a string using explode

Here we can see that optional parameter is specified as 3 as limit count. So the string is split to three parts and last part contain the rest of the original string.

Now look at the next sample PHP program with explode() function

<?php
$data="http://www.youtube.com/watch?v=ZR0iBvof3MA";
$splittedstring=explode("?v",$data);
echo "Video ID is ".$splittedstring[1];
?>

Output will be :

Video ID is =ZR0iBvof3MA

Here we trying to split a youtube video url by a string ?v for getting its video id.

Optional parameter with negative value:
If we specified -LIMIT , then the last LIMIT number of splitted results wont return.
See the flowing example and its output for understand whats happening

<?php
$data="ONE TWO THREE FOUR FIVE";
$splittedstring=explode(" ",$data,-2);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = ONE
splittedstring[1] = TWO
splittedstring[2] = THREE

Here we can see that it wont store the last two components ( FOUR and FIVE ) in array.

PHP trim() – Remove whitespace from string

PHP trim() function is used for removing the white space or other characters from starting and end of a string. Its used for formatting data properly. In some cases unnecessary whitespaces may be there in the beginning or end of a string, we can use this function to remove those blank spaces.

trim() function has an optional parameter for specifying the character to remove.
Its Syntax will be :
trim(string to be trimmed , character to remove );


By default it will remove the following character from the beginning and end of a string

  • ” ” :  an ordinarywhite space.
  • “t” : a tab.
  • “n” :  a new line.
  • “r” : a carriage return.
  • “” : the NUL-byte.
  • “x0B” :  a vertical tab.

See the sample PHP program using trim function without parameter

<?php
$data=" how to remove blank spaces  ";
$data1=trim($data);
echo $data.":<br>";
echo $data1.":<br>";
?>

Now check the display result source code in browser , we can see

 how to remove blank spaces  :<br>how to remove blank spaces:<br>

Here we can see that $data contain whitespaces at the starting and end , and $data1 doesn’t contain those things ( our trim function has removed that )…

By default output in browser we wont feel any difference between these data because browsers will automatically trim the data for output . Thats why we need to check the source code in browser for the real values.

Now we can write another program using trim function with parameter

<?php
$data="how to remove blank spaces how";
$data1=trim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>

Its output will be :

how to remove blank spaces how:<br> to remove blank spaces :<br>

Here we have specified “how” as optional parameter with trim function and “how” is removed from the beginning and end of the string.

There is two more trim function available
ltrim() : Left trim only; Will remove only from the beginning of a string ( starting )
rtrim() : Right trim only will remove only from the end of a string

Rest everything is same as trim() function.

See the sample php program with ltrim() function

<?php
$data="how to remove blank spaces how";
$data1=ltrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>

Its output will be :

how to remove blank spaces how:<br> to remove blank spaces how:<br>

Here we can see that “how” is removed from the beginning of string and “how” at end remains

Now look at the program with rtrim()

<?php
$data="how to remove blank spaces how";
$data1=rtrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>

Its output will be L

how to remove blank spaces how:<br>how to remove blank spaces :<br>

Here we can see that “how” is removed from end only, the beginning “how” remains in the ouput string .

We can use any of these function for remove the un necessary whitespaces or characters from the end or beginning or from both as per our requirement.
And note trim() = rtrim() + ltrim() in action.

File Upload in PHP

It is very important to know how to upload a file in PHP.File upload in PHP can used for uploading any types of files from a user computer to server. First it will store the file to a temporary folder in server and this file will be deleted when the user exist the script ( leaving that page ). And we can move that file to a permanent folder in server using move_uploaded_file() function.

First see how a HTML form will look like for file upload

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileupload" id="file" />
<input type="submit" name="submit" value="Upload file" />
</form>

This form will call the file upload.php where we will write the PHP scripts for handling this file upload.

$_FILES array :
$_FILES variable array will contain all the information about the uploaded file like its name, type, size and error codes.
See the different syntax and usage :

  • $_FILES[“form field name for file”][“name”] : It will contain the name of the uploaded file
  • $_FILES[“form field name for file”][“type”] : It will contain the mime type of the uploaded file
  • $_FILES[“form field name for file”][“size”] : It will contain the size of the uploaded file
  • $_FILES[“form field name for file”][“tmp_name”] : It will contain the name with path of the temporary folder in the server.

Now we can write a sample PHP program using the same html form above

<?php
if ($_FILES["fileupload"]["error"] > 0)
{
echo "Error code when upload: " . $_FILES["fileupload"]["error"] . "<br />";
}
else
{
echo "Upload file name : " . $_FILES["fileupload"]["name"] . "<br />";
echo "Type of the file: " . $_FILES["fileupload"]["type"] . "<br />";
echo "Size of the file in KB: " . ($_FILES["fileupload"]["size"] / 1024) . "<br />";
echo "Stored in temporary folder : " . $_FILES["fileupload"]["tmp_name"];
}
?>

Its only a temporary storage now, the file will be deleted when we quit the script. If we need to store the file in server for later use, we need to move that file from temporary folder to a permanent folder ( lets us take a folder “uploads” for this example ). Syntax of the move_uploaded_file(0 function is like
move_uploaded_file( source file, destination file )

Now watch the sample PHP program for file upload to a server and store the file to a permanent folder uploads

<?php
if ($_FILES["fileupload"]["error"] > 0)
{
echo "Error code when upload: " . $_FILES["fileupload"]["error"] . "<br />";
}
else
{
echo "Upload file name : " . $_FILES["fileupload"]["name"] . "<br />";
echo "Type of the file: " . $_FILES["fileupload"]["type"] . "<br />";
echo "Size of the file in KB: " . ($_FILES["fileupload"]["size"] / 1024) . "<br />";
echo "Stored in temporary folder : " . $_FILES["fileupload"]["tmp_name"];
move_uploaded_file($_FILES["fileupload"]["tmp_name"],"uploads/".$_FILES["file"]["name"]);
}
?>

Now our uploaded file is stored in the folder named “uploads” in server.

And this is only a basic introduction about file upload, normally we need to do several other checking and operations before the file upload as per the program requirement. For example if its an image upload section in site, we need to check the uploaded file type is image before storing. And we can restrict the maximum size using the $_FILES[“form field name for file”][“size”] variable. And we can also rename the file before storing. I will explain those things in later posts.

PHP fread() – reading a file

PHP fread() function is used for reading contents of a file. It read from the file stream pointed to by handle which is created by fopen() function.
Syntax of the PHP fwrite function :
fread( file handler, length )

Length is a parameter to specify how many bytes to be read. Read will stop at the specified length is reached.

PHP fread() statement is binary-safe , means both binary and character data can be read from a file.

Here is a sample PHP program for reading from a file using fread() function

<?php
// First we will create a file syam.txt and write a string into that
$file = fopen("syam.txt","w");
fwrite($file,"Here You can learn about how to write to a file");
fclose($file);
// Now we are going to read the contents of the created file and display the contents
$file_1 = fopen("syam.txt","r");
$data=fread($file_1,filesize("syam.txt"));
echo $data;
fclose($file_1);
?>

Its output will be :

Here You can learn about how to write to a file

This is only a basic introduction tutorial about reading a file using PHP. We will discuss more about in our later posts.

PHP fwrite() – writing to a file

PHP fwrite() function is used for writing contents to a file. It write to the file stream pointed to by handle which is created by fopen() function.

Syntax of the PHP fwrite function :
fwrite( file handler, string to write , length )

Length argument is optional , and if we specify a length parameter write will stop when it write will reach to that length bytes.

PHP write() statement is binary-safe , means both binary and character data can be written to a file.

Here is a sample PHP program for writing to a file using fwrite() function

<?php
$file = fopen("syam.txt","w");
fwrite($file,"Here You can learn about how to write to a file");
fclose($file);
?>

This program will create syam.txt if not exist using fopen statement and write the string “Here You can learn about how to write to a file” into that file using the handler $file and fwrite() statement.

Its only a basic tutorial about writing to files. We will discuss more about this in our later posts.

Share
Share