Category

Php

Category

Most of us know PHP – is a server side scripting language commonly used to write web applications. MySql – is an RDBMS (Relational Database Management System) used to store data handled by web applications. We have written a handful of amazing articles on how to make money online as a PHP Programmer. All these articles guide you through different opportunities available for a programmer or web developer to make money from internet using his skills. I am listing the most useful articles below:

You might also like – How a PHP beginner can land their first job

We have been working with PHP, MySql and many open source web apps like WordPress, Magento, OpenCart and frameworks like Yii, CakePHP, Zend etc for many long years. We know these languages and systems inside out. In this article, we are listing some of the best books and resources to learn PHP and MySql – which will help you to polish your programming skills and command over the language and database.

Programming – is a skill that you master with experience. We all begin with a “Hello World” program and we work our way up from building single web pages to full-fledged websites to complex web applications. We have taken utmost care while developing this resource article that we haven’t listed any book/website that will waste your precious time. We have also carefully structured this article for beginners, medium level programmers and advanced web app developers. Let’s have a look at the  six best books through which you can learn php and mysql.

For Beginners

W3Schools – We don’t need to mention this website (which is the best reference resource to begin learning any scripting language). Everyone knows about W3Schools and its usefulness. If you are a complete benginner, this website will really help you. It does have a lot of practical examples in PHP which are written in simple language so that it will be easier for the php beginners.

Book #1 PHP and MySql Web Development by Luke Welling and Laura Thomson

php1

This is one of the best and highly recommended (by other readers and programmers) book on PHP and MySql.  This book is well structured and the contents are so well selected that this book is more than enough for your journey from a beginner to a mid level programmer. The contents of this book are divided into 5 main sections. The first 2 sections take you through the basics of PHP and MySql – like storing and retrieving data, usage of arrays, regular expressions, object oriented PHP, designing database, accessing MySql database using PHP, advanced MySql administration and programming. The final 3 sections – are what makes the book outstanding and unique compared to other similar books.

The authors have carefully included a dedicated section for E-Commerce and Security. In this section, they have included chapters to explain E-Commerce systems, security issues that arise while developing E-Commerce systems, implementing authentication techniques using PHP and MySql, implementing secure transactions using PHP and MySql etc. The fourth section takes you through many advanced PHP techniques like sessions control, interacting with file system and server, using network and protocol functions etc.  The final section (5th) takes you through building practical web based applications using PHP and MySql – like building a shopping cart, a mailing list manager, web-based E-mail service, web based discussion forum and many other interesting projects.

To conclude, this book by Luke Welling and Laura Thomson is a complete resource for any one serious about PHP and MySql. The simple and easy to understand writing style of authors with well selected content makes this book a unique and best resource to learn PHP and MySql.

Price: $32.34

Book #2  (Kindle Edition)- Learn PHP and MySql – Zero to Hero Programming Crash Course – by Paul Madoff

php2

