Add www To All URLs With htaccess

For SEO it is important to use a set standard of how you present your domain. The most popular approach is to use the sub-domain www. Many people don’t know this but http://www.domain.com is the same as http://domain.com, you will be sent to the same page but they will have different URLs.

For SEO if a search engine saw http://www.domain.com it will crawl this page, check the content and index the content. Then later if it goes and crawls http://domain.com the search engines will see the same content but on different URLs and think it is duplicate content and therefore will penalise this domain in the search engine ranking.

Consistent

The best way to get around this problem is to make sure that all your URLs on your site use a consistent URL format either http://www.domain.com or domain.com. It makes no difference which format you choose, the search engine just worries about duplicate content.

Use www

I prefer to make sure all my domains use www sub-domain, this is the format most people are used to seeing on search engines and web sites. If people are used to seeing it then they will not worry about the URL.

Now that you have chosen your preferred format and changed all your links to your site to use this format then you are done, right, wrong! If you stick just with this you run the risk of someone linking to you but forgetting to put a www on the front, the search engines will then crawl through this link and see duplicate content and penalise your domain.

To combat this problem you have a couple of options the best solution is to perform a check of the URL on each page if it doesn’t contain the www then perform a 301 redirect to your domain with the www sub-domain. The best way of using this solution is to use htaccess, this will run before any pages are loaded and allows you to change the URL with a 301 redirect.

.htaccess To Redirect URLs

To use htaccess to redirect URL just copy and paste the snippet below and replace example.com with your domain.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
Tagged with: , , , ,
Posted in APIs, ASP, Frameworks, PHP

Testing Your Web Designs in Different Browsers

multiple-browsers-testingWeb site themes offer web site owners a lot of flexibility when it comes to designing their site, but even the greatest web site theme or design doesn’t come without issues, such as how it interacts with different programs. For example, if it’s a flash based site, how does it operate on older versions of flash? Another issue that could arise is that with Firefox supporting Third-Party plugins there may be additional issues that result from that. While it would be impossible to download and install every possible Firefox plugin, downloading and installing the top 10 most popular ones wouldn’t be that difficult. The most popular user installed current version plugins can be found atLatestVersionPlugin.com.

internet-browsers

When to Test Your Design?

The best possible time to check your web design is early on in the implementation and construction phase. Basically you want to know right away how your site design functions within each browser, and while these is a time consuming processing, it’s also a worthwhile investment. Because a bad web design/site will result in your visitors, one leaving before they should and two not returning or spreading to word about your site. Which as we know will lead to a drop in traffic and income.

What to Test?

Before you start testing your new web site design you’ll need to create a list of items to test, one of the things you need to consider is any updates you did to the code. You’ll need to see if it functions in the same manner as before.

Things that you must test are:

  • Make sure that you are covering all the modern browsers i.e. latest versions of Chrome, Opera, Firefox, Safari and Internet Explorer (IE). You would find that most of them come with a proper updating system and testing the latest one can give you results for the older versions too.
  • You need to include all the previous versions of IE from 7 onwards. If you have access to windows machine then that won’t be difficult, otherwise you may need to use a browser testing service or emulator such asbrowserstack.com.
  • Testing your sites compatibility on mobile browsers is crucial now as a significant portion of web traffic is generated from mobile devices.

Which pages to test?

  • If you need to choose which pages should be tested the answer would depend upon the size of the web site and the number of pages. If there are huge number of pages then it’s okay to test only the ones which have different unique designs features. Always test against various screen resolution. By resizing the browser window while testing you can easily accomplish it. All these tests are done as because people have different taste and they use different browsers as per their need.

With a little bit of preparation and time, the shift to a new website can be seamless like any minor update that you do on your website.

Tagged with: , , , , ,
Posted in APIs, ASP, CSS, Frameworks, HTML, Javascript, PHP, Scripts

SQL vs NoSQL Database Differences Explained with few Example DB

Most of you are already familiar with SQL database, and have a good knowledge on either MySQL, Oracle, or other SQL databases. In the last several years, NoSQL database is getting widely adopted to solve various business problems.

It is helpful to understand the difference between SQL and NoSQL database, and some of available NoSQL database that you can play around with.

SQL vs NoSQL: High-Level Differences

  • SQL databases are primarily called as Relational Databases (RDBMS); whereas NoSQL database are primarily called as non-relational or distributed database.
  • SQL databases are table based databases whereas NoSQL databases are document based, key-value pairs, graph databases or wide-column stores. This means that SQL databases represent data in form of tables which consists of n number of rows of data whereas NoSQL databases are the collection of key-value pair, documents, graph databases or wide-column stores which do not have standard schema definitions which it needs to adhered to.
  • SQL databases have predefined schema whereas NoSQL databases have dynamic schema for unstructured data.
  • SQL databases are vertically scalable whereas the NoSQL databases are horizontally scalable. SQL databases are scaled by increasing the horse-power of the hardware. NoSQL databases are scaled by increasing the databases servers in the pool of resources to reduce the load.
  • SQL databases uses SQL ( structured query language ) for defining and manipulating the data, which is very powerful. In NoSQL database, queries are focused on collection of documents. Sometimes it is also called as UnQL (Unstructured Query Language). The syntax of using UnQL varies from database to database.
  • SQL database examples: MySql, Oracle, Sqlite, Postgres and MS-SQL. NoSQL database examples: MongoDB, BigTable, Redis, RavenDb, Cassandra, Hbase, Neo4j and CouchDb
  • For complex queries: SQL databases are good fit for the complex query intensive environment whereas NoSQL databases are not good fit for complex queries. On a high-level, NoSQL don’t have standard interfaces to perform complex queries, and the queries themselves in NoSQL are not as powerful as SQL query language.
  • For the type of data to be stored: SQL databases are not best fit for hierarchical data storage. But, NoSQL database fits better for the hierarchical data storage as it follows the key-value pair way of storing data similar to JSON data. NoSQL database are highly preferred for large data set (i.e for big data). Hbase is an example for this purpose.
  • For scalability: In most typical situations, SQL databases are vertically scalable. You can manage increasing load by increasing the CPU, RAM, SSD, etc, on a single server. On the other hand, NoSQL databases are horizontally scalable. You can just add few more servers easily in your NoSQL database infrastructure to handle the large traffic.
  • For high transactional based application: SQL databases are best fit for heavy duty transactional type applications, as it is more stable and promises the atomicity as well as integrity of the data. While you can use NoSQL for transactions purpose, it is still not comparable and sable enough in high load and for complex transactional applications.
  • For support: Excellent support are available for all SQL database from their vendors. There are also lot of independent consultations who can help you with SQL database for a very large scale deployments. For some NoSQL database you still have to rely on community support, and only limited outside experts are available for you to setup and deploy your large scale NoSQL deployments.
  • For properties: SQL databases emphasizes on ACID properties ( Atomicity, Consistency, Isolation and Durability) whereas the NoSQL database follows the Brewers CAP theorem ( Consistency, Availability and Partition tolerance )
  • For DB types: On a high-level, we can classify SQL databases as either open-source or close-sourced from commercial vendors. NoSQL databases can be classified on the basis of way of storing data as graph databases, key-value store databases, document store databases, column store database and XML databases.

SQL Database Examples

1. MySQL Community Edition

MySQL database is very popular open-source database. It is generally been stacked with apache and PHP, although it can be also stacked with nginx and server side javascripting using Node js. The following are some of MySQL benefits and strengths:

  • Replication: By replicating MySQL database across multiple nodes the work load can be reduced heavily increasing the scalability and availability of business application
  • Sharding: MySQL sharding os useful when there is large no of write operations in a high traffic website. By sharding MySQL servers, the application is partitioned into multiple servers dividing the database into small chunks. As low cost servers can be deployed for this purpose, this is cost effective.
  • Memcached as a NoSQL API to MySQL: Memcached can be used to increase the performance of the data retrieval operations giving an advantage of NoSQL api to MySQL server.
  • Maturity: This database has been around for a long time and tremendous community input and testing has gone into this database making it very stable.
  • Wide range of Platforms and Languages: MySql is available for all major platforms like Linux, Windows, Mac, BSD and Solaris. It also has connectors to languages like Node.js, Ruby, C#, C++, C, Java, Perl, PHP and Python.
  • Cost effectiveness: It is open source and free.

2. MS-SQL Server Express Edition

It is a powerful and user friendly database which has good stability, reliability and scalability with support from Microsoft. The following are some of MS-SQL benefits and strengths:

  • Integrated Development Environment: Microsoft visual studio, Sql Server Management Studio and Visual Developer tools provide a very helpful way for development and increase the developers productivity.
  • Disaster Recovery: It has good disaster recovery mechanism including database mirroring, fail over clustering and RAID partitioning.
  • Cloud back-up: Microsoft also provides cloud storage when you perform a cloud-backup of your database

3. Oracle Express Edition

It is a limited edition of Oracle Enterprise Edition server with certain limitations. This database is free for development and deployment. The following are some of Oracle benefits and strengths:

  • Easy to Upgrade: Can be easily upgraded to newer version, or to an enterprise edition.
  • Wide platform support: It supports a wide range of platforms including Linux and Windows
  • Scalability: Although the scalability of this database is not cost effective as MySQL server, but the solution is very reliable, secure, easily manageable and productive.

NoSQL Database Examples

1. MongoDB

Mongodb is one of the most popular document based NoSQL database as it stores data in JSON like documents. It is non-relational database with dynamic schema. It has been developed by the founders of DoubleClick, written in C++ and is currently being used by some big companies like The New York Times, Craigslist, MTV Networks. The following are some of MongoDB benefits and strengths:

  • Speed: For simple queries, it gives good performance, as all the related data are in single document which eliminates the join operations.
  • Scalability: It is horizontally scalable i.e. you can reduce the workload by increasing the number of servers in your resource pool instead of relying on a stand alone resource.
  • Manageable: It is easy to use for both developers and administrators. This also gives the ability to shard database
  • Dynamic Schema: Its gives you the flexibility to evolve your data schema without modifying the existing data

2. CouchDB

CouchDB is also a document based NoSQL database. It stores data in form of JSON documents. The following are some of CouchDB benefits and strengths:

  • Schema-less: As a member of NoSQL family, it also have dynamic schema which makes it more flexible, having a form of JSON documents for storing data.
  • HTTP query: You can access your database documents using your web browser.
  • Conflict Resolution: It has automatic conflict detection which is useful while in a distributed database.
  • Easy Replication: Implementing replication is fairly straight forward

3. Redis

Redis is another Open Source NoSQL database which is mainly used because of its lightening speed. It is written in ANSI C language. The following are some of Redis benefits and strengths:

  • Data structures: Redis provides efficient data structures to an extend that it is sometimes called as data structure server. The keys stored in database can be hashes, lists, strings, sorted or unsorted sets.
  • Redis as Cache: You can use Redis as a cache by implementing keys with limited time to live to improve the performance.
  • Very fast: It is consider as one of the fastest NoSQL server as it works with the in-memory dataset.
Tagged with: , , , , , , , ,
Posted in SQL

8 Online Payment Options That Aren’t PayPal

When most people think of online payments, one name comes to mind: PayPal.

00 - PayPal

But for all PayPal’s strengths, it’s a bad idea to rely on it as the single system to accept payments on your site. Monopolies are never healthy, and you need to diversify your payment channels.

Why You Need PayPal Alternatives

There are plenty of reasons why you should support multiple payment options, but here are several of the most important ones:

  • Your partners or customers can’t always make or accept PayPal payments. This is the major reason to offer payment alternatives. There are always people who can’t (or won’t) pay or receive money via PayPal. In this case, if you are not open to alternatives, you simply lose these customers or partners. On the other hand, you need to make some estimates if the gain is worth the extra effort. It might turn out that offering more options doesn’t increase your income but does increase your costs and hassle.
  • Your PayPal account could be blocked. We have all heard horror stories about PayPal blocking accounts for various reasons, or for no reason at all (so the victims claim). Even if these stories are not 100% true, it would still be a nightmare if it happened to you. You shouldn’t put all your payment eggs in one basket–the risk is too high.
  • You need a safer way to receive payments, especially for larger sums. PayPal is very convenient for small amounts but if you regularly send or receive thousands of dollars, then you are better of with other forms of payments, such as checks or wire transfer.
  • You want to reduce costs. PayPal fees are certainly not the lowest in the industry, so you might end up paying hundreds or even thousands of dollars a month in commissions. There are lower cost alternatives but unfortunately they have other limitations. In fact, if reducing costs is your main reason to look for PayPal alternatives, your options are limited.

If any of these reasons apply to you, then you should definitely consider using other online payment systems to supplement or even replace PayPal.

Best PayPal Alternatives

There is no single PayPal alternative that is best in all cases–the right option depends on your needs.

Since PayPal is global, a real alternative needs to be global, too. The best services that can be used for international transfers are: Skrill, Google Wallet, Payoneer and Payza.

In addition to these, there are dozens of local and regional ones payment processors. These services could be good for you, though if you have international clients or partners they’re not much use.

1. Skrill

01 - Skrill

Skrill, formerly known as Moneybookers, is one of the few true alternatives to PayPal. Though it is global in nature, it’s targeted mainly at U.K. and the other European countries because the merchant fees for these regions are more favorable than for the rest of the world.

Skrill is one of the more popular PayPal alternatives, so if you want to send money to somebody, he or she might have already heard about Skrill, or even have an account. Skrill is also widely accepted by many top websites and service providers, including Skype, eBay and oDesk.

Skrill is easy to use and it allows to transfer your account balance onto a prepaid debit card almost right away.

The fees for personal transfers are very low, though they very from country to country. With a 1% sending fee (capped at a maximum of €10) and no receiving fees, it’s one of the best offers on the market.

With merchants, the fees are much higher, though still acceptable. You can check the fees here. Currently their rates range from 1.4% + £0.20 for U.K. merchants with more than €50,000 monthly sales volume, to 3.9% + €0.35 for non European merchants with monthly sales volume of up to €2,500.

2. Google Wallet

02 - Google Wallet

Google Wallet, formerly known as Google Checkout, is another good online payment system with global reach. It might not have all the features of PayPal but for personal and business payments it does a good job.

Google Wallet’s fees are reasonable–it’s free to send money directly from your bank account or from your Google Wallet balance. If you want to send money via credit card, then the fee is 2.9%. Unlike PayPal, it’s also free to you receive money or transfer it to your bank account.

There are some per transaction and other limits ($10,000 USD per single transaction and no more than $50,000 USD per 5 day period) but they are something to worry about only if you have a huge turnover (in which case you will most likely be using wire transfer anyway). One of the limits I personally find peculiar is the $500 limit per 30 days for uploading money to your Wallet Balance with a credit or debit card, but this is hardly a deal breaker.

3. Payoneer

03 - Payoneer

Payoneer is very similar to the other international services on this list. Probably what makes it truly different is that with it you can get a virtual U.S. bank account. This is of great importance to everybody who is not in the US but who needs to get money in a U.S. bank. (If this might pose legal issues in your country, check with a local lawyer.)

As for fees, Payoneer is not cheap. First, it has an annual fee of $29.95. Second, withdrawal from an ATM costs about $3. Third, there are transaction fees (they differ based on volume and location).

Despite its high fees, Payoneer has managed to become popular. Many sites now accept it, and some of the best affiliate marketing networks have embraced it as well.

4. Payza

04 - Payza

Payza (formerly known as AlertPay) is very similar to the preceeding payment options. It is available in more than 190 countries. It offers generally low fees (though this varies on your location and the type of the transaction) and some of the services are even free. It seems to be the least popular of the PayPal alternatives but still many sites accept it.

Bonus: Local Payment Systems

The availability of local payment services is astonishing, especially for the U.S. Some of the best options include: Stripe, Paymate, Amazon Payments, and Dwolla.

Of all the non-global payment alternatives Stripe is the most promising. Currently they cover the U.S., Canada, U.K., and Ireland but they are also available in beta in another 10 or so countries. At 2.9% + $0.30 per transaction, their fees are similar to PayPal’s. Stripe also has great customization capabilities that might be of interest to developers.

Paymate is a good option for sellers in New Zealand and Australia, though cards from 60-plus countries are also accepted. They have relatively high monthly fees and transaction fees. However, one of the advantages of Paymate is that you can use it to collect payments on eBay.com.au.

Amazon Payments is a good option if you are looking for a credit and debit card processing and an eCommerce platform. It’s an option for U.S. sellers only and it’s fairly pricey for low sales volumes. You can use Amazon Payments on Amazon.com, of course, and some other sites also accept it as a form of payment.

If you are looking for a PayPal alternative mainly for personal payments and you are in the U.S., then Dwolla is probably your best option. With a cost of just $0.25 per transaction and no fees for transactions under $10, it beats all the other systems in terms of fees.

In addition to these systems, there are dozens of payment processors that target particular countries, so do your homework if you only need to sell in-country.

There’s No Perfect PayPal Replacement

While there are plenty of online payment systems, none can really replace PayPal completely.

Your best bet is using alternatives to reduce your reliance on PayPal while still offering PayPal as an option.

If you try to eliminate it completely, chances are good that most of your clients or partners won’t follow you.

Tagged with: , , , ,
Posted in APIs, ASP, CSS, Frameworks, Giveaway Stuff, HTML, Javascript, PHP, Scripts, Snippets

How to call javascript function instead of href in HTML

call javascript function in href

<a href="javascript:void(0);" onclick="foo(2367,146986,2);">

or

<a href="javascript:foo(2367,146986,2);">
Tagged with: , ,
Posted in HTML, Javascript

Top 10 Programming Languages in 2014

1. Java

Java

What it is: Java is a class-based, object-oriented programming language developed by Sun Microsystems in the 1990s. It’s one of the most in-demand programming languages, a standard for enterprise software, web-based content, games and mobile apps, as well as the Android operating system. Java is designed to work across multiple software platforms, meaning a program written on Mac OS X, for example, could also run on Windows.

 

2. C Language

C Language

What it is: A general-purpose, imperative programming language developed in the early ’70s, C is the oldest and most widely used language, providing the building blocks for other popular languages, such as C#, Java, JavaScript and Python. C is mostly used for implementing operating systems and embedded applications.

Because it provides the foundation for many other languages, it is advisable to learn C (and C++) before moving on to others.

 

3. C++

C Plus Plus

What it is: C++ is an intermediate-level language with object-oriented programming features, originally designed to enhance the C language. C++ powers major software like Firefox, Winamp and Adobe programs. It’s used to develop systems software, application software, high-performance server and client applications and video games.

 

4. C#

C Sharp

What it is: Pronounced “C-sharp,” C# is a multi-paradigm language developed by Microsoft as part of its .NET initiative. Combining principles from C and C++, C# is a general-purpose language used to develop software for Microsoft and Windows platforms.

 

5. Objective-C

Objective-C

What it is: Objective-C is a general-purpose, object-oriented programming language used by the Apple operating system. It powers Apple’s OS X and iOS, as well as its APIs, and can be used to create iPhone apps, which has generated a huge demand for this once-outmoded programming language.

 

6. PHP

PHP

What it is: PHP (Hypertext Processor) is a free, server-side scripting language designed for dynamic websites and app development. It can be directly embedded into an HTML source document rather than an external file, which has made it a popular programming language for web developers. PHP powers more than 200 million websites, including WordPress, Digg and Facebook.

 

7. Python

Python

What it is: Python is a high-level, server-side scripting language for websites and mobile apps. It’s considered a fairly easy language for beginners due to its readability and compact syntax, meaning developers can use fewer lines of code to express a concept than they would in other languages. It powers the web apps for Instagram, Pinterest and Rdio through its associated web framework, Django, and is used by Google, Yahoo! and NASA.

 

8. Ruby

Ruby

What it is: A dynamic, object-oriented scripting language for developing websites and mobile apps, Ruby was designed to be simple and easy to write. It powers the Ruby on Rails (or Rails) framework, which is used on Scribd, GitHub, Groupon and Shopify. Like Python, Ruby is considered a fairly user-friendly language for beginners.

 

9. JavaScript

JavaScript

What it is: JavaScript is a client and server-side scripting language developed by Netscape that derives much of its syntax from C. It can be used across multiple web browsers and is considered essential for developing interactive or animated web functions. It is also used in game development and writing desktop applications. JavaScript interpreters are embedded in Google’s Chrome extensions, Apple’s Safari extensions, Adobe Acrobat and Reader, and Adobe’s Creative Suite.

 

10. SQL

SQL

What it is: Structured Query Language (SQL) is a special-purpose language for managing data in relational database management systems. It is most commonly used for its “Query” function, which searches informational databases. SQL was standardized by the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO) in the 1980s.

Tagged with: , , , , , , , , , , , , , ,
Posted in APIs, ASP, CSS, Frameworks, Giveaway Stuff, HTML, Javascript, PHP, Scripts, Snippets, SQL, Uncategorized

How to Set Up PayPal Integration with PHP & MySQL

PayPal is the most popular payment service on the web so being able to integrate your website with PayPal’s Instant Payment Notification Service (IPN) is essential if you need to process payments through your website.

There are 3 main parts to the PayPal IPN system.

  1. A webpage that initiates a request to PayPal to make a payment.
  2. A PHP page on your webserver that PayPal calls to notify you that payment has been made.
  3. A webpage that confirms the above payment and continues on to the next phase of your web application, such as a ‘Thank You’ page.

Parts 1 and 3 are accessible by customers on your website. Part 2 is only visible to PayPal.  The diagram below illustrates the interaction between your customer, PayPal and your website.

PayPal Interaction

The following steps break down each part of the process into easy to follow chunks, it is assumed that you have knowledge of PHP and MySQL.

Step 1 – Setup PayPal Account

Sign up for a PayPal account if you don’t already have one. Select an appropriate account type, either Personal or Business.

Once you have a registered PayPal account your account must be setup correctly to use IPN.

Select ‘edit profile’ from your PayPal account and check the following settings.

  • Under ‘Selling Preferences’ >> ‘Instant Payment Notification Preferences’
  • Under ‘Selling Preferences’ >> ‘payment receiving preferences’
    • Block payments from users who pay with echeck. (This is because these will not be instant payments)
  • Under ‘account information’ >> ‘email’
    • Note down your primary email address. This email will be visible to users so make it a professional one. User’s may feel apprehensive about sending money to an e-mail address with the domain ‘hotmail.com’ or ‘Yahoo.com’ etc…

Step 2 – Simple HTML Form

Your website must now send all the required values to PayPal so that the payment can be processed.

The following code example demonstrates a basic form that we will use to send the values:

cmd” type=”hidden” value=”_xclick” />


The business name, price, submit type, notify URL and other sensitive values will be sent during the next step.

A full list of the values to send can be found at the PayPal website under the title “A Sample IPN Message and Response”.

Step 3 – Payments.php (The Request)

The payment.php page will be used to handle the outgoing request to PayPal and also to handle the incoming response after the payment has been processed.

The following sample code shows the querystring being constructed before it is posted to PayPal. Here you can specify the following values:

  • Business ($paypal_email) – Enter the email address of your PayPal account.
  • Item name ($item_name) – The name of the item being purchased.
  • Amount ($item_amount) – The price of the item.
  • Return ($return_url) – The address to return to after a successful payment.
  • Cancel Return ($cancel_url) – the address to return to after a cancelled payment.
  • Notify URL ($notify_url) – The address of the payments.php page on your website.
  • Custom – Any other data to be sent and returned with the PayPal request.
// Database variables
$host = "localhost"; //database location
$user = ""; //database username
$pass = ""; //database password
$db_name = ""; //database name

// PayPal settings
$paypal_email = 'paypal@example.com';
$return_url = 'http://example.com/payment-successful.htm';
$cancel_url = 'http://example.com/payment-cancelled.htm';
$notify_url = 'http://example.com/paypal/payments.php';

$item_name = 'Test Item';
$item_amount = 5.00;

// Include Functions
include("functions.php");

//Database Connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){

    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&";

    // Append amount& currency (£) to quersytring so it cannot be edited in html

    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&";
    $querystring .= "amount=".urlencode($item_amount)."&";

    //loop for posted values and append to querystring
    foreach($_POST as $key => $value){
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&";
    }

    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    $querystring .= "notify_url=".urlencode($notify_url);

    // Append querystring with custom field
    //$querystring .= "&custom=".USERID;

    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();

}else{
    // Response from PayPal
}

Step 4 – Payments.php (The Response)

The next part of the payments.php page handles the response from PayPal. The response is re-assigned to variables and then posted back to PayPal for verification using fsockopen.

If the response is VERIFIED then a validation check can be performed. The check_txnid and check_price functions are called to check that the correct Transaction ID and Price have been returned. The updatePayments function can finally be called to store the details of the payment in the payments table (Step 6).

// Database variables
$host = "localhost"; //database location
$user = ""; //database username
$pass = ""; //database password
$db_name = ""; //database name

