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.

PHP Switch case

PHP Switch case statement is an alternative for complex IF statements with a same expression. Its a best alternative for elseif statements using the same expression.
In many situations we need to compare a variable against different values and needs different operations according the values. Switch statement is coming for this requirement.

See the syntax structure of switch case statement in a PHP program

switch ($variable){

case $value1 :
Operation statements for this value1;
case $value2:
Operation statements for this value1;
case $value3:
Operation statements for this value1;
default:
Operation statements when there is no match in all the above cases;
}

Working of a switch case statement
switch statements is executed by line by line. No code will execute till the first match case found. After that it will execute all other case codes till a break statement found.Its really important to understand this behavior to avoid mistakes with this statement.

Usage of break statement in switch case
Break statement is used if we want to stop the execution of other cases when one case match with our condition.
See the difference in ouput for the following two sample programs

<?php
$i=1;
switch ($i) {
case 0:
echo " 0 ";
case 1:
echo " 1 ";
case 2:
echo " 2 ";
default:
echo " NO MATCH ";
}
?>

Its output will be
1 2 NO MATCH
Here we can see that, after the match case found ( in this case 1 ) all other case codes also executed. We need to use the break statement to avoid this.

<?php
$i=1;
switch ($i) {
case 0:
echo " 0 ";
break;
case 1:
echo " 1 ";
break;
case 2:
echo " 2 ";
break;
default:
echo " NO MATCH ";
}
?>

Its output will be ;
1
Here we can see that program stops the execution of other case statements due to the break statement in matched case.

Switch case statements supports strings also. See the following sample PHP program with switch case dealing with strings.

<?php
$i="PHP";
switch ($i) {
case "ASP":
echo " I hate ASP ";
break;
case "VB":
echo " Its good but I dont want ";
break;
case "PHP":
echo " I Love PHP ";
break;
default:
echo " NOTHING ";
}
?>

Its output will be :
I Love PHP
( Note : strings should be enclosed in double quotes)

call function in PHP

We can create our own function inside our PHP programs for re-usability and making our code optimization purposes. Functions are a block of codes executed only when calling. Codes inside a PHP function will execute when we call a function in PHP program.

We can create a function using the “function” statement. Its syntax will look like

function functioname()
{
Operation Codes here;
}

Here is a simple example of using a function in PHP

<?php
function message()
{
echo "Welcome to phpmysqlbrain.com";
}
$name="Guest";
echo "Hi ".$name." ";
message();
?>

Its output will be
Hi Guest Welcome to phpmysqlbrain.com
You can easily understand whats happening when we call that function.

Now we can look at some more deep about functions. We can use parameters to pass the values to a function. Also function can return the values ( results ).

See the following sample PHP program for passing a value to a function

<?php
function message($data)
{
echo "Hi ".$data." Welcome to phpmysqlbrain.com";
}
$name="Guest";
message($name);
?>

Its output will also same as our previous example
Hi Guest Welcome to phpmysqlbrain.com
Here we can see that we have passed the $name variable to the function message() . And function received that variable using the variable $data. Like this we can pass any number of parameters while calling a function.

Now watch the following sample PHP program with passing more than one parameters and return value from a function

<?php
function multiply($a,$b)
{
$result=$a * $b;
return $result;
}
$x = 10;
$y = 20;
$z = multiply($x,$y) + 1;
echo $z;
?>

Output of this program will be:
201

Here call multiply function passing the values $x and $ y. function multiply receiving these values with variables $a and $b accordingly. Then its doing the calculation parts and return the result.

Array in PHP tutorial

Array is a special variable which can store multiple value. ( Note : a normal variable can store only one value at a time ). Arrays are the oldest and most important data structure which can hold multiple values. Each value in an array is associated with a key. And we can retrieve each value from array using the keys.

Arrays can be mainly two types

  • One-dimensional arrays
  • Multidimensional arrays

Array in PHP can be categorized as

  • Numeric arrays
  • Associative array
  • Multidimensional array

In PHP array can be declared using the construct array()

Numeric arrays are with a numeric index. Here we don’t need specify the keys. Index will start from 0. Means first data can be accessed using the index 0 , second data can be accessed using the index 1 etc
See the Example for a numeric array declaration
$names=array(“Syam”,”Binu”,”Bob”,”cathy”);
Its same as the following declarations
$names[0]=”Syam”;
$names[1]=”Binu”;
$names[2]=”Bob”;
$names[3]=”cathy”;

In Associative arrays each key is associated with a value.Here we need to specify each key and its associated value. And these values can be fetched using the declared keys.
See the example of an Associative array declaration
$age = array(“Syam”=>30, “Binu”=>25, “Bob”=>50, “cathy”=>30);
Here Syam, Binu etc are the keys and values are associated with those keys using => .
In this example we are trying to store the ages of some persons using arrays. So if we want to know the age of one particular person , we only need to know his name ( key ).
The above array can be declared same as
$age[“Syam”]=30;
$age[“Binu”]=25;
$age[“Bob”]=50;
$age[“cathy”]=30;

In Multidimensional arrays each element in array can be another array. Its useful for building matrices, tree and table like data storage structures.In some programming scenarios we can avoid the usage of several different one-dimensional arrays using a single Multidimensional arrays for our programming optimization , speed and other things.

For example , consider a case we need to store names , age and location. We can use a multidimensional array. See below
$data=array (“Syam”=>array(“age”=>30,”location”=>”India”),
“Bob”=>array(“age”=>50,”location”=>”USA”) );

Here is a sample program of array in PHP ( using the above array )

<?php
$data=array ("Syam"=>array("age"=>30,"location"=>"India"),"Bob"=>array("age"=>50,"location"=>"USA")  );
echo $data["Bob"]["location"];
?>

Its output will be ;
USA

Adding line break using PHP

For the formatting purpose we need to add line breaks in our output or strings to store in MySQL tables and all. Here I am describing about various methods to add line break using PHP.

In HTML we can add a line break using <br> or <br /> tag.
For this purpose in PHP we need to simply echo that tag like following code

<?php
echo "syam is here<br>for teaching you PHP";
?>

Its output will be
syam is here
for teaching you PHP
( We can see that a line break is added after “syam is here”)

But in several other cases line break is applying using “n” or “rn”, like data storage in csv , txt files or mysql tables or data in a text area etc. In that cases we need to use function nl2br()
to convert the “n” into “<br>” tags to display line break.

See the sample PHP program for display line break using nl2br()

<?php
echo nl2br("syam is herenfor teaching you PHP");
?>

Its output also will be same as our previous PHP program
syam is here
for teaching you PHP
( we can see that “n” is decoded to <br> tag by nl2br() )

There is PHP_EOL constant available instead of using “n: or “rn”.

See the following sample PHP program with constant PHP_EOL

<?php
echo nl2br("syam is here".PHP_EOL."for teaching you PHP");
?>

Its output also will be same as our previous PHP programs
syam is here
for teaching you PHP
( here we can see that constant PHP_EOL is converted into line break using nl2br )

Most of the time we can use “<br>” tag itself for displaying the line breaks in our HTML contents or displaying areas. The other things will come under some advanced cases that we can understand in our later postings.

Share
Share