I got this question the other day: how to send a POST request from PHP with correctly-formatted JSON data? I referred to the slides from my web services tutorial for the answer, and I thought I’d also put it here, with a bit of explanation. After all, publishing your slides is all very well, but if you didn’t see the actual tutorial, I often think they aren’t too useful.

We can’t send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   
$ch = curl_init('http://api.local/rest/users');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
$result = curl_exec($ch);

All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. If you’re sending JSON data with PHP, I hope this might help!


cURL Requests with PHP


cURL allows transfer of data across a wide variety of protocols, and is a very powerful system. It’s widely used as a way to send data across websites, including things like API interaction and oAuth. cURL is unrestricted in what it can do, from the basic HTTP request, to the more complex FTP upload or interaction with an authentication enclosed HTTPS site. We’ll be looking at the simple difference between sending a GET and POST request and dealing with the returned response, as well as highlighting some useful parameters.


Before we can do anything with a cURL request, we need to first instantiate an instance of cURL – we can do this by calling the function curl_init();, which returns a cURL resource. This function takes one parameter which is the URL that you want to send the request to, however, in our case, we’ll hold off doing that for now and set it an alternatively way later.


Once we’ve got a cURL resource, we can begin to assign some settings, below is a list of some of the core ones that I set

  • CURLOPT_RETURNTRANSFER – Return the response as a string instead of outputting it to the screen
  • CURLOPT_CONNECTTIMEOUT – Number of seconds to spend attempting to connect
  • CURLOPT_TIMEOUT – Number of seconds to allow cURL to execute
  • CURLOPT_USERAGENT – Useragent string to use for request
  • CURLOPT_URL – URL to send request to
  • CURLOPT_POST – Send request as POST
  • CURLOPT_POSTFIELDS – Array of data to POST in request

We can set a setting by using the curl_setopt() method, which takes three parameters, the cURL resource, the setting and the value. So, to set the URL that we’re sending the request to as

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, '');

As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:

$curl = curl_init('');

It is possible to set multiple settings at one time by passing through an array of settings and values to the function curl_setopt_array():

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => ''

Sending request

When all of the options are sent, and the request is ready to send, we can call the curl_exec() method which will execute the cURL request. This function can return three different things:

  • false – if there is an error executing the request
  • true – if the request executed without error and CURLOPT_RETURNTRANSFER is set to false
  • The result – if the request executed without error and CURLOPT_RETURNTRANSFER is set to true

Using the previous example, where we are wanting to get the result back, we would use the following:

$result = curl_exec($curl);

With $result now containing the response from the page – which might be JSON, a string or a full blown site’s HTML.

Close Request

When you’ve sent a request and got the result back, you should look to close the cURL request so that you can free up some system resources, this is as simple as calling the curl_close() method which as with all other functions takes the resource as its parameter.

GET Request

A GET request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET requests. If you want to send parameters along in the request you simply append them to the URL as a query string such as

So for example to send a GET request to the above URL and return the result we would use:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_URL => '',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources

POST Request

The sole difference between the POST and GET request syntax is the addition of one setting, two if you want to send some data. We’ll be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS

So for example switching the above GET request to be a POST request, we would use the following code:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_URL => '',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_POST => 1,
        item1 => 'value',
        item2 => 'value2'
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources

There you have a POST request that will work the same as our GET request above and return the response back to the script so that you can use it as you want.


As much as we all hate errors, you really need to take care to account for any eventuality with cURL as ultimately you will not have control over the site(s) that you are sending your request to, you cannot guarantee that the response will be in the format that you want, or that the site will even be available.

There are a few functions that you can use to handle errors and these are:

  • curl_error() – returns a string error message, will be blank '' if the request doesn’t fail.
  • curl_errno() – which will return the cURL error number which you can then look up on this page listing error codes.

An example usage would be:

    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));

You might want to look at using the setting CURLOPT_FAILONERROR as true if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.


cURL is a behemoth, and has many many possibilities. Some sites might only serve pages to some user agents, and when working with APIs, some might request you send a specfici user agent, this is something to be aware of.



13 Questions That Will Change Your Life

