Monday, 30 September 2013

GET data with htaccess URL rewrite?

URL rewriting is one of the best way to create SEO friendly URL for your site.

Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7

http://www.yourdomain.com/product.php?product_id=7

The problems with this kind of URL structure are that the URL is not at all memorable and not SEO friendly also.
In case of dynamic pages created by admin (product.php?slug=productname) or pages with query string you have to redirect that dynamic page to a existing page let's say "get-product.php" here you can get the slug value (query string value) by using PHP $_GET['slug'](super global variable) by the help of that variable you can fetch corresponding data from database.

Note: create a unique slug  from the title field for fetching data from database.

Write following code in .htaccess file for url rewrite of dynamic generated file.

RewriteEngine on
RewriteRule ^([A-Za-z0-9]+)\.php get-product.php?slug=$1 [NC,QSA,L]

Note: here we added some flags at the end of RewriteRule.
  • NC (case insensitive)
  • QSA (append query string from request to substituted URL)
  • L (last - stop processing rules)
Now go to "get-product.php" file write following code.

<?php print_r($_GET);?>

Output
Array ( [slug] => productname )

Sunday, 29 September 2013

PHP ini file and its uses

The ini File

The ini(initialization) file has come to be a pseudo standard among application developers for initializing data variables.

Most applications that use an ini file for configuration use the PHP parse_ini_file() function to get values from the ini file. Many classes and abstractions have been written to provide a Object Oriented approach, but the core remains the single PHP function to gain access to the values within.

The simple syntax within the ini file makes it simple to edit and is easy to read. The reason it has been around so long is due to this simplicity. Here is an example of an ini file. Create file called "config.ini"

;
; This is a comment
;
[database]
db_username = username
db_password = password
db_host = localhost
db_port = 1234

[mail]
mail_username = username
mail_password = password
mail_host = mail.example.com

[blog]
blog_title = "My Blog"
blog_moderate = 1
blog_images = 1


To parse the example config.ini file use PHP parse_ini_file() function in your php file.

<?php
    /*** turn on errors ***/
    error_reporting(E_ALL);

    /*** parse the ini file ***/
    $config parse_ini_file("config.ini"1);

    /*** print the array ***/
    print_r($config);?>

This simple script above reads the ini file int a multi-dimensional array for easy retrieval. The array looks like this.

Array
 (
  [database] => Array
  (
   [db_username] => username
   [db_password] => password
   [db_host] => localhost
   [db_port] => 1234
  )

  [mail] => Array
  (
   [mail_username] => username
   [mail_password] => password
   [mail_host] => mail.example.com
  )

  [blog] => Array
  (
   [blog_title] => My Blog
   [blog_moderate] => 1
   [blog_images] => 1
  )
 )

To retrieve a single value from the array is now a simple matter of reading the array as with any PHP array. In the following script, a single value is retrieved from the ini file, and a timer is added to see how long it takes.

<?php
    /*** turn on errors ***/
    error_reporting(E_ALL);

    /*** start a timer ***/
    $start microtime(true);

    /*** parse the ini file ***/
    $config parse_ini_file("config.ini"1);

    /*** get the database user name ***/
    echo $config['database']['db_username']."\n";

    /*** end timer ***/
    $end microtime(true);

    /*** show duration ***/
    echo round$end $start6) . "\n";?>

The above script echos the database db_username configuration option and calculates the time in seconds, rounded to six decimal places. The results from this test averaged around 0.000421

username
0.000425

File Handling in PHP

Opening and Closing Files

Files are opened in PHP using the fopen command. The command takes two parameters, the file to be opened, and the mode in which to open the file. The function returns a file pointer if successful, otherwise zero (false). Files are opened with fopen for reading or writing.

$fp = fopen("myfile.txt", "r");

If fopen is unable to open the file, it returns 0. This can be used to exit the function with an appropriate message.

if ( !($fp = fopen("myfile.txt", "r") ) )
exit("Unable to open the input file.");


FileModes

The following table shows the different modes the file may be opened in.

Mode Description
r Read Only mode, with the file pointer at the start of the file.
r+ Read/Write mode, with the file pointer at the start of the file.
w Write Only mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
w+ Read/Write mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
a Append mode, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.
a+ Read/Append, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.

Note: The mode may also contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e.Windows. It's useless on Unix/Linux). If not needed, it will be ignored.


Closing a File

The fclose function is used to close a file when you are finished with it.

fclose($fp);


Reading from Files

You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine if the end of file is true.

if ( feof($fp) )
echo "End of file
";

The feof function can be used in a while loop, to read from the file until the end of file is encountered. A line at a time can be read with the fgets function:

while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a newline.
// If the length argument is omitted, PHP defaults to a length of 1024.
$myline = fgets($fp, 255);
echo $myline;
}