This is a good beginners book who wants to quickly skim through the language and understand the concepts. This book by Paul Madoff is not comprehensive as the first book (Book #1) we recommended. But this book is an easy to read and understand one, which can be handy for a new comer.

Price:$2.99

Book #3 Learning PHP, MySql and Javascript: with Jquery, CSS and HTML5 – by OReilly (Author – Robin Nixon)

php3

This is an all-in-one packed book to learn web development. This book published by OReilly is one of the best-selling books on Amazon and has very positive user reviews. We find this book very useful as it covers the very important and essential scripting languages (in addition to PHP and MySql) – Javascript, CSS and HTML5 along with Jquery. A web developer’s learning curve comes to full circle when he masters a server-side scripting language (like PHP), an RDBMS (like MySql), a browser side scripting language (Javascript and Jquery), finally Markup and Styling (HTML and CSS). This book helps a beginner to grasp the essence of all these languages and how to effectively use them to build web applications.

We highly recommend Book #1 and Book #3 for any one serious about PHP and MySql. These 2 books can make a profound impact on your web development knowledge and skills. The ideas you grasp from these 2 books will help a lot in building your career as a web app or software programmer. Book #2 is for quick skimming – for those who are interested only in learning the concepts of PHP and MySql.

Price: $31.98

For Mid Level and Advanced Programmers

Book #4 PHP and MySql for Dynamic Website: Visual QuickPro Guide by Larry Ullman

php4

This is a very interactively written book on PHP and MySql. The author himself is a software programmer and teacher, who has years of hands-on experience in developing dynamic web applications. The book is very comprehensive and covers every important aspect of developing web applications using PHP and MySql. Though this book goes easy with beginners as well, we would like to recommend this book to intermediate level programmers who already has a base of PHP and MySql. However, a beginner can also go ahead with this book and will find it easy for grasping. The author has a very vivid style of writing and he explains the basic concepts with utmost care and ease of understanding. We found this book very useful in polishing your knowledge in PHP, improving web development skills, understanding core concepts thoroughly and to know the world of dynamic web development deeper. We also found this book useful for job aspirants who have to face interview questions around core concepts of PHP and MySql.

Price: $31.28

Book #5 PHP Advanced and Object Oriented Programming by Larry Ullman

php5

This book helps to take your PHP skills to next level through real world applications. The book teaches you how advanced techniques are used in developing real world applications and advanced database techniques. Larry Ullman – author of this book has given great focus on OOP (Object Oriented Programming) concepts of PHP, which is the programming method of software industry as a whole. OOP concepts are very essential to be mastered by any web development professional. We highly recommend this book to advance your PHP skills and we are sure this book will be an asset for your career.

Price:$31.28

Book #6 Advanced PHP Programming by George Schlossnagle

php6

This is a handy and useful book for all professional PHP programmers. This book covers the best practices to be followed while developing web based applications using PHP. This book by Schlossnagle is purely for professionals as the author focuses a great deal on scaling PHP to develop enterprise level web applications. The book covers important chapters on how to optimize for performance, stability andy. We consider this as a great reference resource for every professional who works on PHP based Web Application Development.

Price: $43.58

Hope you guys find these php learning books helpful, as said these are the best books to learn php and mysql currently in the industry. Its totally worth the price!

Paypal integration use to be a real pain for many developers. They use to change their interface(especially their sandbox and developer environment). In fact there is a strategy for the paypal integration and if its followed properly this is an easy process. Have a look at this guide which completely guide you to php paypal integration.

Objectives and Steps

  1. Step 1 :  Create Sandbox testing account.
  2. Step 2 : Implement the paypal buttons.
  3. Step 3 : Doing the transactions,setting up the return url, and verifying the transaction.
  4. Step 4 :  Setting an IPN (instant payment notification).

[steps]1 [/steps]

 Create sandbox testing accounts in paypal developer section.

You need to login to paypal developers section. You may login with your exact paypal,address, that is the one you use to login to paypal.com. After that you need to create a sandbox account in paypal. After creating the sandbox account you need to login to the sandbox.paypal.com

What is paypal sandbox?
Sandbox is nothing but a testing environment of paypal. You can create seller and buyer account in sandbox and can do test transactions exactly like the paypal live transactions. And of course no one would be losing any money, you can add or transfer as much as money you like (say in dollars ) as like we see in some games. And once you’ve done the testing, you can change it easily to live by changing all instances of sandbox to paypal, that is if there is something like http://sandbox.paypal.com in your code, just change it to http://paypal.com.

Paypal sandbox
create sandbox account

Create one personal(to send money) and one business account(to recieve money). You can create the test accounts with fake emails, provided it doesnt exist in the paypal database. Add an amount to the paypal balance text box( the required money ) say 500 and that much money will be there inside your paypal account. I’ve created two testing accounts here

  1. a business account – businesstest@dollarfry.com
  2. a personal account – personaltest@dollarfry.com

 

After that I am going to log in to the sandbox environment of the business account. As seen in the screenshot below, I’ve selected the business account and then the Enter the Sandbox link which will drop us into the sandbox environment. You need to login to the sandbox account with the business (or personal account) credentials(which you’ve created a while ago).

 

paypal sandbox login
paypal sandbox login
Sandbox login
Sandbox login

And once you login , you can see that test sandbox account has came up exacly like a real paypal account(you can see the account balance and all).
[steps]2[/steps]

Create paypal buttons from the paypal business account profile

You can either create button from paypal(which makes you descent buttons) or you can create one by yourself. Basically a button is a simple html form posting some data (amount, currency etc) into the paypal and initiating the transaction.
You need to get into your Profile>My Selling Tools>Paypal Buttons>update.

There are three steps in creating a paypal button

1 : Choose a button type and enter your payment details
Here as shown in the screenshot below, you can fix the amount for the button. Also in the button type you do have multiple options like shopping cart(through which you can create a shopping cart with paypal! ), buy now etc. Here we are using the buy now option . A price is set for the button (say 50 $) and once the button is clicked, the user will be taken to paypal to pay 50 dollars.
2 :Track inventory, profit & loss (optional) – Here you can track the inventory ,profit and all
3: Here we can set the return url and cancel url for the buyer.

Create paypal button
Create paypal button
Paypal Button details
Paypal Button details

[df_hireme price=”25 USD” service=”Paypal integration” extratext=”I have more than 5 years of experience in WordPress and PHP and have implemented paypal for many clients”]

Whats the purpose of Return url and Cancel Url?

At this stage you might have an idea of what happening or whats going to happen. You can integrate this button to your website , the user clicks the buy now button from your website and when the user makes a payment , the business account holder gets money credited into his account. After that the user must be returned back to your website so that only you can verify which user has paid the money and his transaction details. Once the payment is successfully completed, paypal posts back the transaction details (with the unique transaction id and all as $_GET parameters) to the return url where you can retrieve these parameters and store in database . You also need to verify the transaction id whether its a genuine transaction id or not.
The cancel url is nothing but at some point the user changes his mind and cancel the payment. After that the user will be returned to your website where you can show the notification that “Your transaction has been Cancelled!”.

And once you generate the button with paypal, you can save it and alter it later as you wish. Just paste the code into your website and the button will appear inside your website.

Alternatively, you can skip the above step(creating a button in paypals admin ) by pasting a self made form inside your website(which would be easy for you to customize , you can create an admin side in your website and easily configure the amount to paid by the user) .

This form will generate the paypal button.Here you can see that I am passing some hidden fields to paypal sandbox,

 

represents the sandbox business account which we created before, you can replace it with your business account details.

Represents the amount to be paid.

 

This is a custom field, which is the most useful part. This helps your to identify which user is making the payment. We can pass the user id along with this form and it will be returned to the return url along with the $_GET parameters so that we can easily save it into the database. This custom field can be used to connect with any attribute, like product id, product name or whatever.

 

These are the return url and cancel urls to your website.

Have a look at the complete list of Paypal variables which you can pass through.
[steps]3[/steps]

Verifying the paypal transaction in the Return Url

I’ve already mentioned about the return url and its use. You can see what all parameters are passed back to your websites return url(which the paypal have made after successful transaction). This do have a transaction id (txnid) .
You can get it through $_GET[‘txnid’] in your return url page. You need to verify this transaction id by sending it back to paypal and getting the response . What if a bogus user is accessing your return page url with a fake transaction id? So this stage is very important. We need to post a curl to paypal with the transaction id so that paypal will fetch back all the details of the transactions (like, amount, currency, country,address,email ) etc and you can save it in the database as a transaction record.

The paypal response string fetched through curl should look like this

SUCCESS mc_gross=50.00 protection_eligibility=Eligible address_status=confirmed payer_id=ZEDQ57L32HS3Y tax=0.00 address_street=1+Main+St payment_date=22%3A31%3A56+Aug+19%2C+2013+PDT payment_status=Pending charset=windows-1252 address_zip=95131 first_name=Sam address_country_code=US address_name=Sam+Alex custom=752/ payer_status=verified business=businesstest%40dollarfry.com address_country=United+States address_city=San+Jose quantity=1 payer_email=personaltest%40dollarfry.com txn_id=7B1573210T2407153 payment_type=instant last_name=Alex address_state=CA receiver_email=businesstest%40dollarfry.com receiver_id=NRWL58NJZA7TA pending_reason=multi_currency txn_type=web_accept item_name=normal mc_currency=AUD item_number= residence_country=US handling_amount=0.00 transaction_subject=752/ payment_gross= shipping=0.00

How can you verify your paypal transaction ID in your return page using curl?
Have a look at this verification of transaction id in paypal php.

 'https://www.sandbox.paypal.com/cgi-bin/webscr',
  CURLOPT_POST => TRUE,
  CURLOPT_POSTFIELDS => http_build_query(array
    (
      'cmd' => '_notify-synch',
      'tx' => $tx,
      'at' => $identity,
    )),
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_HEADER => FALSE,
  // CURLOPT_SSL_VERIFYPEER => TRUE,
  // CURLOPT_CAINFO => 'cacert.pem',
));
// Execute request and get response and status code
$response = curl_exec($ch);
$status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close connection
curl_close($ch);
if($status == 200 AND strpos($response, 'SUCCESS') === 0)
{
    // Save the Record into the database
}

Everything is pretty straight forward. You are sending a curl request to paypal sandbox with the transaction id ($tx) and getting the response in the $response variable. If the status is success , the transaction id is verified and we can save it into the database.

You might have seen the identity section,

$identity = 'Your Identity';

How can you get your Paypal Identity Token and set Auto Return?

You will be having a unique identity token for your paypal business account and that what we have given above as identity. You need to enable PDT(Payment data transfer) and Auto Return in order to get the identity token. By setting Auto Return, your user will be returned back to your return url(which is really an essential feature). You need to get into

Profile>My Selling Tools > Website Preferences (In the Selling Online section)

In that section you can set the return url, pdt and auto return. Check the screenshot below

Paypal Auto Return
Paypal Auto Return -PDT

Once you save the details, you can see the Identity Token along with the success notification. Just get into the website preferences again to get the identity token (in case you miss the notification).

 

You may need to use php Preg_match kind of function to retrieve particular details alone(say payer email).
[steps]4[/steps]

Usage of Paypal Instant Payment Notifications (IPN)

We can say that the paypal integration is complete with the above step (step 3). So whats the use of Paypal IPN?
Assume a situation that the user clicks the buttons from your site , makes the payment (in paypal) and his pc bursts out at that point(that is, before the user is forwarded to the return url). How will you know that this particular user have made the payment(well you got the money, but how can you identify the user and his trasaction id? ) Remember that you are getting all the details of the payment in the return url page.

Here is were paypal IPN comes to save you. IPN or Instant Payment Notification, as the name indicates, it sends an immediate request to your IPN your (some page in your website) right after the payment. And the user doesnt know or have to do anything about this request(nothing matters if his pc bursts off or loses his internet connection). The details of the transaction will be posted to the IPN url(which you’ve set) as a $_POST instance. You can retrieve it there, verify it as said above (with curl) and save it into the database.

To use IPN, you need to enable it inside paypal.
Go to, Profile >My Selling Tools > Instant Payment Notifications(under Getting paid and managing my risk)

Under that you need Choose IPN Settings, and you need to provide an IPN Notification url and enable the Receive IPN Messages option.

IPN Settings  paypal
Paypal IPN Settings
 &$value) {
   $value = mb_convert_encoding($value, 'utf-8', $charSet);
 }
 $ipn_data['charset'] = 'utf-8';
 $ipn_data['charset_original'] = $charSet;
}
// Looping through the IPN Post Data and creating a final array of transaction details
foreach ($ipn_data as $key => $value) {
  $finalIPN[$key] = $value;
}
// Saving the encode transaction details  to the table
$dataJson = json_encode($finalIPN);

Advantage of using IPN
IPN is useful to handle safe returns. For instance, from your site, the user goes to paypal and the payment will be made. After that the user will be returned to your website, and the transaction data will be posted and you can verify the payment.

WHAT IF ???

  • The power of the pc goes off
  • The internet fails
  • User closes the paypal window accidently

The user will pay the money to you, but you wont be able to track it right? This is where IPN is useful. Instant Notification(Posed data) will be made to the url you specify(you can store the data in your database or whatever) right after the payment is done(With as status of success,failure or whatever). You can verify and track this payement even if the any of the above scenarios happen.

Here in the $dataJson variable, you will be getting the entire transaction details encoded in json format.
So thats all about paypal php integration. Hope you enjoyed this tutorial. Shoot in comments and we are here to help you!

The sort function in array sorts the array very well, but it doesnt maintain the keys so that it becomes really painful sometimes. There will be several scenarios were we need to keep the keys of the associative arrays.

Luckily there are two functions in php which will help us to achieve this

1. uasort

uasort sort the array in the desired order (ascending or descending and will maintain the keys). It accepts two arguments,
1. The array to be sorted
2. The compare function

  $b) ? -1 : 1; 
        }  // Array to be sorted echo" pre="">";
        	
        $array = array('a' => 3, 'b' => 1, 'c' => -1, 'd' => -2, 'e' => 2, 'f' => -3, );
        echo "
";
        echo "Array Before Sorting 
"; print_r($array); echo "
"; // Sort and print the resulting array uasort($array, 'compare'); echo "Array After Sorting
"; print_r($array); ?>

The compare function return 1 or -1 which comes as the outcome of the bigger or smaller values(in the array) which has been compared.
Output

Array Before Sorting 
Array
(
    [a] => 3
    [b] => 1
    [c] => -1
    [d] => -2
    [e] => 2
    [f] => -3
)

Array After Sorting 
Array
(
    [a] => 3
    [e] => 2
    [b] => 1
    [c] => -1
    [d] => -2
    [f] => -3
)

2. asort