When things aren’t going quite the way you’d like them to, it’s often the result of not asking yourself the right questions. Some questions are hard to confront because you’re afraid you won’t get the answer you want, others because you really don’t want to know the answer.

But the best things in life don’t come easily, and turning away from life’s toughest questions is a sure path to mediocrity. I believe that Socrates said it best:

“The unexamined life isn’t worth living.”

Socrates’ observation also applies to business. When Eric Schmidt was CEO of Google, he famously said, “We run this company on questions, not answers.”

Life, like business, runs on questions, not answers. Let’s take a closer look at some of the tough questions we should be asking ourselves regularly.

How do people see me differently than I see myself?

Have you ever heard a recording of your voice and thought, “Is that what I really sound like?” Because of the way the sound of the voice travels through the human skull, we never hear ourselves the same way that everybody else hears us. The same is often true for the way we behave. We interpret our behavior in terms of how we think we come across, whereas everyone else sees the real thing. A 360° assessment is a great way to gain this perspective. It gathers feedback that is constructive, anonymous, and accurate. If you forego the 360 and solicit feedback in person, make certain you ask for feedback that is specific, avoiding broad questions and generalizations. For example, you’re more likely to get an honest and accurate answer to, “How well did I handle myself in the meeting when everyone disagreed with me?” than to, “Am I a good boss?” And be careful to show that you’re receptive to the feedback. If you flip out or get defensive every time somebody speaks their mind, they’re going to stop doing it.

What/whom did I make better today?

That’s another way of saying, “Leave things better than you found them.” Ending each day by asking yourself what or whom you made better is a great way to keep yourself grounded and focused on what really matters.

Am I being true to my values?

Do you ever get that nagging feeling that something is a little off in your life? This often happens when little behaviors creep up on you that violate your values. If spending quality time with your family is one of your primary values, but you keep staying late at work, there’s a conflict. If you want that nagging little voice to go away, you’re going to have to do something about it.

If I achieved all of my goals, how would I feel? What can I do to feel that way as I work to achieve them?

The ability to delay gratification in pursuit of your goals is one of the most fundamental prerequisites for success, but delaying gratification doesn’t have to mean being miserable until you cross that finish line. You can achieve more—and have more fun doing it—if you let yourself feel some of that pride and pleasure along the way.

What haven’t I taken the time to learn about?

It’s a big world out there, and it’s getting bigger all the time. Scientists have theorized that it once took 1,500 years for the accumulated knowledge in the world to double; now it only takes a year or two. Don’t get caught behind.

In what areas of my life am I settling?

When you settle, you accept less than you’re capable of. Sometimes we settle in dead-end jobs. Other times we settle for unhealthy relationships. If you don’t ask yourself where and why you’re settling, it’s hard to stop it.

What do I want my life to be like in five years?

Lewis Carroll once said, “If you don’t know where you’re going, any road will take you there.” The corollary is that, once you have your destination in mind, you can plan your route. Five years is the perfect timeframe: It’s not so far in the future that you can’t imagine yourself there, but it’s not so close that you can’t do anything about it.

What would I do if I wasn’t scared?

From a survival perspective, fear has its purpose. It’s what keeps us from sticking our hand in the washing machine or any of the million other things that could get us hurt or killed. But fear has a tendency to get carried away. Instead of keeping you safe, it keeps you from improving your life and living your dreams.

Who has qualities that I aspire to develop?

When people have qualities that you admire, it’s a great exercise to reflect on these qualities and think about ways that you can incorporate them into your repertoire.

What problem are we solving?

Have you ever been in a meeting and suddenly realized that not everyone was having the same conversation? Not because people were talking over each other, but because they had different ideas about the purpose of the discussion. Sometimes it helps to put the topic on the whiteboard when you’re having a meeting. This makes certain everyone knows why they’re there.

What’s stopping me from doing the things that I should be doing?

It’s easy to shrug your shoulders and say, “I don’t know what to do,” but that’s just an excuse. Most of the time, we know exactly what we should be doing; we just aren’t willing to move the obstacles out of the way.

Will you be my mentor?