You can read in a single character at a time from a file using the fgetc function:

while( !feof($fp) ) {
// Reads one character at a time from the file.
$ch = fgetc($fp);
echo $ch;
}

You can also read a single word at a time from a file using the fscanf function. The function takes a variable number of parameters, but the first two parameters are mandatory. The first parameter is the file handle, the second parameter is a C-style format string. Any parameters passed after this are optional, but if used will contain the values of the format string.

if (!($fp = fopen($listFile, "r")))
exit("Unable to open $listFile.");
while (!feof($fp)) {
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3) // $buffer contains the number of items it was able to assign
print "$name $title $age
\n";
}

Here is the file list.txt:
Dave Programmer 34
Sue Designer 21
Lisa Programmer 29
Nigel User 19

You can also store the variables in an array by omitting the optional parameters in fscanf:

while (!feof($fp)) {
$buffer = fscanf($fp, "%s %s %d"); // Assign variables to an array
// Use the list function to move the variables from the array into variables
list($name, $title, $age) = $buffer;
print "$name $title $age
\n";
}

You can read in an entire file with the fread function. It reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example.

$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
echo "$buffer
\n";
fclose($fp);

You can also use the file function to read the entire contents of a file into an array instead of opening the file with fopen:

$array = file(‘filename.txt’);

Each array element contains one line from the file, where each line is terminated by a newline.


Writing to Files

The fwrite function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle, the string to write, and the number of bytes to write. If the number of bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate lines in the file, use the \n character.  
Note:Windows requires a carriage return character as well as a new line character, so if you're using Windows, terminate the string with \r\n. The following example logs the visitor to a file, then displays all the entries in the file.

\r\n";
else
$userDetails .= "
\r\n";
fwrite($fp, "$userDetails"); // Write the user details to the file
rewind($fp); // Move the file pointer to the start of the file
$entries = 0;
while(!feof($fp)) { // Display each line in the file
$buffer = fgets($fp, 1024);
if ($buffer != "") {
echo $buffer;
$entries++;
}
} // Show a summary
echo "There are $entries entries in the log file
";
fclose ($fp);
?>


Locking Files

boolean flock ( resource fp, integer operation)

 PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). If there is a possibility that more than one process could write to a file at the same time then the file should be locked.

flock() operates on fp which must be an open file pointer. operation is one of the following:
  • To acquire a shared lock (reader), set operation to LOCK_SH
  • To acquire an exclusive lock (writer), set operation to LOCK_EX
  • To release a lock (shared or exclusive), set operation to LOCK_UN
  • If you don't want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX
When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

Here is a script that writes to a log file with the fputs function and then isplays the log file’s contents:

”; // dump log
readfile(“/tmp/log.txt”);
echo “
\n”; ?>


Other Useful File Functions

The opendir function returns a directory handle; closedir closes a directory; readdir reads a directory entry.

$myDirectory = opendir(“.”); // use the current directory
while($entryname = readdir($myDirectory)) {
echo “”;
echo “$entryname

”;
echo “”;
echo filesize($entryname); // the filesize function returns the file size in bytes
echo “

”;
echo “\n”;
}c
losedir($myDirectory);

The is_dir function tests if a filename refers to a directory:

if(is_dir($filename))
echo $filename . “ is a directory”;

The is_file function determines if a filename refers to a file:

if(is_file($filename))
echo $filename . “ is a file”;

The is_readable function returns TRUE if the file exists and it is readable, otherwise it returns false. On Unix/Linux this is determined by the file’s permissions. On Windows, TRUE is always returned if the file exists.

if(is_readable($filename))
echo $filename . “ is readable”;

The is_writable function determines whether the server will allow you to write data to the file before you attempt to open it:

if(is_writable(‘../quotes.txt’)) {
// attempt to open the file and write to it
} else {
echo ‘The file is not writable’;
}

Note: there are many more file functions. Please refer to PHP documentation for an exhaustive list.

Introduction to PHP SESSION Variable

Introduction

As we know that http protocol is a stateless protocol so the web server does not recognize you . A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

What is session control?

Gives ability to track a user through site, and easily move data related to that user among pages.No need to move data through hidden form fields.
Very useful for authentication, but can be used any time persistent data needed throughout a site visit.

How sessions work

Sessions are identified by a random number (Session ID) generated by PHP and stored on the client computer in 1 of 2 ways:
  1. Using a cookie, if the user's browser supports.
  2. Appending the session number to URLs as user traverses site (i.e  www.whatever.com?PHPSESSID=495294532459x)
Session ID corresponds a session data store onserver
A session will eventually expire‐‐usually after aspecified period of inactivity.

Progression of events

PHP script starts a session. Done before any other page activity.

session_start();// Session ID created and stored on user's computer. (if possible)


