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.

PHP fopen() – opening, creating a file

PHP fopen() function is used for opening a file or url in PHP. It can also be used for creating a file in PHP.We can use two parameters with this function. First parameter is for specifying the file name and second parameter is for specifying the mode for opening that file.

Syntax of the fopen() function is

$file=fopen(“file name”,”mode”);

for ex:

$file=fopen(“syam.txt”,”r”);

See the different opening modes used with fopen()

  • r : Open for read only, Start from the beginning of file
  • r+ : open for read and write , start from the beginning of file
  • w : Open for write only, if the file exists all the data will be removed and start from the beginning, if the file not exist – it will create the new file
  • w+ : Open for write and read, if the file exists all the data will be removed and start from the beginning, if the file not exist – it will create the new file
  • a : Open for write only , mainly for append operation, will point to the end of file , will create a new file if file not exist
  • a+ : Open for read and write, will point to the end of file , will create a new file if file not exist
  • x : create and open for write only , starts from the beginning of file, if the file exist E_WARNING error will occur, if the file does not exist it will create a new file
  • x+ : create and open for read and write, starts from the beginning of file, if the file exist E_WARNING error will occur, if the file does not exist it will create a new file

From this we can see that following modes are used for creating a file in PHP

  • a
  • a+
  • w
  • w+
  • x
  • x+

PHP date tutorial

PHP date() function is used for formatting the timestamps in a readable / customized format. date() function will accept an optional integer timestamp parameter and will return the formatted date according to the specified date or time on the parameter. If optional timestamp is not present, it will return the current time.

If optional parameter timestamp contains a non-numeric value date() function will return FALSE and E_WARNING level error.

Syntax of PHP date() function
date(string format, integer timestamp)

See the formatting characters used with date() function

format character Description Example returned values
Day
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase ‘L’) A full textual representation of the day of the week Sunday through Saturday
N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Month
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year
L Whether it’s a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Microseconds (added in PHP 5.2.2) Example: 654321
Timezone
e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) in hours Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00
T Timezone abbreviation Examples: EST, MDT
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Now watch the following sample PHP program with date() function and its output

<?php
echo "1 : ".date("Y-m-d")."<br>";
echo "2 : ".date("D M j G:i:s T Y")."<br>";
echo "3 : ".date("Y-M-D")."<br>";
echo "4 : ".date("y-m-d : H  :i : s")."<br>";
echo "5 : ".date("F j, Y, g:i a")."<br>";
?>

Its output will be:

1 : 2010-08-07
2 : Sat Aug 7 3:04:00 CDT 2010
3 : 2010-Aug-Sat
4 : 10-08-07 : 03 :04 : 00
5 : August 7, 2010, 3:04 am

You can check each formatting characters used with date function and its output and can understand whats happening easily.

Now let us consider a sample PHP program with integer timestamp with date function

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>

Its output will be :

Tomorrow is 2010/08/08

Here in timestamp we have given the integer timestamp for the next date , and date function is formatted that timestamp according to the formatting characters we have given.

PHP session tutorial

Using PHP session variable is a mechanism to store user’s data in server. And sessions will last till we are on the site, it will be destroyed when the user quit the site.
One main example of session usage is login information. When a user login to a site with his user name and password, sessions will be created for that user in server. By using these session variables servers and our PHP programs identify each user.

For each user session will create a unique ID , and other session variables and values are stored based on this ID.

How to start a PHP Session

For storing theWe need to start session before going to store any session variables and all. Function using for this is session_start(). It must be appear in our page before starting any output on the page. Better to use before our<html> tag.
Syntax for a PHP session start will be :
<?php session_start(); ?>

Storing a value in session
$_SESSION is the variable for session. We need to specify the the custom name for each session variable and value associated with that.
For example , if we want to store the user name and password of a user in PHP session, we can store like as below
$_SESSION[‘user_name’]=$username;
$_SESSION[‘password’]=$password;