It’s an intimidating question to ask, but few people will turn you down. Everyone likes being looked up to, and it feels good to share our knowledge with others.

What’s the most important lesson I’ve learned so far in life? Am I living that lesson?

Sometimes life lulls us back into complacency and we’re forced to learn a powerful lesson twice. The trouble with this is that it’s just as much of a rude awakening the second time around.

Bringing It All Together

Asking the hard questions can be extremely uncomfortable. But we don’t learn and grow by sticking with what’s comfortable.

What other questions should people be asking? Please share your thoughts in the comments section below, as I learn just as much from you as you do from me.


Dr. Travis Bradberry is the award-winning co-author of the #1 bestselling book, Emotional Intelligence 2.0, and the cofounder of TalentSmart, the world’s leading provider of emotional intelligence tests and training, serving more than 75% of Fortune 500 companies. His bestselling books have been translated into 25 languages and are available in more than 150 countries. Dr. Bradberry has written for, or been covered by, Newsweek, TIME, BusinessWeek, Fortune, Forbes, Fast Company, Inc., USA Today, The Wall Street Journal, The Washington Post, and The Harvard Business Review.

10 regrets too many people will have in 10 years

Too often we waste our time waiting for the ideal path to appear, but it never does, because we forget that paths are made by walking, not waiting.

In the final decade of his life, my grandfather woke up every single day at 7 am, picked a fresh wild flower on his morning walk, and took it to my grandmother.  One morning, I decided to go with him to see her.  And as he placed the flower on her gravestone, he looked up at me and said, “I just wish I had picked her a fresh flower every morning when she was alive.  She really would have loved that.”  As you can imagine, my grandfather’s words touched a nerve in me.  And over the years I’ve often reflected on what he said that morning, and how his sentiment relates to everyone and everything I care about.

God willing, when I’m on the cusp of my 80’s, I don’t want to sit with regrets.  I don’t want to wish I had done things differently—especially something as simple, yet meaningful, as picking flowers for the love of my life.

In the end, more than anything else, we regret the small chances we didn’t take, the priceless relationships we were too busy to nurture, and the good decisions we waited too long to make.

I learned this through extensive experience.  I’ve spent the past decade coaching hundreds of students and clients from all over the world, and the same exact regrets relentlessly pop up in the personal stories people share with us.  Below, we’re going to take a look at ten of these common regrets, and then cover some principles and strategies for avoiding and overcoming them.

1. Not spending enough quality time with the right people.

At some point, you’ll just want to be around the few people who make you smile for all the right reasons.  So today, spend more time with those who help you love yourself more—spend more time with those who make you feel good, and less time with those who you feel pressured to impress.  Never be too busy to make room in your day for the ones who matter most.  And remember that nothing you can give will ever be more appreciated than your sincere, focused attention—your full presence.  Truly being with someone, and listening without a clock and without anticipation of the next event, is the ultimate compliment.

2. Not expressing your love openly and honestly with those you love.

Without question, you’re going to lose people in your life.  Realise that no matter how much time you spend with someone, or how much you appreciate them, sometimes it will never seem like you had enough time together.  Don’t learn this lesson the hard way.  Express your love!  Tell people what you need to tell them.  Don’t shy away from important conversations because you feel awkward or uncomfortable.  You never know when you might lose your opportunity.  Is it really possible to tell someone what you feel?  Yes, it is.  They won’t always understand, because even when they’ve heard you, they can’t feel exactly what you feel inside.  But you still have to speak up for your own peace of mind.  If you appreciate someone today, tell them.  If you have something else important to say, say it.  Hearts are often confused and broken open by words left unspoken.

3. Basing a significant portion of your self-worth on other people’s opinions of you.

We tend to forget that most people judge us based on experiences from their own life that have absolutely nothing to do with us.  For example, a person might assume things about you based entirely on a troubled past experience they had with someone else who looks somewhat like you.  Therefore, basing any part of your self-worth on what they think puts you in limbo—you are literally at the mercy of their unreliable, bias perspective.  If they see you in the right light, and respond to you in a positive, affirming manner, then you feel good about yourself.  And if not, you feel like you did something wrong.  The bottom line is that you will never find your worth in another human being—you find it in yourself, and then you will attract those who are worthy of your energy.  And in the meantime, not overreacting or taking things personally will keep your mind clear and your heart at peace.