Session variables are created, and values stored on the server.
PHP script can use these variables from page to page throughout a site.

Starting a session In PHP

In any script using sessions, you must first call

session_start();
  •  If session has not been established, this will do that.
  • If a session has been established, this will load session data.
You must start the session at the very beginning of the script‐‐as part of header transmission.
Add or access session variables by using the $_SESSION superglobal array.

Session Handling

Createa page ses1.php copy the following code in that page. and run it. now session will be set.

<?php
session_start();
$_SESSION['name'] = "your name";
$_SESSION['office'] = "company name";
$_SESSION['phone'] = 96951;
?>

Let's create another page ses_result.php copy following codes and run.


<?php
session start();
session_echo "Here's the session info:<br />";
foreach ($_SESSION as $var=>$contents)
echo "$var: $contents<br />";
?>


Manipulating the Session data

session_unset() erases all session variables and data.

unset() can be used to erase a single variable and data.

unset($_SESSION['myvar']);

session destroy() destroys the session data (without destroying the session variables).Can be useful for "logging out" user.


Session variable arrays

 Session variables can be arrays



<?php
session_start();
$_SESSION['list'][]="Hello";
$_SESSION['list'][]="Wow";
echo count($_SESSION['list'])."<br />";
foreach ($_SESSION['list'] as $item)
echo "$item<br />";
?>

Can be useful technique for shopping carts or other data that is accumulated over multiple page visits.

 

When and why to use Sessions

  • Performance: When performing a slow operation, storing the results for use on several pages is better than repeating the calculation on each.
    Example: storing results of SQL query
  • Sequence: When a user process takes place over a sequence of screens, storing information saves time and user input.
Personalization: Session variables can be used to store user color or layout preferences or facts about browsing activity. Pages can then adapt to that activity.


Introduction and use of cookies in PHP

Introduction

A cookie is a small text file composed of alphanumeric characters, which is created on your computer when your browser accesses a website that uses cookies. The files are used to help your browser navigate the website and fully use all its features like logins, preferences, language settings, themes, among other common features. The cookie is used solely to help your browser process a website, it doesn't collect any information from your computer or your file system.

The cookie containing following things
  • The name of the website server that created the cookie
  • The duration of the cookie-how long use the cookie will be alive.
  • A cookie value-this unique information is normally a randomly generated number.

HTTP (Hyper Text Transfer Protocol), is  protocol used by the WWW ( World Wide Web). HTTP  is responsible for submit the user request to the Web server and receive the response from the server.
It is a  stateless protocol means it does not store or remember any value after sending the request  or receiving the response from server.
So cookies are used to remember some useful date in client side for example to remember login username and password in client side.

Using cookies in PHP

To create a cookie, use setcookie() function in php

setcookie(cookiename, value, [expire]);
setcookie("cook","27");

Expiration—expressed using time. If not set, cookie is valid for this user session only.

setcookie(cookiename, value, [expire]);
setcookie("other","1", time()+60*60*24*30);

Retrieved similar to $_POST variables: $_COOKIE['cookiename']

Deleting and checking cookies

To delete: overwrite cookie with expiration time in the past.

setcookie("cook","",time()-100);

Actual cookie deletion done by user's browser.

To see if the user accepts cookies, write one and then check (on another page or after a refresh) to see if it exists.

Saturday, 28 September 2013

Introduction to MVC Architecture and it's Benefits

MVC (Model-View-Controller) is a software architecture,or design pattern which is used in software engineering. The principle of MVC is  separation  the "presentation logic" from the "business logic".  MVC design pattern have some rules, that should be followed by the programmer to produce clean, scalable, powerful, fast code in the least amount of time with the least amount of effort.


The MVC principle is to separate the application into 3 main parts
"Model" ,"View","Controller"


Model 

Model is the most important part  of MVC .It is responsible for the business logic of he software application like the database logic, main logic of the application etc. End user does not bother about this logic,model doesn't interact with the end user.


View

View is responsible for the presentation  logic of the application , it represent the output   to the user.
it obtains data from the model and presents it to the user.

 
Controller

Controller is responsible for communication between model and view it send commands to the model to update the model's state (e.g., updating database). It can also send commands to its associated view to change the view's presentation of the model (e.g., Present the updated view).

 

Benefits of MVC

 

Substitutable user interface
 
Different views and controllers can be substituted to provide alternate user interfaces for the same model. For example, the same model data can be displayed as a bar graph, or a pie chart, or a spreadsheet.

Multiple simultaneous views of the same model
Multiple different views can be active at the same time. Each view simultaneously and independently presents the same information from the model. This applies more to GUI MVC than web MVC. 

Syncronized views
 The change propagation mechanism insures that all views simultaneously reflect the current state of the model.

