Monday, March 31, 2014

Ecommerce track code for virtuemart

This article explains you how to track your order status using google analytics.

Lets have a look .

Please find the below code:

<script type="text/javascript">

  var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'Your analytics code']);
_gaq.push(['_trackPageview']);
_gaq.push(['_addTrans',
   '<?php echo $trans['id']; ?>',           // transaction ID - required
   'Pantech', // affiliation or store name
   '<?php echo $trans['revenue']; ?>',          // total - required
   '<?php echo $trans['shipping']; ?>',           // tax
   '<?php echo $trans['tax']; ?>',          // shipping
   '',       // city
   '',     // state or province
   'India'             // country
]);
<?php
foreach($this->orderdetails['items'] as $item) { 
?>
_gaq.push(['_addItem',
   '<?php echo $trans['id']; ?>',           // transaction ID - necessary to associate item with transaction
   '<?php echo $item->order_item_sku; ?>',           // SKU/code - required
   '<?php echo $item->order_item_name; ?>',        // product name
   '<?php echo $item->virtuemart_category_name; ?>',   // category or variation
   '<?php echo $item->product_item_price; ?>',          // unit price - required
   '<?php echo $item->product_quantity; ?>'               // quantity - required
]);

<?php } ?>
_gaq.push(['_trackTrans']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
  
</script>

MotionCAPTCHA – Stop Spam, Draw Shapes

Motion captcha is JQUERY PLUGIN based on HTML5.

It is used to stop spam mails

Please click here to see a demo

Saturday, March 29, 2014

Export table values from MYSQL to CSV Using PHP

In this article we will discuss about export table values from MYSQL to CSV.

Let's have look.


Change values as per your requirement.

conn.php

<?php

        //config file
      
        define('host','localhost');/*Hostname*/
       
        define('username','root');/*Username*/
       
        define('password','');/*Password*/
       
        define('database','register');/*Database*/
       
        $conn=mysql_connect(host,username,password) or die(error);
       
        $db=mysql_select_db(register,$conn);
       
        ?>

sqltocsv.php

<?php

include("conn.php"); //Database config file

$result = mysql_query("select * from reg");/*edit as per your requirement*/

if (mysql_num_rows($result) > 0)

{

$csv="FIRSTNAME".","."LASTNAME".","."GENDER".","."MONTH".","."COUNTRY".","."EMAIL".","."PASSWORD".","."PASSWORD1".","."EMAIL1".","."SECERT1".","."ANSWER".","."SECRET2".","."ANSWER1"."\n";

while ($row = mysql_fetch_array($result))

{

$csv.= $row['firstname'].",".$row['lastname'].",".$row['gender'].",".$row['month'].",".$row['country'].",".$row['email']

.",".$row['password'].",".$row['password1'].",".$row['email1'].",".$row['secert1'].",".$row['answer'].",".$row['secret2'].",".$row['answer1'];

$csv.= "\n";

}

}

//print $csv;

$filename = date("Y-m-d/H-i",time());

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

header( "Content-disposition: filename=".$filename.".csv");

print $csv;

exit;

?>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Htaccess code for apache server

Use this htaccess for website speed.

.htaccess files can be used to alter the configuration file of the Apache Web Server

<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>

Automatic logout after session expires in PHP

I have written this article for automatic logout after session expires.

Please use the following code

<?php
$timeout = 600; // Number of seconds until it times out.

// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
    // See if the number of seconds since the last
    // visit is larger than the timeout period.

    $duration = time() - (int)$_SESSION['timeout'];
    if($duration > $timeout) {
        // Destroy the session and restart it.        session_destroy();
        session_start();
    ?>
        <script>
            alert("Your session was expired.Please login again to continue");
            window.top.location='login.php';
        </script>
    <?php
    }
}

// Update the timout field with the current time.
$_SESSION['timeout'] = time();

?>

Redirect http to https using htaccess

Lets take a look how to redirect http to https using htaccess file

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Form validation using javascript

Lets have a look how to validate  a HTML form using Javascript

HTML code:

<form action="#" method="post"; onsubmit="return form();" name="myform">
      <table>
        <tr>
          <td>username</td>
          <td><input type="text" name="name" /></td>
        </tr>
        <tr>
          <td>password</td>
          <td><input type="password" name="pword" /></td>
        </tr>
        <tr>
          <td>email</td>
          <td><input type="text"  name="email"/></td>
        </tr>
        <tr>
          <td>gender</td>
          <td><select name="gen">
              <option>male</option>
              <option>female</option>
            </select></td>
        </tr>
        <tr>
          <td></td>
          <td align="left"><input type="submit" name="submit" value="register" /></td>
        </tr>
      </table>
    </form>
  </div>