4. Being too busy impressing others and forgetting about what matters to YOU.

Ten years from now it won’t really matter what shoes you wore today, how your hair looked, or what brand of clothes you wore.  What will matter is how you lived, how you loved, and what you learned along the way.  So forget about impressing people for the sake of it.  Be real instead!  If you want to impress someone, impress yourself by making progress on something you’re sincerely proud of.  Focus on what matters!  It’s truly amazing what you can accomplish in a day when you aren’t incessantly worried about what everyone else in the world is thinking and doing.  Just show yourself that you can grow and get better.  It’s never about impressing or competing with others.  In the end, it’s just you vs. you.

5. Letting uncertainty paralyse you.

Trust me now and thank me later, embrace uncertainty!  Because some of the most incredible chapters of your life won’t have a title you feel comfortable with until much later.  Living is risky business.  Every decision, every interaction, every step, every time you get out of bed in the morning, you take a small, uncertain risk.  To truly live is to know you’re getting up and taking that risk, and to trust yourself to take it.  If you don’t—if you let uncertainty win—you will never know anything for sure, and in many ways this unknowing will be worse than finding out your hunch was wrong.  Because if you were wrong, you could make adjustments and carry on with your life without ever looking back and wondering what might have been.  Remember this, and find the courage you need!  You don’t need guarantees 24/7.  That’s not how life works.  In life you can be comfortable or courageous, but not both at once.

6. Focusing on failures instead of opportunities.

Well, it’s true, you have failed and you have been hurt in the past.  But it’s also true that you have loved, and been loved.  That you have risked, and received.  That you have grown not just older, but wiser.  And all of this carries a weight of its own—a greater weight than any particular failure or wound.  In fact, it’s better to have a life full of small wounds and failures that you learned from, rather than a lifetime filled with the regrets of never trying.  Think about it!  Have you ever seen a toddler learn to walk?  They stumble and fall numerous times before getting it right.  The falls are learning opportunities.  Oftentimes it takes pain and patience to make lasting progress.  So don’t let time pass you by like a hand waving from a train you desperately want to be on.  Don’t spend the rest of your life thinking about why you didn’t do what you can do right now.

7. Holding on too tight to every ideal, and then missing out on real opportunities.

You can’t lose what you never had, you can’t keep what’s not yours, and you can’t hold on to something that does not want to stay.  But you can drive yourself mad by trying.  What you need to realise is that most things are only a part of your life because you keep thinking about them.  Stop holding on to what hurts, and make room for what feels right!  Do not let what is out of your control interfere with all the things you can control.  In other words, say “goodbye” to what didn’t work out so you can say “hello” to what might.  In life, goodbyes are a gift.  When certain people walk away from you, and certain opportunities close their doors on you, there is no need to hold on to them or pray to keep them present in your life.  If they close you out, take it as a direct indication that these people, circumstances and opportunities are not part of the next chapter in your life.  It’s a hint that your personal growth requires someone different or something more, and life is simply making room.

8. Playing the victim for far too long.

If you always play the victim, you will always be treated like one.  Life isn’t fair, but you don’t have to let the past define your future.  Remember that time you thought you couldn’t make it through?  You did, and you’ll do it again.  Don’t let your challenges get the best of you.  Don’t let your insecurities bully you into a corner.  Don’t be your own victim!  Take the next smallest step.  The greatest of all mistakes is to do nothing simply because you can only do a little.  And you can ALWAYS do a little!  Where you are right now is necessary.  Sometimes we avoid experiencing exactly where we are because we have developed a belief, based on our ideals, that it is not where we should be.  But the truth is, where you are right now is exactly where you need to be to take the next smallest step forward.

9. Waiting, overanalysing, and never taking the necessary steps.

