Thursday 29 August 2013

Prestashop Zopim Chat Free 1.3

Product Description: Prestashop Zopim Chat Free


There are many reasons to use Live Chat. You can use Live Chat to: Increase sales conversion on your website,  Handle customer support on your website, Get feedback from early beta users of your service, Many more, let your imagination run wild! We decided to create module for all store owners based on prestashop engine. With our addon you will be able to install own zopim chat widget with one mouse click! Module is absolutely free and you can download it now.


zopim-free-cover-big


Why to use Zopim? And why via us module?



  •     Zopim module & Our product, customer service and response time set us apart from the rest. We are dedicated to providing you with the best service and support, wherever you are.



  •     We are incessantly preoccupied with delivering products that we are proud of. That means getting every single little detail right – from perfecting each pixel on the widget, to reducing the nano-second delays in message delivery. We are proud artisans.



  •     We never take our eyes away from big issues like reliability, and scalability. This is why our uptime has averaged 99.8% in the past year, and this year we aim to do even better. We are proud engineers.


Geeky facts about Zopim & our module



  •     Work across major browsers ( Internet Explorer 6+, Firefox, Google Chrome, Opera, Safar) and IMs (Gtalk / MSN / Yahoo! Messenger / AIM).



  •     Uptime averaged 99.8%.



  •     New HTML5 dashboard.



  •     iPhone application available.



  •     Android application for beta testers (will be available soon)


 


Download Link



Prestashop Zopim Chat Free 1.3

Thursday 22 August 2013

jQuery stylish CSS3 image zoomer

In this quick post, I am sharing you a jQuery plugin which uses CSS3 to create stylish image zoomer.


SKDZoom – A jQuery stylish CSS3 image zoomer plugin with lens zoom support. Big image shows in a awesome rounded box beside the thumbnail. It is very light weight and easily customizable image zoomer.


zoomer


 


Download SkdZoom

 


Click here to download SkdZoom



jQuery stylish CSS3 image zoomer

Wednesday 21 August 2013

jQuery - Page Redirect after X seconds wait

You must have come across any website which uses a webpage with some annoying advertisement and a message that says “You will be redirected to actual page after X seconds”. This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.


The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.


HTML Code


<h1>You will be redirect to actual page after <span id="spnSeconds">10</span> seconds.</h1>

CSS Code


body {
font-size:12pt;
font-family:Calibri;
}
#spnSeconds {
font-size:25pt;
color:Red;
}

Jquery Code


$(document).ready(function () {
window.setInterval(function () {
var iTimeRemaining = $("#spnSeconds").html();
iTimeRemaining = eval(iTimeRemaining);
if (iTimeRemaining == 0) {
location.href = "http://paceinfonet.org/jquery-page-redirect-after-x-seconds-wait/";
} else {
$("#spnSeconds").html(iTimeRemaining - 1);
}
}, 1000);
});


jQuery - Page Redirect after X seconds wait

Thursday 15 August 2013

Understanding Model View Controller in Asp.Net MVC

The Model-View-Controller (MVC) pattern was introduced in 1970s. It is a software design pattern that splits an application into three main aspects : Model, View and Controller. Moreover, MVC pattern forces a separation of concerns within an application for example, separating data access logic and business logic from the UI.


asp.net MVC


Model

The Model represents a set of classes that describes the business logic and data. It also defines business rules for how the data can be changed and manipulated.


Moreover, models in Asp.Net MVC, handles the Data Access Layer by using ORM tools like Entity Framework or NHibernate etc. By default, models are stored in the Models folder of the project.


View

The View is responsible for transforming a model or models into UI. The Model is responsible for providing all the required business logic and validation to the view. The view is only responsible for displaying the data, that is received from the controller as the result.


Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result of a request received by a controller. By default, views are stored in the Views folder of the project.


Controller

The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receive input from users via the View, then process the user’s data with the help of Model and passing the results back to the View.


Moreover, controllers in Asp.Net MVC, respond to HTTP requests and determine the action to take based upon the content of the incoming request. By default, controllers are stored in the Controllers folder of the project.



Understanding Model View Controller in Asp.Net MVC

Tuesday 13 August 2013

Platform Features