Easier user interface changes 
Changes affecting just the user interface of the application logic become easier to make.

Easier testing
With MVC it can be easier to test the core of the application, as encapsulated by the model.

 




 

 








 

Thursday, 26 September 2013

PHP Class For Mobile Device Detection: Mobile_Detect

Mobile_Detect is an open source PHP class for detecting mobile devices.

It uses the User-Agent string combined with various HTTP headers in order to detect the mobile environment.

The class can easily understand whether the platform is mobile, tablet or desktop.


Also, functions exist for detecting whether it is iPad, iPhone, Android, Blackberry, etc. And, we can even drill-down to the versions of the platforms and browsers if needed.
It has a huge library of devices (including Nook, Nexus, Kindle, Archos..) and browsers for a stable detection.

Wednesday, 25 September 2013

Login or Register With Yahoo Open Id in PHP

This article will guide you to crate login or register with Yahoo.

The process and steps are same as login or register through Gmail. You only need to change the path from https://www.yahoo.com/accounts/o8/id to https://me.yahoo.com.

Step1:

Include your database connection file and openid.php to you login page.
Here you can download openid.php  file.

<?php
 include('connection.php');
 require_once 'yahoo/openid.php';
 $yahooid = new LightOpenID("localhost");//your damain name
 $yahooid->identity = 'https://www.yahoo.com/accounts/o8/id';
 $yahooid->required = array(
   'namePerson/first',
   'namePerson/last',
   'contact/email',);
$yahooid->returnUrl = 'http://xxx.com/login-yahoo.php';
?>

Now Add the following code to "Login with Yahoo" button.

<a href="<?php echo $yahooid->authUrl() ?>">Login with Yahoo</a>

If the user enters the correct info then Yahoo page will redirect back to or login page with required information's.

if ($yahooid->mode == 'cancel') {
echo "User has canceled authentication !";
} elseif($yahooid->validate()) {
$data = $yahooid->getAttributes();
$email = $data['contact/email'];
$firstname = $data['namePerson/first'];
$lastname = $data['namePerson/last'];

$Identity = explode("=",$yahooid->identity);
$userid = $Identity[1];
$loginwith = 'Yahoo';

$sql = mysql_query("select userid from register where passcode='".$userid."'");
$numrow = mysql_num_rows($sql);
if($numrow > 0){
header('Location:myaccount.php');
exit();
}
}

If the user registered before then our system will redirect the user to my account page otherwise it will ask the user to register for the first time.