// PayPal settings
$paypal_email = 'paypal@example.com';
$return_url = 'http://example.com/payment-successful.htm';
$cancel_url = 'http://example.com/payment-cancelled.htm';
$notify_url = 'http://example.com/paypal/payments.php';

$item_name = 'Test Item';
$item_amount = 5.00;

// Include Functions
include("functions.php");

//Database Connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
    // Request from step 3
}else{

    // Response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
        $req .= "&$key=$value";
    }

    // assign posted variables to local variables
    $data['item_name']          = $_POST['item_name'];
    $data['item_number']        = $_POST['item_number'];
    $data['payment_status']     = $_POST['payment_status'];
    $data['payment_amount']     = $_POST['mc_gross'];
    $data['payment_currency']   = $_POST['mc_currency'];
    $data['txn_id']             = $_POST['txn_id'];
    $data['receiver_email']     = $_POST['receiver_email'];
    $data['payer_email']        = $_POST['payer_email'];
    $data['custom']             = $_POST['custom'];

    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

    if (!$fp) {
        // HTTP ERROR
    } else {
                mail('ash@evoluted.net', '0', '0');
        fputs ($fp, $header . $req);
        while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp ($res, "VERIFIED") == 0) {

                // Validate payment (Check unique txnid & correct price)
                $valid_txnid = check_txnid($data['txn_id']);
                $valid_price = check_price($data['payment_amount'], $data['item_number']);
                // PAYMENT VALIDATED & VERIFIED!
                if($valid_txnid && $valid_price){
                    $orderid = updatePayments($data);
                    if($orderid){
                        // Payment has been made & successfully inserted into the Database
                    }else{
                        // Error inserting into DB
                        // E-mail admin or alert user
                    }
                }else{
                    // Payment made but data has been changed
                    // E-mail admin or alert user
                }

            }else if (strcmp ($res, "INVALID") == 0) {

                // PAYMENT INVALID & INVESTIGATE MANUALY!
                // E-mail admin or alert user
            }
        }
    fclose ($fp);
    }
}

Step 5 – Functions.php

The payments.php page calls upon a number of functions used to validate the returned data and store the response in the database.

// functions.php
function check_txnid($tnxid){
    global $link;
    return true;
    $valid_txnid = true;
    //get result set
    $sql = mysql_query("SELECT * FROM `payments` WHERE txnid = '$tnxid'", $link);
    if($row = mysql_fetch_array($sql)) {
        $valid_txnid = false;
    }
    return $valid_txnid;
}

function check_price($price, $id){
    $valid_price = false;
    /*
    you could use the below to check whether the correct price has been paid for the product
    if so uncomment the below code

    $sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'");
    if (mysql_numrows($sql) != 0) {
        while ($row = mysql_fetch_array($sql)) {
            $num = (float)$row['amount'];
            if($num == $price){
                $valid_price = true;
            }
        }
    }
    return $valid_price;
    */
    return true;
}

function updatePayments($data){
    global $link;
    if(is_array($data)){
        $sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES (
                '".$data['txn_id']."' ,
                '".$data['payment_amount']."' ,
                '".$data['payment_status']."' ,
                '".$data['item_number']."' ,
                '".date("Y-m-d H:i:s")."'
                )", $link);
    return mysql_insert_id($link);
    }
}

Step 6 – Setting Up The Payments Table

To store payment details in the database a payments table must be created in your database. The following MYSQL code will create a payments table.

CREATE TABLE IF NOT EXISTS `payments` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `txnid` varchar(20) NOT NULL,
  `payment_amount` decimal(7,2) NOT NULL,
  `payment_status` varchar(25) NOT NULL,
  `itemid` varchar(25) NOT NULL,
  `createdtime` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 7 – Sandbox Testing / Going Live

PayPal Sandbox offers all of the functionality of PayPal, but the information involves all “Fake accounts” created by the developer. You can create fake buyer and fake seller profiles, then test your PayPal integration through your development website.

During the testing phase of the development process the PayPal links should be prefixed to www.sandbox.paypal.com. You can visit the PayPal Developer website and sign up for a free PayPal Sandbox account

Once the payment process is ready to be used by real customers you will need to remove the sandbox from each PayPal link to www.paypal.com.

That’s it; you’re ready to start taking payments online through your website.

Tagged with: , , , , ,
Posted in PHP
Follow

Get every new post delivered to your Inbox.

Join 135 other followers