Create Secure API in php

by Subramanian 2013-09-06 16:30:16

Create Secure API in php :

The Api without security is response to the request from all the unknown server. For avoid this type of data theft we are using secure api in php.

Here api is created with key and id based. that is the api only response to which the key is matched in request.

First we create secured api with key.

$keyId = 'ID0123';
$keyValue = '6c928e33423d9466a263cb9c6a02d1a2';

$req_id = $_REQUEST['id'];
$request_array = $_REQUEST['request_array'];
$request = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $keyValue, base64_decode($request_array), MCRYPT_MODE_ECB)));

//$request is a json array with decrypted value of request. now you can do what you want with this data and return response to the server
return "Invalid Request";

In this code $_REQUEST['id'] and $_REQUEST['request_array'] is requested from another server using curl in php.

Now we create the api caller using curl method.

$keyId = 'ID0123';
$keyValue = '6c928e33423d9466a263cb9c6a02d1a2';

$items = array('action' => 'getUserDetails','userid' => $_SESSION['id'],'userpass' => $_SESSION['userpass']);

$requests = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $keyValue, json_encode($items), MCRYPT_MODE_ECB));

$request_array = array();
$request_array['request_array'] = $requests;
$request_array['id'] = $keyId;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($request_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_array);

$result = curl_exec($ch);

Here we are passed encrypted key id and items with encrypted json value. this curl pass all the value to api and in api match the key id . if it matched then decrypt the data and process the request and return response.

You must LOGIN to add comments