Too often we waste our time waiting for the ideal path to appear, but it never does, because we forget that paths are made by walking, not waiting.  Remember this!  It’s easy to be lazy and wait around.  It’s easy to waste another day.  But you need to do the opposite!  Decide what you want to accomplish and get it done.  Action is worry’s worst enemy.  Action is the best ammunition.  Action brings progress!  So do not confuse senseless movement with real action.  Whenever you find yourself at a point of intense decision-making where you’re caught in a cycle of over-analysis and hesitation, and you’re making zero progress, take a deep breath, break the cycle, make an educated guess on the next logical step, and take it.  Even if you get it wrong, you will learn something useful that will help you get it right.  A daily ritual of small, positive steps is the ultimate key.

10. Being too busy to appreciate your life.

Take action, work hard, but don’t forget to pause and pay attention to life’s little moments too.  That’s honestly the best advice there is.  Realise that life is simply a collection of little chances for happiness, each lived one moment at a time.  That some time each day should be spent noticing the beauty in the space between the big events.  That moments of dreaming and sunsets and refreshing breezes cannot be bettered.  But most of all, realise that life is about being present, watching and listening and working without a clock and without anticipation of results at every moment, and sometimes, on really good days, for letting these little moments fill your heart with intense gratitude.  Truth be told, you will inevitably, whether tomorrow or on your deathbed, come to wish that you had spent less time worrying and rushing through your life, and more time actually being mindful and appreciative of each day.


The points above are crucial reminders, but what if you already have regrets you’re desperately struggling with?

No doubt, the feelings of regret sometimes sneak up on the best of us.  As alluring as the idea of living a regret-free life sounds, it’s rarely an easy feat.

Oftentimes, before we even realise what our minds are dwelling on…

  • We regret missed chances.
  • We regret not spending our time and energy more wisely.
  • We regret situations and conversations that didn’t go well.
  • We regret not speaking up when we had the chance.
  • We regret getting into toxic relationships, or making mistakes in past relationships.

Yes, even when we know better, we regret things.  And we do so simply because we worry that we should have made different decisions in the past.  We should have done a better job, but didn’t.  We should have given a relationship another chance, but didn’t.  We should have started that business, but didn’t.  And so on and so forth.

We compare the real outcomes of our past decisions to an ideal fantasy of how things “should” be.  In other words, we have a fairy tale dancing around in our heads of what could have been, if only we had made different decisions.

The problem, of course, is that we can’t change those decisions, because we can’t change the past.  Yet we resist this truth to no end—we keep overanalysing and comparing the unchangeable reality to our ideal fantasy until we’ve wasted days of our lives in head-spinning misery.

If we logically know better, why can’t we just let all our ideals and fantasies GO?

Because we identify personally with these ideals and fantasies.  We all have this vision in our minds of who we are—our well-meaning intentions, our intelligence, our social impact, etc.  And we make the best decisions we can, of course, because, again, we generally mean well.  Even if you struggle with deep-seeded self-esteem issues, you probably still identify with yourself as being a decent and respectful human being.

And so when someone says something about us that contradicts the vision of ourselves that we identify with—they insult our intentions, our intelligence, our status, etc.—we take offence.  We feel personally attacked, and we have a hard time letting it go.

Something very similar happens when we believe we did something—made a mistake—that contradicts that same vision of ourselves that we identify with.  We take offence!  In some cases we implode on ourselves—we berate ourselves for making the mistake … “How could I have done this?” we think.  “Why couldn’t I have been smarter and made a better decision?”  And again, we have a hard time letting it go—we have a hard time coming to grips with the fact that we aren’t ALWAYS as good as the vision we have of ourselves.

So in a nutshell, our ideals and fantasies about ourselves tend to cause us lots of misery.

The key is to gradually practice letting go of these ideals and fantasies, and focus instead on making the best of reality.  The truth must be embraced…

Every bad decision we made in the past is done—none of them can be changed.

And in fact there’s some good in every one of those bad decisions too, if we choose to see it.  Just being able to make a decision at all is a gift, as is being able to wake up in the morning, and being able to learn and grow from our wide-ranging life experiences.

We are not actually what we envision ourselves to be, at least not always.

