PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

22 Jul 2014

Create Registration / Sign up form using PHP and Mysql

                                If you want to add login form to your websites, then you need to add sign up  or registration form in order to get values from user and store it into Mysql database. Your registration form should be made in HTML and the values are stored in Mysql using PHP. Lets see create the registration form in PHP , Mysql, HTML.

1. Create Database


                               First you need to create database to store user values. You need to use below Mysql query to create database in your phpmyadmin.

            Create database db_name

     ie,
             Create database new

where new is my database name

                               Then you've to use below Mysql query for use created database.
         
             Use db_name
   
    ie,

             Use new


2. Create table in Mysql database


                               After created database, you need to create table for store users values. You can create table using below Mysql query.

             create table login (name varchar(30),password varchar(30),mail varchar(50))

                              Now  you can see created table is presented in your database.

3. Create registration form in HTML


                              After finished database and table creation, you need to create front end design which can be viewed by users. ie, client side script. Using below HTML code to create registration form in HTML.

<form action="#" method="post">
      <table id="tbl" align="center">
       <tr><td>Name:</td><td><input type="text" name="name" id="name"></td></tr>
       <tr><td>Password:</td><td><input type="text" name="password" id="password"></td></tr>
  <tr><td>Email:</td><td><input type="text" name="mail" id="mail"></td></tr>
       <tr><td></td><td><input type="submit" name="submit" id="submit" value="Submit"></td></tr>
      </table>

     </form>

4. Add styles to registration form


                            After created form in HTML, it should not be present user attractable one. So you need to add CSS styles to HTML form in order to make form colorful. Just add below CSS codes to your html form.

 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
width:520px;
 }
 #name, #password, #mail {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;

}


5. Form validation in javascript


                                 After add CSS to your form, you've to validate your form using javascript or jquery.  You can validate empty textbox, validate valid email id and valid phone number using below javascript. Add below javascript validation to your HTML form.

$(document).ready(function() {
$('#submit').click(function() {
var name=document.getElementById('name').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var chk = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(name=='')
{
 $('#er').html('Enter your name');
 return false;
}
if(password=='')
{
 $('#er').html('Enter your password');
 return false;
}
if(mail=='')
{
 $('#er').html('Enter your mail');
 return false;
}
if(!chk.test(mail))
{
 $('#er').html('Enter valid email');
 return false;
}
});

});


6. Connect Mysql database using PHP


                                     Then you need to write server side script to store values into database. First you make connection to Mysql database to store user values using PHP. Visit How to connect Mysql database using PHP. Add below PHP codes

  mysql_connect('localhost','root','') or die(mysql_error());
  mysql_select_db('new') or die(mysql_error());


7. Add PHP code for store values into database


                                     Here is the PHP code for insert user data into Mysql database. This is the code for avoid duplicate entries in table. visit How to avoid duplicate values storing in Mysql table while inserting using PHP

  $name=$_POST['name'];
  $password=$_POST['password'];
  $mail=$_POST['mail'];
  $q=mysql_query("select * from login where name='".$name."' or mail='".$mail."' ") or die(mysql_error());
  $n=mysql_fetch_row($q);
  if($n>0)
  {
   $er='The username name '.$name.' or mail '.$mail.' is already present in our database';
  }
  else
  {
   $insert=mysql_query("insert into login values('".$name."','".$password."','".$mail."')") or die(mysql_error());
   if($insert)
   {
    $er='Values are registered successfully';
   }
   else
   {
    $er='Values are not registered';
   }

  }

8. PHP script for register values into Mysql database


                                        Now you combine all above codes to single PHP file. Then you'll get code like below one. visit How to insert values into Mysql database using PHP.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
width:520px;
 }
 #name, #password, #mail {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body>
<?php
 error_reporting('E_ALL ^ E_NOTICE');
 if(isset($_POST['submit']))
 {
  mysql_connect('localhost','root','') or die(mysql_error());
  mysql_select_db('new') or die(mysql_error());
  $name=$_POST['name'];
  $password=$_POST['password'];
  $mail=$_POST['mail'];
  $q=mysql_query("select * from login where name='".$name."' or mail='".$mail."' ") or die(mysql_error());
  $n=mysql_fetch_row($q);
  if($n>0)
  {
   $er='The username name '.$name.' or mail '.$mail.' is already present in our database';
  }
  else
  {
   $insert=mysql_query("insert into login values('".$name."','".$password."','".$mail."')") or die(mysql_error());
   if($insert)
   {
    $er='Values are registered successfully';
   }
   else
   {
    $er='Values are not registered';
   }
  }
 }