Then user name will stored in the session variable $_SESSION[‘user_name’] and password will be stored in the session variable $_SESSION[‘password’]. And we can retrieve these values in any other pages for that domain as long as that user stay on that site.
See the sample program to create and retrieve the PHP session variables

<?php php session_start();?>
<html>
<?php
$username="syam";
$password="mysql";
$_SESSION['user_name']=$username;
$_SESSION['password']=$password;
?>
<body>
<?php
echo "Hi ".$_SESSION['user_name']. " Your password is ".$_SESSION['password'];
?>
</body>
</html>

Output of this program will be :
Hi syam Your password is mysql

Its better to check session variable is stored or not before retrieving its value for any operation to avoid any errors or other issues.
See the sample program with checking session exist or not for counting the page views of a visitor

<?php php session_start();?>
<html>
<?php
$username="syam";
$_SESSION['user_name']=$username;
if(isset($_SESSION['page_views']))
{
$_SESSION['page_views']=$_SESSION['page_views']+1;
}
else
{
$_SESSION['password']=1;
}
?>
<body>
<?php
echo "Hi ".$_SESSION['user_name']. " You have visited ".$_SESSION['page_views']." pages";
?>
</body>
</html>

In this example output will be :
Hi syam You have visited 1 pages
OR
Hi syam You have visited 2 pages
etc.. for each time he visit the page with this code his session value for page visit count will be increment by one. If its his first visit our session exist check will find that session is not existing and will assign the value 1, otherwise it will increment.

PHP Session Destroy

If we want to destroy the session, there are two functions are for this

  • unset()
  • session_destroy()

Difference between these two are

  • Using unset(0 function we can destroy one particular session variable for that user
  • using session_destroy() we can destroy all the sessions for that user

unset($_SESSION[‘username’]) will destroy only the session variable used for storing the username of that user. If we used session_destroy() function all the session variables including $_SESSION[‘username’] will be destroyed.

There are several other functions used with PHP session , we will discuss about those in our later posts.

PHP cookie tutorial with sample program

Cookie is a variable stored in the user computer. Its a mechanism to store the data for future use. Cookies are part of HTTP header and will passed to the server when the site is accessing in browser.
We can use cookies for knowing the return visitors or for storing a value in user computer. In PHP cookie is create using setcookie() function. And this function should be called in your PHP program before any output is sent to the user computer browser .
We can store multiple values in a single cookie by declare the cookie as an array ( using [] with cookie variable name ).
Here is the syntax for creating a cookie
setcookie (name, value, expiration time , path to store , domain name);

Consider a case. In our website there is a form to enter user’s name. And we need to store that name in his computer for next 30 days.
Now we need to plan a cookie name for this, and we decided to put the name as “user_name”.
Now this will be the sample PHP program to set a cookie in user computer

<?php
$name="syam";
$expire_time=time()+60*60*24*30;
setcookie("user_name", $name, $expire_time);
?>

Here for storing next 30 days, current time + time in seconds for next 30 days will store , ie time()+60*60*24*30.
And dont forget to put this setcookie() in top of your page , better to put before your HTML tags itself.

OK. Now we have stored a cookie. Next time we want to retrieve that cookie value in our website. See the sample program here for retrieving our stored cookie user_name.

<?php
echo $_COOKIE["user_name"];
?>

And its will output
syam

Its always better to check if cookie is set or not before doing any operation with that. See the code below for checking that.

<?php
if (isset($_COOKIE["user_name"]))
echo "Welcome back " . $_COOKIE["user_name"];
else
echo "Welcome guest";
?>

This code will check first cookie is exist or not in that machine. If exist it will do the next operations. Here it will output like “Welcome back syam” because we have already set a cookie for this name.

For Deleting a cookie , we need to change the expiration time to a past time. See the code

<?php
setcookie("user_name", "", time()-3600);
?>

Here this code will set the expiration to a past time one hour less than the current time.

PHP $_GET and $_POST functions with forms

$_GET Method  |  $_POST Method

There are two types of methods are available for a form to send data. They are “get method” and “post method”.

 

PHP $_GET function is used for collecting the values passed from a “form using get method”. When we use get method, passed variables and its values will be displayed in browser address bar and visible for everyone.

Here is sample form using get method

<form action="form.php" method="get">
Name: <input type="text" name="yourname" />
Age: <input type="text" name="age" />
<input type="submit" value="SUBMIT FORM" />
</form>

Here you can see that values are passed to form.php using get method.
Now look at the form.php code with $_GET function

<?php
$name=$_GET["yourname"];
$age=$_GET["age"];
echo "Name :".$name."<br>";
echo "age".$age;
?>

Suppose user has entered the values JOHN for name and 25 for age in the first form. After pressing the submit button, form will send the data to form.php . That time address bar will look like
form.php?yourname=JOHN&age=25
In form.php passed values are retrieved using $_GET function and output will be like:
Name : JOHN
age : 25

Limitations of GET method :

  • Maximum characters can be passed is limited, so its not suitable for sending large data
  • passed data will be visible in browser, so in some cases it wont be suitable to use get method like passing password and other secret datas.

Advantages of GET method :

  • User can bookmark or direct access to the page with passed data. Next time he don’t need to enter the form again to access the same page
  • Search engines can index the page with passed data. SEO friendly method

 

PHP $_POST function is usedd for collection the values passed from a “form using post method”.There are two types of methods are available for a form to send data. They are “get method” and “post method”. $_POST function is applicable for post method only.
When we use post method, passed variables and its values will be hidden in browser address bar and wont visible for the users.

Here is sample form using post method

<form action="form.php" method="post">
Name: <input type="text" name="yourname" />
Age: <input type="text" name="age" />
<input type="submit" value="SUBMIT FORM" />
</form>

Here you can see that values are passed to form.php using post method.
Now look at the form.php code with $_POST function

<?php
$name=$_POST["yourname"];
$age=$_POST["age"];
echo "Name :".$name."<br>";
echo "age".$age;
?>

Suppose user has entered the values JOHN for name and 25 for age in the first form. After pressing the submit button, form will send the data to form.php . That time address bar will look like
form.php only ( see the passed values are hidden )
In form.php passed values are retrieved using $_POST function and output will be like:
Name : JOHN
age : 25

Advantages of POST method :

  • There is no limit for Maximum characters can be passed, It depends on the post_max_size variable stetting in your php.ini file. So its suitable for passing large data
  • passed data will be hidden in browser, so its suitable for passing password like secret datas

Dis Advantages of POST method :

  • User cannot bookmark or direct access to the page with passed data. Next time we needs to enter the form again to access the same page
  • Search engines cannot index the page , because the passed values are hidden and cannot be accessible

PHP include file

We can include other files also in our PHP programs. Its for inserting the codes in other files in the current PHP program. Its a good practice to do make individual files with a piece of code which we need to use in several other pages of our project. Instead of writing the same codes in all pages we can include that file with the same code. Database connection code, reusable function and some global declarations , common header or footer or sidebar etc can be saved in a separate file , and we need to only include that file in the required page.

Here we are going to learn about various statements using for include a file.
There are mainly four statements are there for this in PHP

  • include
  • require
  • include_ once
  • require_ once

include” and “require” statements will simply add the contents of the includes file.Its usage is like include ‘filename’; or require “filename”;( dont forget to provide the exact path to the file)

“include_ once” and “require_ once” statements will do the same job as include and require execpt it will include the file only once. Means even if we have tried to include the file same file more than once in a page using any of these statements it will include only once.

Now we can look at the different between these statements

Difference between include and require

Both will do the same job when including a file. Difference is occurring when the file is missing. include statement will produce only a warning (E_WARNING) and continue the execution of script . But require statement will produce a fatal level error (E_COMPILE_ERROR) and stops the execution of program.

Share
Share