if($_POST['register']){
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$passcode = mysql_real_escape_string($_POST['passcode']);
$loginwith = mysql_real_escape_string($_POST['loginwith']);
$status = 'active';
$mysql = mysql_query("insert into register set fastname = '".$fname."',
lastname = '".$lname."',
email = '".$email."',
passcode = '".$passcode."',
loginwith = '".$loginwith."',
status = '".$status."'");
header('Location:myaccount.php');
}

The MySql table used in this project

CREATE TABLE IF NOT EXISTS `register` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`fastname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`passcode` varchar(100) NOT NULL,
`loginwith` varchar(20) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`userid`),
UNIQUE KEY `userid` (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Login/ Register Using Google Open Id in PHP

This summary is not available. Please click here to view the post.

Display User feeds from Twitter in webpage

Though Twitter has lunched API Ver1.1, most of the application developed in older version API will not work, You need to migrate your application to Ver1.1 and which requires Authentication on all endpoints and support JSON only. Lets discuss how to display User feeds from Twitter in you website.

The first thing you need to create an application in twitter and get the following
 - oauth access token
 - oauth access token secret
 - consumer key
 - consumer secret
This you can create in dev.twitter.com, by using your twitter user name and password.

Then you need TwitterAPIExchange.php class file which you can download from here.

Now copy paste the following code to get user Twitter Feeds.
Note: Click here to generate App ID/API Key for Twitter.
 
<?php
include("TwitterAPIExchange.php");

$settings = array(
'oauth_access_token' => "Enter Your Access Token",
'oauth_access_token_secret' => "Enter Your Token Secret",
'consumer_key' => "Enter Your Consumer Key",
'consumer_secret' => "Enter Your Consumer Secret"
);

$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=a2zwebhelp';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();

/* Here you will get all info from user timeline */
var_dump(json_decode($response));
?>
Copy/ paste the following code to display user feeds
<?php
$valid_data = json_decode($response); //JSON data to PHP.
print "<ul>";
  foreach ($valid_data as $key=>$value) {
    print "<li>";
    print $value->text;
    print "</li>";
  }
print "</ul>";
?>

Export Database table to CSV using PHP

Lets write a simple php program to export data from MySql table to CSV file.

PHP Code

<?php

// Database Connection

$host="localhost";
$uname="root";
$pass="";
$database = "database-name"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or 
die("Database could not be selected"); 
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = ""; // Enter Your Table Name 
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>


What is cURL and how to use cURL in PHP

Introduction

cURL stands for client URL

curl is a command line tool for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks.

PHP cURL allows you to read websites, make automated logins, upload files and many more.

Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

Example

Now that you know what cURL is, I think it’s time to look at some code.

<?php
$ch = curl_init ("http://www.yahoo.com");//Initialize curl with the URL of yahoo
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
/*Tell php curl that we want the data returned to us instead of being displayed*/ 
 $yahoo = curl_exec ($ch);//Execute curl and put the output in $yahoo.
?>


The power of PHP cURL lies within the curl_setopt() function. This function instructs cURL of what exactly we want to do. Let’s say, what if a webpage that you want to access checks for the HTTP_REFERER header? Or perhaps, what if you need to access a webpage that works correctly only if cookies are enabled? for more parameters of  curl_setopt() click here .

Here’s another example… This time we specify the HTTP_REFERER…

<?php
$ch = curl_init ("http://www.somedomain.com/page2.php");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somedomain.com/page1.php");
$page = curl_exec ($ch);
?>



In this example, the CURLOPT_REFERER line tells cURL to set the HTTP_REFERER header to http://www.somedomain.com/page1.php.

PHP cURL can do more. It can send POST data, it can log on to a website and automate tasks as if it was a real person and much more.

Tuesday, 24 September 2013

Multiple Like Buttons on a Single Page on multiple images

My last post explained how to put a Like button on a web page. That sets us up nicely to explain how to make different Like buttons for different parts of a page.
For example, imagine you have a page that lists all of your books. You could have a Like button for each of them right below the cover image.

Sound good? Let's get going then.

For the purpose of this post, let's say you have a small-to-medium-sized website. It has a home page, a page about you, a page that lists all your books and stories, and a simple form for contacting you. It's nothing fancy, but it's a start. And it looks good.

  Because you read my last post, you added a Like button to your home page. Now, you want to add a Like button for each of your books, but you've got a problem. The way the Like button works, it uses the entire page. Even though you put a button next to each book, they all seem to Like the entire page. That's not what you want.

It's a tricky problem, but there is a solution.

Step 1) More Pages

Because you have to Like whole pages, that means you need to create a separate page for each book.

Each page should have the book cover image and your hook (1-2 sentences that describe your book). Fill in the Open Graph tags just the way I explained in my previous article. The page can also have blurbs, snippets, buy links, ISBN, etc. The key is that the page is devoted to the book.

Don't forget to include a Like button on this page.

Step 2) Can You Feel the Like?

Go back to your main books page--the one that has all your books and stories. Add Like buttons to each one just like you did before. The code will look something like this:

<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
...
<!-- AddThis Button END -->


Here's the key. In the first div tag, add the following attribute:

<!-- AddThis Button BEGIN -->

<div class="addthis_toolbox addthis_default_style " addthis:url="http://url/to/your/book/page">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
...
<!-- AddThis Button END -->

That's all there is to it.

Now, when someone uses that Like button, it will like the book page just as if they clicked the Like button on the book page itself.

This will work for anything. Just setup a page for the thing you want Liked. Then create a Like button using the page URL. This button can be used on as many different pages as you want.

Add social network button in webpage

Today, it’s important for business owners to realize that social media is a powerful marketing tool and that it’s here to stay. To ensure that your business succeeds, it’s essential to focus on social media integration when it comes to web design as you’ll be better able to drive transactions and make valuable connections with your customers. You can’t succeed by simply spreading your messages to the world via social media nor can you rely solely on your website to drive sales. Here are a few ways you can integrate social media into your website design.

I'm recommending you go out to Add This and grab their code. AddThis is used by some big sites. They are simple to use and have a lot of ways to tinker with their stuff if you're the tinkering type.

When you download their code, they'll ask you to create an account. It's not required, so if you want to try them out first, that's fine. Just dismiss the sign-up window.


Add a Facebook Like Button to a Webpage using Add This Tool

Today, it’s important for business owners to realize that social media is a powerful marketing tool and that it’s here to stay. To ensure that your business succeeds, it’s essential to focus on social media integration when it comes to web design as you’ll be better able to drive transactions and make valuable connections with your customers. You can’t succeed by simply spreading your messages to the world via social media nor can you rely solely on your website to drive sales. Here are a few ways you can integrate social media into your website design.

I'm recommending you go out to AddThis and grab their code. AddThis is used by some big sites. They are simple to use and have a lot of ways to tinker with their stuff if you're the tinkering type.

When you download their code, they'll ask you to create an account. It's not required, so if you want to try them out first, that's fine. Just dismiss the sign-up window. 

Have you ever gone to like a webpage and Facebook decides it wants to use the "Email Me" picture of a giant @ sign instead of the site logo, or the description that comes up is the "About the Author" text instead of the first paragraph of the page? Frustrating, isn't it.

You solve these issues for your site using Open Graph tags. These are meta tags you include at the top of your html page that help Facebook and other sites figure out what's most important.


Monday, 23 September 2013

More .htaccess Examples

Deny/Allow Certain IP Addresses

Block an IP Address
#Deny List

order allow,deny
deny from 123.123.123.123 #specify a specific address
deny from 123.123.123.123/30 #specify a subnet range
deny from 123.123.* #specify an IP address wildcard
allow from all

Allow an IP address
#Allow List

order allow,deny
allow from 123.123.123.123 #specify a specific address
allow from 123.123.123.123/30 #specify a subnet range
allow from 123.123.* #specify an IP address wildcard 
deny from all

Disable directory browsing
For security reason it is always better to disable directory browsing so that people won’t know what files you have. The following code will do so.
Options All -Indexes
Adding MIME Types
If your server is not set up to deliver certain file like MP3 or SWF properly then you can add the MIME type for those through .htaccess.
AddType application/x-shockwave-flash swf
Change your default directory page
Through DirectoryIndex you can change your default landing page of your website. The default landing pages are index.html, index.php, default.php etc. But if want to change it to some other page then please use the following code.
DirectoryIndex filename.html
Protect .htaccess files

order allow,deny
deny from all

Protect php.ini file

order allow,deny
deny from all

Preventing hotlinking

What is Hotlinking or Bandwidth Theft?
When someone uses a link to an image , video or any other file that is saved on another website is known as hotlinking. For example, instead of saving video.flv on to your own website, if you uses a link to the video as http://domain.com/video.flv is known as hotlinking. Following is the .htaccess code to prevent hotlinking.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|js|css)$ - [F]
You can also show different file when hotlink is detected.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.domain.com/404.html [R,L] 
Force Caching with htaccess
The following htaccess code won’t help the initial pageload, but it will significantly help subsequent pageloads by sending 304 statuses when requested elements haven’t been modified.
FileETag MTime Size
ExpiresActive on
ExpiresDefault "access plus x seconds"
Check Spelling directive
This directive can be useful to auto-correct simple spelling errors in the URL

CheckSpelling On
 

Create custom error pages through .htaccess file

This is always a best practices to create your own error page rather showing the host default page. You can use your own custom error pages for any know error like 404 - page not found, 500 - Internal Server Error etc.
It can be simply done by adding the following code to your .htaccess file.
ErrorDocument errornumber /file.html
1. 404 - page not found
RewriteEngine On
ErrorDocument 404 /404.html
2. 500 - Internal Server Error
RewriteEngine On
ErrorDocument 500 /500.html
3. 403 - Forbidden
RewriteEngine On
ErrorDocument 403 /403.html
4. 400 - Bad request
RewriteEngine On
ErrorDocument 400 /400.html
5. 401 - Authorization Required
RewriteEngine On
ErrorDocument 401 /401.html
You can also redirect all error to single page. like
RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

URL redirect through .htaccess file

URL rewrite helps you to hide your extension name or show different extension name like index.php can be displayed as index.html or only index or home etc.
The following code will rewrite anyfile.php to anyfile.html
RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php
The following code will rewrite index.php to index
RewriteEngine on
RewriteRule ^index index.php

Few Example to create SEO friendly URL.

1. Rewrite product.php?id=1 to product-1.html
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
2. Rewrite product.php?id=12 to product/cat/12.html
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
3. Rewrite domain.com/member.php?username=arup to domain.com/susil
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
4. Rewrite domain.com/users.php?id=username&page=2 to domain.com/username/2
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)$ users.php?user=$1&page=$2
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)/$ users.php?user=$1&page=$2

What is .htassess file and its uses ?

The .htaccess file is a general text file, which can be create using Notepad or any text editor. This file contains the configuration statements/ commands to customize the Apache Web server as per user requirement.

How to create a .htaccess file?

if you try to create a .htaccess file in Windows it will not allow you to do so because the file won't have a name. To solve this problem you can create a file called htaccess.txt then transfer it to your web server and rename it to .htaccess. Then you can download the file, edit save and re upload. or Very simple method open any editor like notepad go to file save within double quotations write ".htacess" the file will be created. Also you can do it through command prompt. Open Command Window (window key + r) type "command" press ok. Now change to root directory. CD\ + enter Type: copy con .htaccess press enter. Now press ctrl + z to save the file. You can check if your file is created or not.

What are the use of .htaccess file?

.htaccess file helps you to Password protect you website, Deny/ Allow remote hosts or IP from your web site, Protecting your images and other files from linking, Add Security to your PHP projects, URL redirect/rewrite etc.

URL redirect using the .htaccess file

1. Add www by default to your URL.

301 redirect forcing all http requests to redirect from domain.com to www.domain.com
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

2. Remove www by default from your URL.

301 redirect forcing all http requests to redirect from www.domain.com to domain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteRule ^/?$ "http\:\/\/domain\.com\/" [R=301,L]

3. Redirect from domain.com to domain.com/index.html

If you want to redirect all incoming URLs from domain.com/ to domain.com/index.html then use the following code.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^$ http://example.com/index.php [L,R=301]

4. How to add a trailing slash

Like Yahoo some search engines remove the trailing slash from URLs. So it creates duplicated content problems when the same page content is accessible under different URLs. Per example domain.com/google/ will index in Yahoo as domain.com/google - which would result two different URLs with the same content.
To solve this problem lets add a trailing slash to the URLs
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !example.php
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://example.com/$1/ [L,R=301]

5.Redirect visitors from old site to a new site

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

Password Protection with htaccess

With .htaccess it is very easy to password protect a folder or directory. The method is called htaccess password protection or htaccess authentication, and works by uploading two files called .htaccess and .htpasswd in the directory you want to password protect. The htaccess file should contain the following:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
 
You only need to change “/path/to/.htpasswd” with the full path to your .htpasswd. Take a look at my article on how to find the full path using PHP. Next you need to upload the .htpasswd file which contains the username and password to enter the password protected folder. The .htpasswd file should contain:

test:dGRkPurkuWmW2
 
The above code will allow the user “test” to access the password proteced area with the password “test”. The text “dGRkPurkuWmW2″ is a encrypted version of the password. You will need to use a htpasswd generator to create another password. Each line in the .htpasswd file contains a username and password combination, so feel free to add as many combinations as you like.

The automatic way – Use the generator
You can also just use the htaccess authentication generator to create a htaccess file for password protection.

Get Domain name country state city region By using Geoip info data

You can get the domain name of server country,state and region of the server by following code
this function accept the ip address which you can get from the $_SERVER variable of php


Folowing function return  an array with geoip-infodata
<?php function geoCheckIP($ip)
{
 //check, if the provided ip is valid
  if(!filter_var($ip, FILTER_VALIDATE_IP))
  {
     throw new InvalidArgumentException("IP is not valid");
 }

 //contact ip-server
 $response=@file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
 throw new InvalidArgumentException("Error contacting Geo-IP-Server");
 }

 //Array containing all regex-patterns necessary to extract ip-geoinfo from page
 $patterns=array();
  $patterns["domain"] = '#Domain: (.*?)&nbsp;#i';
 $patterns["country"] = '#Country: (.*?)&nbsp;#i';
$patterns["state"] = '#State/Region: (.*?)<br#i';
 $patterns["town"] = '#City: (.*?)<br#i';

 //Array where results will be stored
 $ipInfo=array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
 {
 //store the result in array
 $ipInfo[$key] = preg_match($pattern,$response,$value)
 && !empty($value[1]) ? $value[1] : 'not found';
}

  return $ipInfo;
}?>


Call the above function

<?php  $ip=$_SERVER['REMOTE_ADDR'];
 print_r(geoCheckIP($ip)); ?>


Example:


Array
(
    [domain] => 106.215.57.31
    [country] => IN - India
    [state] => bla bla
    [town] =>bla bla
)


How to Easily Add Custom Classes to Your First and Last Menu Items in WordPress

Sometimes you want to be able to style your first and/or last menu items differently from the rest. Maybe you want to remove padding, shift margins, or the like.


The code snippet below will apply the classes to all menus on your site( add in function.php file of your theme):


add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class' );


function tgm_filter_menu_class( $objects ) {
// Add "first-menu-item" class to the first menu object
$objects[1]->classes[] = 'first-menu-item';
// Add "last-menu-item" class to the last menu object
$objects[count( $objects )]->classes[] = 'last-menu-item';
// Return the menu objects
return $objects;


}
If you want to go a step further and limit this to only a particular navigation menu on your site, 
check out the code below:
 
add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class', 10, 2 );


function tgm_filter_menu_class( $objects, $args ) {
// Only apply the classes to the primary navigation menu
if ( isset( $args->theme_location ) )
if ( 'primary' !== $args->theme_location )
return $objects;
// Add "first-menu-item" class to the first menu object
$objects[1]->classes[] = 'first-menu-item';
// Add "last-menu-item" class to the last menu object
$objects[count( $objects )]->classes[] = 'last-menu-item';
// Return the menu objects
return $objects;
}
Now if you have noticed above, these two pieces of code are really only effective for top level menus (e.g. menus with no dropdowns). If you want to add the same class structure to nested menus,use the code below. It will do the exact same thing as above,except for it will apply the logic to all nested submenus in your menu structure.
add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class', 10, 2 );


function tgm_filter_menu_class( $objects, $args ) {
// Add first/last classes to nested menu items
$ids = array();
$parent_ids = array();
$top_ids = array();
foreach ( $objects as $i => $object ) {
// If there is no menu item parent, store the ID and skip over the object
if ( 0 == $object->menu_item_parent ) {
$top_ids[$i] = $object;
continue;
}
// Add first item class to nested menus
if ( ! in_array( $object->menu_item_parent, $ids ) ) {
$objects[$i]->classes[] = 'first-menu-item';
$ids[] = $object->menu_item_parent;
}
// If we have just added the first menu item class, skip over adding the ID
if ( in_array( 'first-menu-item', $object->classes ) )
continue;
// Store the menu parent IDs in an array
$parent_ids[$i] = $object->menu_item_parent;
}
// Remove any duplicate values and pull out the last menu item
$sanitized_parent_ids = array_unique( array_reverse( $parent_ids, true ) );
// Loop through the IDs and add the last menu item class to the appropriate objects
foreach ( $sanitized_parent_ids as $i => $id )
$objects[$i]->classes[] = 'last-menu-item';
// Finish it off by adding classes to the top level menu items
$objects[1]->classes[] = 'first-menu-item'; // We can be assured 1 will be the first item in the menu :-)
$objects[end( array_keys( $top_ids ) )]->classes[] = 'last-menu-item';
// Return the menu objects
return $objects;
}


 

Add html tag in wordpress nav menu item

If you want to add a html line break and other tag in the custom  menu title in wordpress then bellow code will be helpful add these codes in the function.php file of your theme folder.



Add following code in function.php file of your theme.


<?php 
function wpa_105883_menu_title_markup( $title, $id ){
    if ( is_nav_menu_item ( $id ) ){
        $title = str_ireplace( '#BR#', '<br/>', $title );
    }
    return $title;
}
add_filter( 'the_title', 'wpa_105883_menu_title_markup', 10, 2 );

?>


Now you can use "#BR#for <br /> in your custom menu title.






Create slug from a title in PHP

if you want to generate seo friendly slug url from the title of a post product or category like wordpress the use following code to generate the slug this code is taken from wordpress  just include the following function and the call the sanitize($arg) . Where $arg is the title.

<?php
function utf8_uri_encode( $utf8_string, $length = 0 ) {
    $unicode = '';
    $values = array();
    $num_octets = 1;
    $unicode_length = 0;

    $string_length = strlen( $utf8_string );
    for ($i = 0; $i < $string_length; $i++ ) {

        $value = ord( $utf8_string[ $i ] );

        if ( $value < 128 ) {
            if ( $length && ( $unicode_length >= $length ) )
                break;
            $unicode .= chr($value);
            $unicode_length++;
        } else {
            if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;

            $values[] = $value;

   if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
                break;
            if ( count( $values ) == $num_octets ) {
                if ($num_octets == 3) {
      $unicode .=
 '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
   $unicode_length += 9;
     } else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
                    $unicode_length += 6;
                }

                $values = array();
                $num_octets = 1;
            }
        }
    }

    return $unicode;
}

//taken from wordpress
function seems_utf8($str) {
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
        }
    }
    return true;
}

//function sanitize_title_with_dashes taken from wordpress
function sanitize($title) {
    $title = strip_tags($title);
    // Preserve escaped octets.
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    // Remove percent signs that are not part of an octet.
    $title = str_replace('%', '', $title);
    // Restore octets.
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        }
        $title = utf8_uri_encode($title, 200);
    }

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');

    return $title;
}



//Call sanitize function

sanitize('test tilte');
?>

Get date difference in PHP

 Following code is used for date difference 
 
<?php 
date_default_timezone_set("Asia/Calcutta");
//Set your time zone
 
/* this is the function for date difference */ 
function dt_differ($start, $end){
  $start = date("G:i:s:m:d:Y", strtotime($start));
  $date1=explode(":", $start);

  $end  = date("G:i:s:m:d:Y", strtotime($end));
  $date2=explode(":", $end);
 
  $starttime = mktime(date($date1[0]),date($date1[1]),
date($date1[2]),
  date($date1[3]),date($date1[4]),date($date1[5]));
  $endtime   = mktime(date($date2[0]),date($date2[1]),
date($date2[2]),
  date($date2[3]),date($date2[4]),date($date2[5]));

  $seconds_dif = $starttime-$endtime;

  return $seconds_dif;
} 
/* end of function */


  $today = date("Y-n-j H:i:s");
  $fromday = "2012-12-31 23:59:59";
  $timediffer = dt_differ($fromday, $today); 
//call date difference function
  echo $timediffer." seconds";