We are human and therefore we are multi-layered and imperfect.  We do good things, we make mistakes, we give back, we are selfish, we are honest, and we tell white lies sometimes.  Even when we are doing our absolute best, we are prone to slip.  And once we embrace this and get comfortable with our humanness, making a bad decision tends to conflict a lot less with our new, more flexible (and accurate) vision of ourselves.

Of course, all of this is easier said than done, but whenever you find yourself obsessing over and regretting a past decision, you can 1) acknowledge that you’re falling into this pattern, 2) realise that there’s some ideal or fantasy you’re comparing your decisions and yourself to, and 3) let go of this ideal or fantasy and embrace a wider range of reality by making peace with what’s behind you, so you can focus more on what’s ahead.

It takes constant practice.

But you won’t regret it.

First published here. 


Written by Marc Chernoff, September 24, 2017


Stripe Payment Integration & Development in Codeigniter

This blog gives an overview on integration of stripe payment service in Codeigniter.

There are two types of payment services we can integrate using stripe.

  • Recurring Payment.
  • One Time Payment.

First step is to create a stripe account. Use the below link to create an account.

Once registered, confirm your email address using the activation link received in email. It will redirect you to a login page of stripe website. After login, you will be redirected to dashboard.

Recurring Payment

For this, we need to create a new subscription plan which will be used for recurring payment. To create a plan, click on Subscriptions from left menu -> Plans -> New. It will open a popup to create new plan as shown below.


We need to provide details for the below fields.

ID: Used for recurring payment which can be numeric or alpha numeric.

Name: Name of your subscription plan.

Currency: Select currency in which we want to accept payments.

Amount: Amount for the subscription.

Interval: Select subscription period. There are seven options available like daily, monthly, yearly, weekly, every 3 months, every 6 months and custom. In custom, we can set our own subscription period by entering number and selecting period from drop down like month(s), week(s) or day(s).

Trial period days: This field is optional and it is used if we want to give subscription as a trial for mentioned day(s).

Statement description: A description of the payment plan which optional and appear on statement.

When someone pays for the subscription or does a recurring payment, it is mandatory to create a customer. We can create customer through a php code.


$card_data = array(

            ‘number’ => $this->input->post(‘card_number’),

            ‘cvc’ => $this->input->post(‘cvv’),

            ‘exp_month’ => $this->input->post(‘exp_month’),

            ‘exp_year’ => $this->input->post(‘exp_year’),

            ‘name’ => $this->input->post(’email’),


 $dollars = str_replace(‘$’, ”, $this->input->post(‘amount’));

$cents = number_format((float)$dollars*100., 0, ‘.’, ”);   

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cent));

$stripeToken = $tokenArray->id;

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘service_name’);

$plan = $this->input->post(‘plan_name’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id; //return inserted customer id


How to integrate stripe payment gateway in codeigniter?

We need to create a basic view file which will accept the required data from the user like card number, card expiry month, card expiry year, card CVV number etc.

We need to mention controllerMethodName in the action of the form as shown below.

<form action=”controllerMethodName” method=”post”>



Stripe Payment

                   $ 11.50




Card Number






Email Address






Exp. Month





Exp. Year









                                      Pay Now





To integrate stripe payment gateway, we need two files. One is the library file and another is the configuration file. Both these files can be downloaded from the below URL.

After downloading the zip file from the above URL, we will get two files: one is and another is Stripe.php

We need to create one configuration file and put it in codeigniter’s application/config/stripe.php and put the following configurations.

// Configuration options

$config[‘stripe_key_test_public’]         = ”;

$config[‘stripe_key_test_secret’]         = ”;

$config[‘stripe_key_live_public’]         = ”;

$config[‘stripe_key_live_secret’]         = ”;

$config[‘stripe_test_mode’]               = TRUE;

$stripe = new Stripe( $config ); // Create the library object

Copy the above code and save it as stripe.php in config folder so the path of this file will be like: <PROJECT_FOLDER>/application/config/stripe.php

Stripe.php file will be placed in our codeigniter’s application/libraries folder, so the path of the Stripe.php file is like: <PROJECT_FOLDER>/application/libraries/Stripe.php

The basic functions are defined in the Stripe.php.

Steps to integrate stripe in Codeigniter

Include library file


Recurring Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),