Javascript code for Validation:

  <script type="text/javascript">
 function form()
 {
 var name=document.myform.name;
 var pwd= document.myform.pword;
 var email=document.myform.email;

 if(name.value=="")
 {
 window.alert("enter your name");
 name.focus();
 return false;
 }
if(pwd.value=="")
 {
 window.alert("enter your password");
 pwd.focus();
 return false;
 }

if(email.value=="")
 {
 window.alert("enter your email");
 email.focus();
 return false;
 }

}

</script>

Display Current date using Javascript

<script type="text/javascript">
            var mydate=new Date()
            var year=mydate.getYear()
            if (year < 1000)
            year+=1900
            var day=mydate.getDay()
            var month=mydate.getMonth()
            var daym=mydate.getDate()
            if (daym<10)

            daym="0"+daym
            var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
            document.write("<b class='date'>"+montharray[month]+" "+daym+", "+year+"</b>")
</script>

Redirect http:// to http://www website Url using htaccess

For SEO purpose we need to redirect http://example.com to http://www.example.com

Find the below htaccess code for redirection:

.htaccess code for redircet:
 
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Rewrite url in wordpress using htaccess


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Friday, March 28, 2014

Date wise search in mysql using php

Query for date wise search:

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

Generate random letter in php

Use the following PHP code to generate a random letters.

<?php 
for($i=0;$i<5;$i++) 
    $let[$i] = randLetter(); 
function randLetter()
{
    $int = rand(0,51);
    $a_z = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $rand_letter = $a_z[$int];
    return $rand_letter;
}
$word = implode('',$let);
echo $word;
?>

Cache remove in PHP

I have submitted one form.After submitted the form ,the listing page didn't shows added item.

Then i found solution for this issue.

Add this code top of the program.

header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0");

After login redirect to clicked link in php

My friend asked how to redirect a page after login to the clicked link php.Then i did some research and found some codes for this.

Lets have a look this tutorial.

$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header("Location: login.php?action=login");
exit();

// On successful login
$redirect = $_SESSION['redirect_to'];
// unset the session var
unset($_SESSION['redirect_to']);
header("Location:$redirect");
exit();

Hope this will help

Add Facebook likebox in website

I have written small and useful article.

Lets have a look how to add facebook likebox in website.

Steps:

Go to this link :

https://developers.facebook.com/docs/plugins/like-box-for-pages/


PHP Login Example



Simple login example using PHP & Mysql.

Download Link



Step 1:
Create table using the following sql commands.