There are specific features that WordPress offers that make it a unique platform for both websites and blogging. Most of these features are generated by third-party coding that can be modified or extended to meet the needs of any project. The features include:
No Rebuilding – Any changes made to a template are immediately recognized on the site without the need to regenerate any dynamic or static page.
WordPress Theme Design And Development – Many third-party companies develop highly creative WordPress themes to create a variety of professional sites, for all types of niche markets. These creative templates optimize web design to the owner’s liking.
Cross-Communication Tools – The platform utilizes the best cross communication tools to allow website owners instant updates on social media channels when posting to their blog or site.
Password Protection – Every post is password protected allowing the site owner complete confidentiality in a private post that can only be viewed by the author, until publicly published.
Comment Capabilities – The platform allows site owners to insert a comment section where visitors can leave feedback and comments. This feature can be enabled or disabled by the site owner.
WordPress offers significant features, plug-ins, add-ons, and themes that are unavailable from its competitors. Any business that is about to design a new website, or renovating an existing one, should consider WordPress as their number one choice. The ability to transfer the site to any hosting location makes WordPress the best solution to develop and maintain a premium site.

significant advantages to using WordPress over the competition

There are significant advantages to using WordPress over the competition. These advantages include:

Enhanced SEO – With a dedicated built-in SEO platform, WordPress can quickly utilize all of the page elements including meta-tags and meta-descriptions to rank higher in search engine results. Web designers do not necessarily provide SEO options. However, in WordPress it is automatic.

an extensive list of add-ons and plug-ins – With a seemingly unlimited amount of add-ons and plug-ins, WordPress offers nearly every type of feature from contact forms, to check out and shopping carts, and more. Every time there is a new version or update of WordPress, all plug-ins and add-ons are automatically updated too.

Extremely affordable – Compared all the other competition available online, WordPress is much less expensive to operate and maintain. With a fully customizable, easy to install CMS, site owners can use all the benefits to develop the best dynamic or static website.

Quick and easy indexing – WordPress utilizes the best indexing tools available. It optimizes the search engine’s abilities to index and file pages and content. Generally, any site that utilizes CMS technology will automatically be indexed much quicker in the search engines than an old-fashioned, static website.

No coding skills required – The CMS is designed to be simple enough that no coding skills are required to develop or maintain the website. This means the site owner can quickly upload newly developed content whenever desired without the need to hire a web designer to perform the duties instead.

Online Marketing – A WordPress site can be promoted for free. Online promotional tools include sending the site to free blog directories.

A built-in blogging platform – WordPress was originally designed as a blogging platform. Because of this it automatically has the best features, plug-ins and add-ons. Many websites incorporate a blog as a way to communicate with their customers, patients, ans, volunteers, and staff.

A transferable framework – Businesses wishing to stay within their budget when using a host provider to handle their online website enjoy the freedom WordPress provides with its transferable framework.

Built-in RSS feed – Website owners can quickly syndicate all the content on their site, through an RSS feed. Designed as an extremely powerful traffic magnetizing tool, the RSS feed distributes company information out to the Internet while pulling an audience toward the site.

Ongoing Support – Because WordPress is used by over 75 million site owners around the world, they offer the best ongoing support. Their support system includes tutorials, forums and a backup of other websites that are all available to answer all pertinent and important questions for the novice or expert user.

Full Compatibility – They also provide extensive backwards compatibility, offering peace of mind when upgrading the system to a newer version, to allow better flexibility and safeguards. WordPress is known for not having migration issues.

Monday 5 August 2013

sql stored procedure Add Operation

Create and add operation using sql stored procedure in Asp.net


sql stored procedure


Create PROCEDURE [dbo].[AddDEmp]
(
@empName  Varchar(50),
@empAge    int,
@empEmail  nVarchar(50),
@PhoneNo  nVarchar(50)
)
AS
INSERT  INTO  empRecord(empName,empAge,empEmail,PhoneNo) VALUES(@empName,@empAge,@empEmail,@PhoneNo)

Use below code in your asp.net page



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class storedProcedureInsert : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
protected void Button1_Click(object sender, EventArgs e)
{
string constr = "Data Source=RLABSRV/SQLEXPRESS;Initial Catalog=employee;Integrated Security=True";
//DataTable allData = new DataTable();


SqlConnection con = new SqlConnection(constr);




try
{
SqlCommand cmd = new SqlCommand("AddDEmp", con);
cmd.CommandType = CommandType.StoredProcedure;


con.Open();
cmd.Parameters.Add("empName", SqlDbType.VarChar, 50);
cmd.Parameters["empName"].Value = TextBox1.Text;




cmd.Parameters.Add("empAge", SqlDbType.Int);
cmd.Parameters["empAge"].Value = TextBox2.Text;


cmd.Parameters.Add("empEmail", SqlDbType.NVarChar, 50);
cmd.Parameters["empEmail"].Value = TextBox3.Text;


cmd.Parameters.Add("PhoneNo", SqlDbType.NVarChar, 50);
cmd.Parameters["PhoneNo"].Value = TextBox4.Text;


cmd.ExecuteNonQuery();

con.Close();
}
catch(Exception ex)
{
con.Close();

Label2.Text = ex.Message;

}
}
}