$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

NOTE: We need to convert the amount into cents because stripe accept payment in cents. (e.g. $2.5 = 250cents)

We need to create a customer using below piece of code.

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘description’);

$plan = $this->input->post(‘plan_id’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));

We need to store the data into database and get the transaction id.

$transaction_id = $payWithStripe->id;

To cancel the subscription, use the below code.

$customer_id = $this->input->post(‘customer_id’);

$result = json_decode($this->stripe->customer_unsubscribe($customer_id,true));

$cancel_date = $result->current_period_end;

In the above function if we pass true then the subscription will be cancel at the end of the subscription period and if we pass it false then subscription will cancel immediately.

One Time Payment

Code is same as the recurring payment code. The only change is that it is not necessary to create a customer for onetime payment in stripe.

One Time Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),


$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));


We need to store the data into database and get the transaction id.


$transaction_id = $payWithStripe->id;

How to zip, save and download a file in codeigniter

In this article we are going to see how to zip, save, download a file in codeigniter PHP framework. codeigniter is a very popular PHP framework.  Codeigniter framework you can do many tasks very easily. Compressing and downloading or saving can be done very easily.

Zip Encoding Class

Zip class is used to create and download archives.  In controller you can initialize the zip class using


After loading the library we can use the zip object.


 Zip, Save and Download a file

The code snippet below shows how to create a zip file, save it and download it.

$filename = 'example.txt';

$filedata = 'This is an example file. Codeigniter zip class is used to zip, save and download the file';

$this->zip->add_data($filename, $filedata);

//Write the zip file to a folder on server with name. ""


//Download the file to system. Name it ""

Adding Controller in CodeIgniter

So if you want to zip, save, download a file in codeigniter then you have to do following

1. In Controller folder, Add a controller file and name it as, “Zip.php”2. Add a folder named “zippedfiles” in root folder.

3. Add the code below to the Zip.php file. 4. Run the code, a zip file is created and downloaded to your computer

Codeigniter controller code

  defined('BASEPATH') OR exit('No direct script access allowed');

  class Zip extends CI_Controller {

        public function __construct()

        public function index()
            $filename = 'example.txt';
            $filedata = 'This is an example file. Codeigniter zip class is 
                         used to zip, save and download the file';

            $this->zip->add_data($filename, $filedata); 
            //Create zip file on server with name.""

            //Download the file to your system. It will be named ""

Code Explanation

In code above We have created a class named Zip that extends CI_Controller. Inside constructor, that runs each time when a class object is created.  After calling parent constructor, we load zip library.

Inside index action we create a variable name $filename and a $filedata with content.

add_data method

$this->zip->add_data($filename, $filedata);

Zip object’s add_data method is called with $filename and $filedata params.

archive method


The code above, archive method of zip object saves file to a specified path.

download method


Finally the download method of zip class object downloads file to user’s computer.  The code above can be used in any of your project to zip and download zip archives.



Create Multiple Database Connections In CodeIgniter Applications

In real world CodeIgniter projects, developers need to work with multiple databases at the same time. This presents a unique challenge to developers. Since this is a common enough problem, CodeIgniter offers a simple solution for it.

In order to use multiple database connections in your CodeIgniter project, you just need to create multiple configuration arrays that simplify working with multiple databases.

The Default Configuration Array

Following is the structure of the default Codeigniter database configuration array:

So in order to create another database connection, you should create another configuration array. This array has to follow the same structure. Here is an example of the array:

Connect to the Right Database

At this point, you have two databases in your sample project. To connect to a specific database, you must specify the database name. Here is the proper syntax:

Now if you need to work with the second database, you have to send the connection to a variable that is usable in your model:

Close the Connections

CodeIgniter does close the database connections after it determines that the code no longer need the connection. However, as a good practice, developers should close the connections explicitly. Here is how to take care of the issue:


In this article, I have discussed the problem and the solution to using multiple database connections in CodeIgniter projects. If you need help with implementing the idea in your projects, do leave a comment below and I will get back to you.

By Owais Alam