POSTing JSON Data With PHP cURL

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!

Advertisements

cURL Requests with PHP

Introduction

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.

Basics

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.

Settings

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 http://testcURL.com:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://testcURL.com');

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

$curl = curl_init('http://testcURL.com');

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_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com'
));

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 http://testcURL.com/?item1=value&item2=value2.

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_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

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_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

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.

Errors

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:

if(!curl_exec($curl)){
    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_exec($theEnd);

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.

 

Source:  http://codular.com/

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.

https://dashboard.stripe.com/register

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.

CreateNewPlan

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

                                     

                            

                            

                                     

CVV

                                     

                            

                            

                                      Pay Now

                            

                   </div>

          </div> 

</form>

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.

https://github.com/chrismackie28/php-stripe

After downloading the zip file from the above URL, we will get two files: one is README.md 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

$this->load->library(‘stripe’);

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

$this->load->library('zip');

After loading the library we can use the zip object.

$this->zip

 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. "example_backup.zip"

$this->zip->archive('/images/example_backup.zip');

//Download the file to system. Name it "my_backup.zip"
$this->zip->download('example_backup.zip');

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

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

  class Zip extends CI_Controller {

        public function __construct()
        {
            parent::__construct();
            $this->load->library('zip');
        }

        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."example_backup.zip"
            $this->zip->archive('/zippedfiles/example_backup.zip');  

            //Download the file to your system. It will be named "example_backup.zip"
            $this->zip->download('example_backup.zip');
        }
    }

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

$this->zip->archive('/zippedfiles/example_backup.zip');  

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

download method

$this->zip->download('example_backup.zip');

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.

 

source: https://programmerblog.net/

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:

Conclusion

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

Pass Data From One Function To Another In Same Codeigniter Controller

A controller often comprises of several functions and often the module’s logic demands passing data between the various functions of the Controller. This is a common enough scenario in many Codeigniter projects. In this tutorial, I will demonstrate how you could pass data between two functions within the same Controller in CodeIgniter. In addition, I will show this data in the View.

pass data between functions in CodeIgniter

Here is what the Model looks like:

Model

The Controller is as follows:

Controller

The following View shows the data that has been passed between the functions of the Controller.

View

Conclusion

In this tutorial, I have discussed how to pass data from one function to another in a Controller. You could easily extend this idea within your Codeigniter projects. If you need help, do leave a comment below.

 

 

By Shahroze Nawaz  September 27, 2017

 

 

 

 

Restlet Client – REST API Testing

Client

Visually create and execute single API requests as well as complex scenarios. Automate the execution of your API tests and scenarios with our CI/CD plugin. Restlet Client is the most popular REST client available as a Chrome extension. It automatically updates itself, can be opened in one or several browser tabs and comes with a convenient browser toolbar icon.

  • Send requests

    Send requests and inspect responses

    Restlet Client handles all HTTP requests, no matter how complex. Requests can be made dynamic by inserting variables. Security and authentication are fully supported, as well as hypermedia and HTML forms. You can inspect HTTP responses and easily validate them thanks to assertions. Finally, an history of recent requests is always available to facilitate re-sending.

  • Automate your REST APIs

    With Restlet Client, you can combine multiple API requests into complex scenarios. Data can be passed from one response to the next request, creating functional scenarios that simulate real usage of an API by a frontend, a mobile application or any HTTP client.

    Orchestrate APIs
  • Test API

    Test the behavior of any API

    Whether you want to check that your API is behaving as specified, or you need to confirm how well third-party APIs are responding, Restlet Client lets you perform many sorts of API response tests such as on the value of headers, parts of the body or response time among others. Several environments can also be created including variables to increase the reusability of your tests.

  • Integrate API testing in your CI/CD toolchain

    When your API testing is part of a continuous delivery process, Restlet Client can integrate natively with Continuous Integration/Delivery (CI/CD) solutions like Jenkins, Travis CI or Circle CI. Thanks to our Maven plugin and native GitHub integration, your scenarios are continuously pushed and tested as part of your DevOps toolchain, improving the quality of your APIs.

    API
  • Test reports

    Generate test reports for your APIs

    Restlet Client provides an integrated reporting capabilities at both the project and the scenario levels. The reports produced help you understand your tests progress in a synthetic way and print to PDF. You can then share those reports within your DevOps team or with business persons to show progress of an API implementation, of tests coverage or production status.

  • Make API testing collaborative and fun

    Restlet Client lets you store test projects securely in the cloud and open them from anywhere. You can share projects with your team members and collaborate over API testing, for example QA testers can define scenarios and developers bind them to actual API endpoints. API tests can also be imported from Postman Collections, OAS contracts (fka Swagger) or HAR files.