sql stored procedure Add Operation

Storing and Retrieving Image from Database in C# Asp.Net

Storing and Retrieving Image from Database in C# Asp.Net


Write Below code in Default Page



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection("data source=.; Initial catalog=LoadPhoto;integrated security=sspi;");




protected void Page_Load(object sender, EventArgs e)
{


}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
//string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
//connection = new SqlConnection(conn);


connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);


Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
}
catch
{
lblResult.Text = "Photo Size should be less than 20 KB";
}
finally
{
connection.Close();
}
}
}

Write the below code in  ShowImage.ashx file



<%@ WebHandler Language="C#" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{


SqlConnection connection = new SqlConnection("data source=.; Initial catalog=LoadPhoto;integrated security=sspi;");
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)
{
//string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;
//SqlConnection connection = new SqlConnection(conn);


string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();

try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}

}


Storing and Retrieving Image from Database in C# Asp.Net

Saturday 3 August 2013

10 Must-Have WordPress Plugins for Your Business Website

1. Content Aware Sidebars  
If you’ve used other content management systems such as Joomla, you’ll quickly find the need to assign widgets to specific pages or posts only. There is no way to do such a thing in WordPress out of the box.
That’s where the Content Aware Sidebars plugin comes in handy. It allows you to create an unlimited number of sidebars (widget areas) for any widget area and assign it to specific pages, posts, categories, and so on. In a nutshell, it basically creates a virtual widget area that replaces the real widget area for the pages you specify.
Once you create a new sidebar, it will show up in the Appearance -> Widgets with all other widget areas.
2. Enhanced Text Widget
The out of the box text widget that comes with WordPress is useful, but it lacks many important and necessary features.
The Enhanced Text Widget is a free plugin that enables a more feature-rich text widget for your use. Some of the features supported by the widget include:
    It allows you to hide or show the widget title
    Turn your widget title into a link
    Assign CSS classes to the widget
    Supports text, HTML, PHP, Flash, JavaScript, and Shortcodes
3. BackupBuddy
Every business that has a website needs to have a way to back up that website on a regular basis. Website backups should be secure and restorable in a short period of time. That it exactly what BackupBuddy does.
BackupBuddy allows you to create full or partial backups of your WordPress website including core WordPress, database, and all plugins. It even allows you to schedule regular backups and store them in various locations such as local hosting, Amazon S3, FTP, Dropbox, or BackupBuddy Stash.
This is the most comprehensive backup plugin for WordPress and it literally has hundreds of useful features that will come in handy. The best part is that you can restore any backup in a matter of minutes.
BackupBuddy will run you $80 for 2 licenses, $100 for 10 licenses, $150 for unlimited licenses, or $197 for developer license for BackupBuddy and all other iThemes plugins. Although the prices seem a bit on the expensive side, you’ll be happy you paid it when your website is corrupted or gets hacked and you find yourself needing to restore it quickly.
4. WordPress SEO by Yoast
WordPress SEO by Yoast is bar none the best SEO plugin for WordPress. It allows complete control of page titles and meta descriptions on a per page/post basis as well as for each taxonomy (category or tag pages).
Some other useful features include 301 redirection and setting up rules for search engine robots such as follow, nofollow, index, noindex, and so on. It also allows you to customize the Facebook and Google+ descriptions for individual pages or posts in case you don’t want to use the default meta description field.
One thing you won’t have to worry about anymore is the rel=“canonical” tag because the WordPress SEO plugin automatically adds it to every page and post. So you can be sure that Google won’t penalize your website for duplicate content due to dynamic URL string variations.
5. Akismet
Although there are many plugins that help you combat spam, Akismet is one of the best options because it comes with WordPress out of the box and it’s free for personal use.
Setting up Akismet is a piece of cake. All you have to do is go to Akismet.com and register to get a WordPress key. Once you’re assigned a key, you can insert it in the Akismet settings on your website and say goodbye to spam!
6. Visual Composer for WordPress
WordPress can be limiting to the average users when it comes to how you want your page layout to look. Even though you can do anything with HTML and CSS, most users do not know these coding languages. That’s where Visual Composer for WordPress can help.
Visual Composer transforms the default WordPress page editor into a robust feature-rich editor that allows you to add columns, image galleries, accordions, tour sections, call-to-action buttons, videos, and much more.
Visual Composer can be hard to find because the only place where you can purchase it is Code Canyon.
7. Gravity Forms
Every website that intends to generate revenue needs to utilize forms. Forms allow us to collect information from our users, which we later use to provide services to them.
There are many WordPress form plugins, but none have as many features as Gravity Forms. This plugin literally has hundreds of add-on plugins that expand on its features and integrate into CRM (Customer Relationship Management) systems such as InfusionSoft, SalesForce, and Highrise.
Although Gravity Forms is not a free plugin, you can have it on your website for as low as $39 with 1 year of support and updates. Most Gravity Forms add-ons tend to be free so you shouldn’t need to spend more than that.
8. Digg Digg
If you’re not taking advantage of social media for your business yet, it is time to start. The Digg Digg plugin adds a floating box on your website that enables your users to quickly and easily share the page they are on.
It supports all popular social media websites such as Facebook, Twitter, LinkedIn, Google Plus, and Pinterest. You can customize which services you want to show to your users so that you don’t have to use social media services that are irrelevant for your business or niche.
9. W3 Total Cache
Website caching necessity varies based on your website. Websites that are heavy in images and scripts will see a nice speed improvement from using cache plugins.
W3 Total Cache is a free WordPress plugin that has all the caching features you will need. In fact, they can be a bit overwhelming at first, so it would behoove you to just start slow and test each feature carefully.
10. 404 Redirected
From my experience, business owners don’t monitor their broken links nearly as much as they should. Broken pages present a business and SEO problem for your website. On one hand, your potential customers might leave your website immediately when they see a 404 error, and on the other hand, Google will not pass PageRank to your 404 page.
404 Redirected plugin shows all URLs which return 404 errors and allow you to 301 redirect those to actual pages on your website. This will redirect traffic to the appropriate content as well as pass PageRank to the correct pages.
Pace Infonet Web Solutions Pvt .Ltd. Vadodara