CREATE TABLE IF NOT EXISTS `admin` (
  `AdminId` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar(225) NOT NULL,
  `Password` varchar(225) NOT NULL,
  PRIMARY KEY (`AdminId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 2:
HTML codes for Login form (Login.php)

<form action="#" method="POST">
    <fieldset>
    <p>
      <label for="email">E-mail address</label>
    </p>
    <p>
      <input type="text" id=" username " name="username" value="" required >
    </p>
    <p>
      <label for="password">Password</label>
    </p>
    <p>
      <input type="password" name="password" id="password" value="" required>
    </p>
    <p>
      <input type="submit" name="Login" value="Sign In">
    </p>
    </fieldset>
  </form>

Step 3:
Write database connection(config.php)

<?php
session_start();
$host = "localhost"; /*Your Hostname*/
$user = "root"; /*Your Databse Username*/
$pass = ""; /*Your Databse Password*/
$db_name = "login"; /*Your Databse Name*/
//database connection
$link = mysql_connect($host, $user, $pass);
$db=mysql_select_db($db_name);
?>

Step 4:
Check posted username and password are correct(include this code top of the login.php)
<?php
                //Database file
                require_once("config.php");
               
                if(isset($_POST['Login'])) {
                                //Get values from post
                                $username=mysql_real_escape_string($_POST['username']);
                                $password1=mysql_real_escape_string($_POST['password']);
                                $password=md5($password1); // Encrypted Password
                               
                                //Check method.Query is correct or not.
                                //echo "SELECT * FROM admin WHERE username='$username' AND Password='$password'";
                                //exit;
                               
                                //Query for login
                                                $res="SELECT * FROM admin WHERE username='$username' AND password='$password'";
                                                $result=mysql_query($res);
                                                $count=mysql_num_rows($result);
                                               
                                // If result matched $username and $password, table row must be 1 row
                                if($count==1)
                                                                                {   //Store values in SESSION
                                                                                                $_SESSION['username'] = $_POST['username'];
                                                                                                $username=$_SESSION['username'];
                                                                                                header("location:welcome.php");//redirect to welcome page
                                                                                } else {
                                                                                                ?>
                                                                                <script type="text/javascript">
                                                                                                 alert('OOPS!.Either the username or the password is wrong. Please try again');
                                                                                                 window.top.location="index.php";
                                                                                </script>
                                                                                <?php }
                                                               
                }
?>

Step 5:
If login successful redirect to welcome page.(welcome.php)
<?php
                //Database file
                require_once("config.php");
                $username=$_SESSION['username'];
?>
Wecome <?php echo $username; ?><a href="logout.php">Logout</a>

Step 6:
Logout.php

<?php

/**
 * The logout file
 * destroys the session
 * expires the cookie
 * redirects to login.php
 */
session_start();
setcookie('Email', '', time() - 1*24*60*60);
setcookie('Password', '', time() - 1*24*60*60);
//Session Destroy
if(session_destroy())
{
                header("location:index.php");
} ?>


Thursday, March 27, 2014

Use for Robots.txt file

The robots.txt file is used to control how search engines crawling and indexing your website.

#Code to not allow any search engines
User-agent:*
Disallow:/

Database connection in PHP

Simple code for mysql database connection

Syntax

<?php
$host = "localhost"; /*Host Name*/
$user = "root";  /*User Name*/
$pass = ""; /*Password*/
$db_name = "realestate";  /*Database Name*/

//database connection
$link = mysql_connect($host, $user, $pass);
$db=mysql_select_db($db_name);

?>

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

Use 127.0.0.1 instead of localhost

This works:

http://127.0.0.1/phpmyadmin/

This not works:

http://localhost/phpmyadmin

Wednesday, March 26, 2014

Change Date format in PHP

<?php

$originalDate = "23/05/2014"; /*Your Date*/
$date = date("d-m-Y", strtotime($originalDate));

?>

Call module inside category page[Joomla + Virtuemart]

<?php
 /* Calling Joomla Module in Virtuemart category page */
 $modules =& JModuleHelper::getModules('position-3');/*Your module Position*/
 foreach ($modules as $module)
 {
     echo JModuleHelper::renderModule($module);
 }
?>

PHP Email script

<?php

$to= "test@gmail.com"; /*To Mail*/
$subject = 'Contact us'; /*Subject*/
$header = "From: test@gmail.com \r\n"; /*From mail*/
$header.= "MIME-Version: 1.0\r\n";
$header.= 'X-Mailer: PHP/'.phpversion();
$header .= "X-Priority: 1";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";/*Mail format .You can change this(text/plain) if you didnt use html codes*/
$message = 'Test for mail script'; /*Your Message*/

$flgSend=mail($to,$subject,$message,$header);
    if($flgSend)
    {
        echo "Thank you! Successfully submitted";
               
    }
    else
    {
         echo "OOPS.Please try again";
               
    }
?>

Top 3 Most Usable Content Management Systems



Nowadays website development comes very easy because of CMS tools. Using CMS we can website very quick and clean. There are many CMS tools available for PHP. Now we can see top 3 CMS tools.
  1.  Wordpress
  2. Joomla
  3. Drupal

Joomla 3+ server requirements


Joomla is the best CMS tools. The installation and content adding is very easy. Please find the below details for server requirements
Software Recommended Minimum
PHP (Magic Quotes GPC off) 5.4 + 5.3.1 +
Supported Databases:
MySQL(InnoDB support required) 5.1 + 5.1 +
MSSQL 10.50.1600.1 + 10.50.1600.1 +
PostgreSQL 8.3.18 + 8.3.18 +
Supported Web Servers:
Apache(with mod_mysql, mod_xml, and mod_zlib) 2.x+ 2.x+
Nginx 1.1 1.0
Microsoft IIS 7 7

Free Responsive Mobile Website Templates



I have found one good website for mobile responsive templates. There are many free templates available with different categories.

Click Here to Download templates