asort sorts the array and maintains its key. The sorting will only be in ascending order (from smallest to largest). We may need to reverse the array in order to sort it in the descending order. For that we can use the array_reverse function in php

Demo Download Country Class Example

In this post, I’ll explain the php oop concepts as simple as possible.

What is Object Oriented Programming? How to learn php oop easily

Object oriented is not some kind of code, but a different approach to the way of programming.  There are lots of drawbacks in the procedural methodology, which the OOP can overcome. Lets gets straight into the Country-Continent Class example which will guide you to most of the main techniques used in PHP OOP.

Continent -Country Class Example

I’ve made up two classes , Continent and Country which explains all the major oop concepts. Country inherits from Continent, means Country is the child class of Continent or Continent acts as the parent class to Country.

Step 1. How is a Class  defined?

A Class is defined using the keyword Class, here

Class Continent {

}

  • The curly braces represents the scope of the class, or where the class starts and ends.

Before getting into the code there are two major concepts(terms) which you need to know.

  1. Properties  – Properties are variables itself, but in OOP we call variables as property.
  2. Methods    – Methods are functions itself, but in OOP we call functions as methods.

Class Continent

Step 2. Properties

Class Continent {
// Properties of the Continent Class
var $name;
var $size;
// Assigning a static value to the static variable.
static $smallestContinent="Australia";

These are properties of the Class Continent. Properties are defined using the keyword var. Everything is pretty straight forward, except the scope. There are three scopes.

  1. Private
  2. Protected
  3. Public

Here the  properties ‘size’ and ‘name’ are of public scope (which is the default scope).I’ve explained the scopes in detail below.

The third variable smallestContinent have a prefix static . This means this variable will be having  static value and it cannot be changed, I will explain this also in detail after explaining the concept of objects.

 Step 3. Methods

Class Continent has one method  getDetails of scope public. Likewise properties, functions are also of  3 scopes (public,private,protected).

/*
Getting the details of the country or continent through the public function getDetails.
*/
public function getDetails($type){
// Returning the assigned values to the properties of the class Continent.
$details= $this->name." is a ".$this->size." ".$type;
return $details;
}

Step 4. Real world analogy and concept of Objects

Objects makes the oop possible. We create a new object of the Class and that object holds all the properties and methods of the class. As a real world analogy to our class Continent, Class Continent has lots of properties like  size, name and all and its methods. And sub class Country extends from Continent and its supposed to have all these properties too.

Assume the name property of the Class Country.  Different countries in this whole world have different names. So what we are doing is that we create different objects for the class country and giving  it different names (India,USA,Australia). All the code stands inside the  class and we can use or reuse  them. Assume that there is a class for a user registration system, we can implement this  registration system anywhere in your website by creating a new object for the user registration class.

//Creating an object of Continent class. Constructor will be called automatically.
$continent=new Continent($type);
// Assigning values to Continent class properties
$continent->name="Asia";
$continent->size="Big";
// Calling a public method(function) of the class Continent
echo $continent->getDetails('Continent');

Here  a continent object is created by,

$continent=new Continent($type);

The attributes of the Continent class are assigned specific values.  Values are assigned to the public properties name and size. Also the public method getDetails is called with the object instance.

In the Continent Class,

/*
Getting the details of the country or continent through the public function getDetails
*/
public function getDetails($type){
// Returning the assigned values to the properties of the class Continent.
$details= $this->name." is a ".$this->size." ".$type;
return $details;
}

We are assigning values Asia and Big to  name and size attributes of the continent object respectively  and this values are appended to some content and returned from the class.

Step 5. $this in php oop  

$this is a simple concept in php oop, but it can be really messy if you doesnt know its purpose. I really had problems with $this when I started learning oop.

$this is nothing but just the current object. Here we are creating an object of the Continent class ($continent) , assigning values to the properties and calling the function getDetails. $this->name in the getDetails function now will be having the  value assigned for the continent object’s name property.

$continent->name="Asia";

That means  $this->name will be having value “Asia” .

Output of the getDetails function

Asia is a Big Continent

Step 6. Constructor  

Constructor is a special function, which will be called right after the object creation.  Here we’ve defined a constructor in the Continent Class.

public function __construct($type){

echo "This is the constructer invoked for the $type object";
}

A constructor is created with the keyword __construct or the name of the Class itself. Constructor is valid for the child classes object instances also.

Step 7. Destructor

Destructor is called once there are no more references to the particular object. Destructor  function can be created with the keyword __destruct.

function __destruct() {

echo "Destructor is called once there are no more references to the particular object";
}