Friday 2 August 2013

15 very useful PHP code snippets for PHP developers

Following are list of 15 most useful PHP code snippets that a PHP developer will need at any point in his career. Few of the snippets are shared from my projects and few are taken from useful php websites from internet. You may also want to comment on any of the code or also you can share your code snippet through comment section if you think it may be useful for others.
1. Send Mail using mail function in PHP


<?php
$to = "youremail@gmail.com";
$subject = "my mail";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?>

2. Base64 Encode and Decode String in PHP


<?php
function base64url_encode($plainText) {
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/=', '-_,');
return $base64url;
}

function base64url_decode($plainText) {
$base64url = strtr($plainText, '-_,', '+/=');
$base64 = base64_decode($base64url);
return $base64;
}
?>

3. Get Remote IP Address in PHP


<?php
function getRemoteIPAddress() {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
?>

The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.


<?php
function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
?>

4. Seconds to String


This function will return the duration of the given time period in days, hours, minutes and seconds.

e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”


<?php
function secsToStr($secs) {
if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
$r.=$secs.' second';if($secs<>1){$r.='s';}
return $r;
}
?>

5. Email validation snippet in PHP


<?php
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
echo 'This is a valid email.';
} else{
echo 'This is an invalid email.';
}
?>

6. Parsing XML in easy way using PHP


<?php
//this is a sample xml string
$xml_string="<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";

//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);

//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
//attribute are accessted by
echo $record['name'], '  ';
//node are accessted by -> operator
echo $record->symbol, '  ';
echo $record->code, '<br />';
}
?>

7. Database Connection in PHP


<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");

# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
header('HTTP/1.x 404 Not Found');
print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
'<html><head>'."n".
'<title>404 Not Found</title>'."n".
'</head><body>'."n".
'<h1>Not Found</h1>'."n".
'<p>The requested URL '.
str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
' was not found on this server.</p>'."n".
'</body></html>'."n";
exit;
}

# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";

?>

8. Creating and Parsing JSON data in PHP


Following is the PHP code to create the JSON data format of above example using array of PHP.


<?php
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);
?>

Following code will parse the JSON data into PHP arrays.
<?php
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google
?>

9. Process MySQL Timestamp in PHP


<?php
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
echo $row;
}?>

10. Generate An Authentication Code in PHP


This basic snippet will create a random authentication code, or just a random string.


<?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
$pos = rand(0,36);
$str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>

11. Date format validation in PHP


Validate a date in “YYYY-MM-DD” format.


<?php
function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}
?>

12. HTTP Redirection in PHP


<?php
header('Location: http://paceinfonet.org/index.php'); // stick your url here
?>

13. Directory Listing in PHP


<?php

function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}

/*
To use:

<?php
list_files("images/");
?>
*/
?>

14. Browser Detection script in PHP


<?php
$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;
?>

15. Unzip a Zip File


<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>


15 very useful PHP code snippets for PHP developers