?>
<div class="contact">
<h1>Registration Form</h1>
     <div id="er"><?php echo $er; ?></div>
     <form action="#" method="post">
      <table id="tbl" align="center">
       <tr><td>Name:</td><td><input type="text" name="name" id="name"></td></tr>
       <tr><td>Password:</td><td><input type="text" name="password" id="password"></td></tr>
  <tr><td>Email:</td><td><input type="text" name="mail" id="mail"></td></tr>
       <tr><td></td><td><input type="submit" name="submit" id="submit" value="Submit"></td></tr>
      </table>
     </form>
</div>

<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var name=document.getElementById('name').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var chk = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(name=='')
{
 $('#er').html('Enter your name');
 return false;
}
if(password=='')
{
 $('#er').html('Enter your password');
 return false;
}
if(mail=='')
{
 $('#er').html('Enter your mail');
 return false;
}
if(!chk.test(mail))
{
 $('#er').html('Enter valid email');
 return false;
}
});
});
</script>
</body>

</html>

                            When you run this file, your screen should be like this:


Create sign up form using PHP and Mysql



                  For example, you'll try to store values guru, guru, guruparthiban19@gmail.com, then your screen like below:

Insert values into Mysql database using PHP


             After enter submit button, the values are registered in Mysql database. Now you can see the values are present in yout table.





Mysql login table


               You will get error message when you tried to insert same values again. This is below

Duplicate entry error message while inserting using PHP and Mysql


                   Now your table contains user details. So you can add login form to validation user name and password of users.

Related Post:
Login form validation using PHP and Mysql
Login form validation with remeber me function using PHP and Mysql
Send forgot password to mailin login form using PHP and Mysql

15 Jul 2014

Create excel spreadsheet using PHP and Mysql

                       You can generate excel spreadsheets easily using PHP. You need to follow below steps to create excel file.

Add content type:


                    First you need to add excel sheet content type to create excel file using PHP.

header("Content-Type: application/vnd.ms-excel");

Add name and download excel file:


                    You can provide name for excel spreadsheet and make your sheet as downloadable file on coding. The Content-Disposition is used to force browser to save a file. For that, your file should be attached following line:

header("Content-disposition: attachment; filename=spreadsheet.xls");

Add content to excel spreadsheet:


                   Finally you can add contents to your excel file. Consider the following PHP script for generate excel file:

<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('new') or die(mysql_error());
$q=mysql_query("select * from table1")  or die(mysql_error());
if(mysql_num_rows($q)>0)
{
echo"<table><tr><th>Name</th><th>Address</th><th>Phone</th></tr>";
 while($res=mysql_fetch_array($q))
 {
  echo"<tr><td>".$res['name']."</td><td>".$res['address']."</td><td>".$res['phone']."</td></tr>";
 }
echo"</table>";
}
?>

     Where,
                 mysql_fetch_array() return values as both an associative and numeric array.
                      while executing file, it required you to save excel file. After save file, you can view it. Now you got excel spreadsheet with named spreadsheet.xls which is created by PHP.

Related Post:
How to fetch result from mysql table using mysql_fetch_array in PHP
Create json file using PHP and MySQL
PHP : Parse data from XML Sitemap using simplexml_load_file and file_get_elements
Read data from JSON file using PHP
Parse data from XML file using PHP

13 Jul 2014

Send forgotten password to mail in login form using php and mysql

                       Already you know about validate login form with remember me and signout concepts using php. You want to know Login with remember me and signout using php and mysql
                       Now see about how to send forgotten password to mail using php?. First your table contains users mail id. Just imagine this is your table:


Mysql login table

Login form using php and mysql:

         
          Consider the following example:
login.php:

<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
span{
  color:lightgreen;

 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='checkbox' name='remember' /> <span>Remember me</span></td></tr>
<tr><td></td><td> <span><a href="forgot.php">Forgot password</a></span></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
//your values are stored in cookies, then you can login without validate
if(isset($_COOKIE['name']) && isset($_COOKIE['pwd']))
{
    header('location:welcome.php');
}
// login validation in php
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new')  or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."' ")  or die(mysql_error());
   $res=mysql_fetch_row($query);
   if($res)
   {
    if(isset($_POST['remember']))
{
  setcookie('name',$name, time() + (60*60*24*1));
  setcookie('pwd',$pwd, time() + (60*60*24*1));
}
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>


             While you run the above file, you'll get output like this:


Login form using php

Fogot password in php:


                 The php script for send forgotten password to mail is:
forgot.php:


<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }

</style>
</head>
<body>
<h1>Forgot Password<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>Email id:</td><td><input type='text' name='mail'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>
</form>
<?php
if(isset($_POST['submit']))

 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $mail=$_POST['mail'];
 $q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
 $p=mysql_affected_rows();
 if($p!=0) 
 {
  $res=mysql_fetch_array($q);
  $to=$res['mail'];
  $subject='Remind password';
  $message='Your password : '.$res['password']; 
  $headers='From:guruparthiban19@gmail.com';
  $m=mail($to,$subject,$message,$headers);
  if($m)
  {
    echo'Check your inbox in mail';
  }
  else
  {
   echo'mail is not send';
  }
 }
 else
 {
  echo'You entered mail id is not present';
 }
}
?>
</body>
</html>

         Where,
                 mysql_query("select * from login where mail='".$mail."' "); is select the values from mysql table.
                 mysql_affected_rows() return the number of rows selected. If it returns 0, then there is no values is present in mysql table.
                 mysql_fetch_array() return the results an associated array. You want to know mysql_fetch_array().
                  Mail() is used to send password to mail. Yow want to know mail() in php.

              When you click the 'forgot password' in login page, you'll get output like this:

Forgot password in php

                You entered your email id in text box and click submit button. Now you can get message 'Check your inbox in mail' if the mail is send. Otherwise, you'll get 'Mail is not send' message. If you enetered mail id which is not present is mysql table, then you will get 'You entered mail is is not present' message.

7 Jul 2014

Validate login form with remember me using php and mysql

                      All of you know the simple login validation concepts in php. Otherwise visit login validation using php. Now see about login form with remember me concept in php. You can remember the user using cookies concept in php.
                     When you click the remember me check box, your name and password is stored in cookie. Though you signout and close the browser, you can login again while open page in browser. Your name kept by cookie until expire the time or you clear the cache in your browser.

Remember me in login form using php:


                     Consider the following example. You have 3 php pages such as login.php, welcome.php and signout.php.

login.php:


<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
span{
  color:lightgreen;

 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='checkbox' name='remember' /> <span>Remember me</span></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
//your values are stored in cookies, then you can login without validate
if(isset($_COOKIE['name']) && isset($_COOKIE['pwd']))
{
    header('location:welcome.php');
}
// login validation in php
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."' ");
   $res=mysql_fetch_row($query);
   if($res)
   {
    if(isset($_POST['remember']))
{
 setcookie('name',$name, time() + (60*60*24*1));
 setcookie('pwd',$pwd, time() + (60*60*24*1));
}
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>

             where,
            if(isset($_COOKIE['name']) && isset($_COOKIE['pwd'])) {} means if the user values in  cookies, then the user can login directly without login validation in php.
         
           if(isset($_POST['remember'])){
           setcookie('name',$name,time() + (60*60*24*1));
           setcookie('pwd',$pwd,time() + (60*60*24*1));
           }
           which means, if the user click the remember me check box, then you have to store them in cookie. If you don't know  about cookies in php, then visit Cookies in php.

          When you run the login.php fille, you'll get output like this:

validate remember me concept in login form using php

welcome.php:


<?php    
  session_start();
  if(isset($_COOKIE['name']))
  {
    echo 'Welcome: '. $_COOKIE['name'].'<br>';
  }
  else
  {
    echo 'Welcome: '. $_SESSION['name'].'<br>';
  }
  echo'<a href="signout.php">Singout</a>';
?>

      where,
                  if(isset($_COOKIE['name'])){}else{} means if the values in cookie, then return name from cookie. Otherwise name return from session.
             Now you enter username and password  'guru' and 'guru' without select the remember check box, you will navigate to 'welcome.php' page and get output like this:

                   welcome: guru
                   Signout

 If it is wrong, then you can't login.

   

Signout in php:           


            When you click the signout.php, it destroy the session and return back to login page. The php script for signout page:
signout.php:

<?php    
         session_start();
         session_destroy();
         header('location:login.php');
?>

           You select the remember me check box while login. Then you navigate to welcome.php page. Now you click the signout on welcome.php page, you can't return back to login page. Because the concept is, when you signout the page, you return back to login.php page, where you wrote the php script as like as:
          
                  if(isset($_COOKIE['name']) && isset($_COOKIE['pwd'])) {}

It means, if values in cookie, you can login again. Now you comes to login page and again login and navigates to welcome page because your values in cookies.So you are in welcome page until the cookie is expired.

Related Post:
Create Registration form using PHP and MySQL
Simple login form validation using php and mysql
Forgot password to mail in login form validation using PHP and Mysql

6 Jul 2014

Login validation using php and mysql

                      Everybody should see the login pages in most of websites. You should have doubt about this login form, how they validate username and password. There is nothing, just only 2 steps as follows as for login validation using php.
                      1. You enter username and password already registered which is stored in mysql database.
                      2. After you submit a button to login, it check the database values whether the username and password is correct or not using php and mysql query. The mysql query for select a values from mysql database as like this:
             
             ie, SELECT * FROM table_name WHERE name='username' and password='password' 

If it return values correctly, then you can login. Otherwise it give error message.

Simple login validation using php and mysql: 


                      Lets see how to validate the username and password using php.
                      1. First you create table using mysql query like this:

           CREATE TABLE login(name varchar(30), password varchar(30), PRIMARY KEY(name))

Now the table 'login' is created. The field 'name' is primary key. Because the username must be unique.
                      2. Then insert values into table using  mysql query like this:

           INSERT INTO login VALUES('guru','guru') 

Now the table look like this:

login validation using php

                       3. The php script for login validation as follows as:
login.php:

<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."'") or die(mysql_error());
   $res=mysql_fetch_row($query);
   if($res)
   {
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>


        Where,
                if(isset($_POST['submit']){}    means run after submit a results.
                if($name!=''&&$pwd!=''){}   means if either username or password is empty, it give message like as 'Enter both username and password'.
                mysql_query("select * from login where name='".$name."' and password='".$pwd."'  ")      select the values if the username and password is present.
                $res=mysql_fetch_row($query) return row as numeric array.
You don't know about mysql_fetch_row, then visit mysql-fetch-row in mysql.
               if($res){} validate the result. If it is correct, then your name is stored in session variable and also you'll navigate to 'welcome.php' page. Otherwise you'll get 'You entered username or password is incorrect' message. You want to visit Session in php.
              When you run the above file, it should be like this:

login form in html and php
             
               The php script for welcome page:

 welcome.php:


<?php    
         session_start();
         $name=$_SESSION['name'];    
         echo'welcome :'. $name.'<br>';
         echo'<a href="signout.php">Signout</a>';
?>

      
             Now you enter username and password  'guru' and 'guru', you will navigate to 'welcome.php' page and get output like this:

                   welcome: guru
                   Signout

 If it is wrong, then you can't login.


Signout in php:              


            When you click the signout.php, it destroy the session and return back to login page. The php script for signout page:
signout.php:

<?php    
         session_start();
         session_destroy();
         header('location:login.php');
?>

                session_destroy is used to destroy the session variable in php.

Related Post:
Create Registration form using PHP and MySQL
Login form validation with remember function using php and mysql
Forgot password to mail in login form validation using PHP and Mysql

2 Jul 2014

Create sitemap dynamically using PHP and MySQL

                         Do you know why you need to add sitemap into you websites? what is the use of sitemap? Let see here to solve all of your doubts about sitemap.

Sitemap:


                         Sitemap is very important for all websites. All of you know, the search engines like google, bing are crawling pages on your websites to know about websites. Using this sitemap, webmasters to inform search engines about pages for crawling. Sitemap is a XML file which contains all url of your websites upto to date. If you add new page to your site, then you'll add url of new page to sitemap for crawling.

                          Sitemap is also provide url structure of websites. Suppose a new user comes to your websites. The sitemap leads new user to all pages on your site.

Structure of sitemap: 


                    The structure of sitemap is:

<?xml version="1.0" encoding="UTF-8">
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://www.phponwebsites.com</loc>
<lastmod>today date<lastmod>
<changefreq>daily</changefreq>
<priority>1</priority>
  </url>
  <url>
    <loc>http://www.phponwebsites.com/p/htaccess.html</loc>
<lastmod>today date<lastmod>
<changefreq>daily</changefreq>
<priority>1</priority>
  </url>
 </urlset>

  where,
      urlset - encapsulates the file ie, start sitemap
      url - parent tag for each entry ie, each page
      loc - location of url
      lastmod - date for last modification of file
      changefreq -  how frequently the pag is changed. It should be always, hourly, daily, monthly, weekly, yearly, never
      priority - priority of url. It should be between 0.0 to 1.0

Create sitemap dynamically using PHP and MySQL:


                          First you need to add content type for xml to generate sitemap in PHP. ie,

 header ("content-type: text/xml");


                        Then add contents to XML file. Then save this file as sitemap.php .


<?php
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $dat=date('Y-m-d');
 header ("content-type: text/xml");
 echo '<?xml version="1.0" encoding="UTF-8"?>
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
 $urls=mysql_query("select * from url")or die(mysql_error());
 while($row_Tags=mysql_fetch_array($urls))
 {
   echo "<url><loc>".$row_Tags['url']."</loc><lastmod>".$dat."</lastmod><changefreq>daily</changefreq><priority>1</priority></url>";
 }
  echo "</urlset>";
 ?>


.htaccess:

               
               In your .htaccess, you add following codes.

RewriteRule ^sitemap.xml sitemap.php [L]

                   When you run sitemap.xml on your website each time,  it display upto date contents.

Related Post:

25 Jun 2014

How to store array values into cookies in PHP

                      Cookies can store only string values. It can't store array values. But we are try to add array values into cookies in PHP.

Store array into cookies in php using serialize():

                           
                    Consider the following PHP script:


<?php
error_reporting('E_ALL ^ E_NOTICE');
$val=array('name'=>'Guru','country'=>'USA');
$val1=serialize($val);
setcookie('values',$val1);
?>

             Where,
                serialize() - Generate a storable values. Suppose you use above PHP code without serialize array value. Then you'll get error like this:

Store array values into cookies in php

After serialize the array values, you can store array values into cookies using setcookie() in PHP.
Now the cookie contains array values.

Retrieve array values from cookies in PHP using unserialize():

                       
                     Consider the following example:

<?php
error_reporting('E_ALL ^ E_NOTICE');
$val=array('name'=>'Guru','country'=>'USA');
$val1=serialize($val);
setcookie('values',$val1);
$dat=$_COOKIE['values'];
$data=unserialize($dat);
foreach($data as $key => $vl)
{
   echo $key.' : '.$vl.'<br>';
}
?>

           Where,
                     unserialize() - takes serialized values and converts it into PHP value again. If you didn't use unserialize() in above PHP code, then you'll get error like this:

Retrieve array values from cookies in php

$_COOKIES[''] is used to retrieve values from cookies.
Now you can get array values from cookies. The output is:

                 name : Guru
                 country : USA


Store multiple values into cookies in PHP using json_encode():


                         You can also store multiple values into cookies using json_encode() method in PHP.
json_encode()  returns JSON representation of a value.  Consider the example:

<?php
$val=array('name'=>'Guru','country'=>'USA');
$ar=json_encode($val);
setcookie('cook',$ar);
?>

                      After encoded the array values, you can store it into cookies. If you use above code without json_encode(), then you'll get warning error message.

Retrieve array values from  cookies in PHP using json_decode();


                      You can retrieve array values from cookies using json_decode() like unserialize() in PHP.
json_decode()  takes JSON encoded values and convert it into PHP value again. Consider the example:

<?php
$val=array('name'=>'Guru','country'=>'USA');
$ar=json_encode($val);
setcookie('cook',$ar);
$return=$_COOKIE['cook'];
$arr=json_decode($return, true);
foreach($arr as $key1 => $values)
{
  echo $key1.' : '.$values.'<br>';
}
?>

Now you can get output like this:
        
                 name : Guru
                 country : USA

Related Post:

23 Jun 2014

How to store array values into session in php

                You can store single value to session in PHP easily. Visit store values to session in php.


Store array values to session in PHP:


                          You can also store multiple values into session using PHP. You can store one or more than one values in array that can be stored into session. Consider the following example. It describes the array values directly stored into session in PHP. The following PHP script is used to store values to session in PHP.

<?php
 session_start();
 $ar=array('php','mysql','jquery');
 $_SESSION['arr']=$ar;
 $session=$_SESSION['arr'];
 foreach($session as $val)
 {
   echo $val.'<br>';
 }
 ?>

 where,
            session_start() - start the session
            $ar=array() - array variable

                  Now you can get output like this:

                                    php
                                    mysql
                                    jquery

Store multiple (array) values into session in PHP on form submit:

                          Consider the following example:


 <html>
 <body>
 <?php
 session_start();
 error_reporting('E_ALL ^ E_NOTICE');
 if($_POST['submit'])
 {
  if(count($_SESSION['arr'])==0)
  {
   $ar=array();
   $val=$_POST['value'];
   array_push($ar,$val);
   $_SESSION['arr']=$ar;
   print_R($_SESSION['arr']);
  }
  else
  {
   $val=$_POST['value'];
   array_push($_SESSION['arr'],$val);
   print_R($_SESSION['arr']);
  }
 }
?>
 <form action="#" method="post">
  <input type="text" name="value">
  <input type="submit" name="submit" value="Submit">
 </form>
 </body>
 </html>


                    The above example describes array values are storing into session in PHP while form submitting.
            where,
                      if(count($_SESSION['arr'])==0) {} - check  whether the array contains values or not. Create array variable and store value into array, then value is stored into session if there is no values in session. Otherwise it directly add values into session.
                     array_push() - add values to array in PHP.

Related Post:

16 Jun 2014

4 Types of errors in php

                       Errors will occur for following reason in php:
                              1.unclosed quotes,
                              2.missing semicolon,
                              3.missing parentheses,
                              4.add extra parentheses,
                              5.unclosed braces,
                              6.undefined variable,
                              7.call undefined function,
                              8.includes files which is not found

Common errors in php:


                    Basically four types errors is occurred in php. There are:

                              1. Parse error
                              2. Fatal error
                              3. Warning
                              4. Noticed error

Parse error:

                       
                             The parse errors php is the syntax error. It stops the execution of the script in php. The common reasons for occur parse in php as follows:
                              1.unclosed quotes
                              2.missing semicolon
                              3.unclosed braces
                              4.missing parentheses
                              5.add extra parentheses

Parse error by unclosed quotes in php:

                               
                           Consider the following example in php:

<?php
          $name='guru;
          echo $name;
?>

       where, the quotes are not closed. When you run this file, you'll get error message like this:

parse error by missing quotes in php

Parse error by missing semicolon in php:

                                     Consider the following example:

<?php
     $name='Guru'
     echo $name;
?>

          where, the semicolon is missing at $name. It gives the parse error like below:

Parse error by missing semicolon in php

Parse error by unclosed braces in php:


<?php
 $a=5;
 $b=6;
 if($a==$b)
 {
   echo 'equal';
 else
 {
   echo'Not equal';
 }
?>

     where the closing brace is missed. When you run this file, you'll get error message like below:

parse error by missing braces in php

Fatal error in php:


                The fatal error will occur when you call the undefined function in php. It stop the execution of the php script.

<?php
 function name($str)
 {
  echo $str;
 }
  echo place('guru');
?>

            where the function "place()" is not defined. But you call that function. Now it gives the fatal error like below:

fatal error in php

Waring in php:


                       The warning is occurred when you include the file but the file is not found in php. It does not stop the execution of the php script.

<?php
 include('welcome.php');
 echo'welcome'; 
?>

       where, the file welcome.php is not found but you include it. So you'll get output like this:

warning error in php

Noticed error in php:


                   The noticed error is occurred when you use undefined variable. It does not stop execution of the php script.

<?php
 $name='Guru';
 echo $guru;
?>

       where $guru is not defined but you accessed. So you'll get error message like this:

Noticed error in php

11 Jun 2014

Send mail using php

                       You can send emails using php.

Mail() in php:


                       The mail() in php is used to send mail. The syndex for mail() is:

                    mail(to, subject, message, header)

Where,
            to - receiver mail id.
            subject - subject of mail.
            message - message to be sent.
            header - header of mail.

Note:
           You can send mail if you are in server. You've to make some changes in php.ini file, if you send mail from local server.

          You've to make following changes in your php.ini file to send mail.
                     [mail function]
                     ; For Win32 only.
                     ; http://php.net/smtp
                       SMTP =your ISP's mail server address
                     ; http://php.net/smtp-port
                       smtp_port = 25


                     ; For Win32 only.
                     ; http://php.net/sendmail-from
                       sendmail_from =example@gmail.com

How to send mail using php:


                      The following php script is used for send mail:

<?php
   $to='example@gmail.com';         
   $subject='Send mail using php';
   $message='This mail send using php';
   $headers='From: guruparthiban19@gmail.com';
   $mail=mail($to,$subject,$message,$headers);
   if($mail)
   {
    echo'Mail send successfully';
   }
   else
   {
    echo'Mail is not send';
   }
 ?>

                      If the the mail is send, then you'll get successful message. Otherwise you'll get 'Mail is not send' message. Now you can see mail in inbox.

2 Jun 2014

PHP - Cookies

                       Cookie is a file. It is used to identify the user. All of you see the login form with remember me check box. When you click it, it store your name in cookie. You can login again, when you open the page in your browser, even if you signout and close the browser. The cookie keep the information until it expired.

Cookies in php:


                       In php, you can
                                    1. Create cookies,
                                    2. Retrieve cookies,
                                    3. Delete cookies.

Create cookies in php:


                      setcookie() is used to create cookies in php. The syntax for create cookies as follows as:

                         setcookie(name, value, expire, path, domain)

     where,
                 - name is name of the cookie.
                 - value is value kept by cookie.
                 - expire is when the cookie expired. It is defined by time() + 60*60*24*30 (cookie set for 30 days). If set the expire is 0 or not defined, then the cookie is expired when close the session.
                 - path refers where the cookie is available. If the set '/', then the cookie will be available on whole domain. If you want to set cookies only particular folder, then you've to set path '/foldername/'. You can set for sub-folder too like '/folder/sub-folder/'. If it is not set, the cookies will be available only on current directory.
                 - domain refers where the cookies is available.

 Consider the following example:          

<?php    
          setcookie('name','guru', time()+ (60*5) );
?>

 where,
           - name is name of guru.
           - guru is the cookie values.
           - time()+ (60*5) means cookies expired after 5 minutes. If you want to set cookies in days, then use
time() + (60*60*24*1) where set expiration time for 1 day.
       

Retrieve cookies in php:


                         S_COOKIE['name'] is used to retrieve the cookie in php. Consider the following example:

<?php    
          setcookie('name','guru', time()+ (60*5) );
          echo $_COOKIE['name'];
?>

                   
             Now you'll get output:     guru

Delete cookies in php: 


                   You can delete the cookies by set expire time is past in php. Consider following example in php:
welcome.php:

<?php    
          setcookie('name','guru', time()+ (60*5) );
          echo $_COOKIE['name'];
          echo'<a href="signout.php">Signout</a>';
?>

 signout.php:

<?php    
           setcookie('name','guru',time() - (60*5));
  header('location:welcome.php');
?>

                When you run the welcome.php, your output like this:

                       guru
                       signout

                  When you click the signout, it delete cookies and navigates to welcome.php. Now you'll get output like below:

delete cookies in php
              signout

Related Post:

22 May 2014

PHP - Session

                      Session is the temporary memory to store a particular value. All of you use gmail, that gmail is the bset example for session concept. If you login gmail, then close the browser. Now you open gmail in your browser, you login gmail again. Unlike, you logout from gmail and close the browser. Now you can't login again. It comes to login page. This is the session concept. The value is stored in session until you destroy the session.

Session in php:


                      In php, there is 3 steps for session.
                      1. Start the session using session_start().
                      2. Load values to session variable by $_SESSION['name']='Guru'.
                      3. Destroy the session by session_destroy() or unset($_SESSION['name']).

session_start() in php:


                      It is used to start the session in php. Consider folowing example in php:

<?php    
         session_start();
         $_SESSION['name']='Guru';    
         echo $_SESSION['name'];
?>

                     Now you'll get output:     Guru

Suppose you run file without session_start(). Then you'll get error message like below:

session_start() in php

session_destroy() in php: 


                   It is used to destroy the session. Consider following example in php:
welcome.php:

<?php    
         session_start();
         $_SESSION['name']='Guru';    
         echo $_SESSION['name'].'<br>';
         echo'<a href="signout.php">Signout</a>';
?>

signout.php:

<?php    
         session_start();
         session_destroy();
         header('location:welcome.php');
?>

                When you run the welcome.php, your output like this:

                       Guru
                       Signout

                  When you click the signout, it destroy the session and navigates to welcome.php. Now you try to clikc back button on your browser, it go to welcome.php page, but the value stored in session is not displayed. It give error message like below:

session_destroy() in php

unset() in php:


                  You can also delete the session using unset() in php. The script for unset() as follows as:

<?php    
         session_start();
         unset($_SESSION['name']);
         header('location:welcome.php');
?>

It is also give same output like session_destroy() in php.

Related Post: