PHP API interface

In actual work, using PHP to write API interface is often do, write a PHP interface, the front desk can interface provides the data accessed by the link, and the returned data generally divided into two situations, XML and json, in this process, the server does not know, what is the source of the request, it is possible that someone else illegal calls our interface, Get the data, so use security authentication.

Verify the principle

Schematic diagram

The principle of

As you can clearly see from the figure, the foreground needs to generate a signature using several parameters to invoke the interface.

Timestamp: current time

Random number: a random number generated randomly

Password: an identifier known to both parties during front-end and back-end development, equivalent to a code word

Algorithm rule: An agreed algorithm rule. The above three parameters can be used to generate a signature.

The foreground generates a signature and passes the timestamp, random number, and signature to the background via the URL when it needs to access the interface. Background to get the timestamp, random number, through the same algorithm rules to calculate the signature, and then pass the signature for comparison, the same words, return data.

Algorithm rules

In front and background interaction, algorithm rules are very important. Both front and background should calculate the signature through algorithm rules. As for how to make rules, it depends on how you like.

The rule of my algorithm is

1 Time stamp, random number, password sorted in alphabetical order

The 2’s are then concatenated into a string

3 Perform SHA1 encryption

4 Perform MD5 encryption

Convert 5 to uppercase.

The front desk

Instead of using an actual foreground, I use a PHP file instead of a foreground and CURL to simulate a GET request. I’m using a TP framework and the URL format is pathinfo.

The source code


      
/** * Created by PhpStorm. * User: Administrator * Date: 2017/3/16 0016 * Time: 15:56 */
namespace Client\Controller;
use Think\Controller;
class ClientController extends Controller{
 const TOKEN = 'API';
 // Simulate the foreground request server API
 public function getDataFromServer(){
  / / timestamp
  $timeStamp = time();
  / / random number
  $randomStr = $this -> createNonceStr();
  // Generate a signature
  $signature = $this -> arithmetic($timeStamp.$randomStr);
  / / url
  $url = "http://www.apitest.com/Server/Server/respond/t/{$timeStamp}/r/{$randomStr}/s/{$signature}";
  $result = $this -> httpGet($url);
  dump($result);
 }
 //curl emulates a get request.
 private function httpGet($url){
  $curl = curl_init();
  // Which address to request
  curl_setopt($curl,CURLOPT_URL,$url);
  // Outputs the requested data as a file stream to a variable
  curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
  $result = curl_exec($curl);
  curl_close($curl);
  return $result;
 }
 // Randomly generate a string
 private function createNonceStr($length = 8) {
  $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  $str = "";
  for ($i = 0; $i < $length; $i{+ +)$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  }
  return "z".$str;
 }
 / * * *@param$timeStamp timeStamp *@param$randomStr A random string *@returnString Returns the signature */
 private function arithmetic($timeStamp.$randomStr){
  $arr['timeStamp'] = $timeStamp;
  $arr['randomStr'] = $randomStr;
  $arr['token'] = self::TOKEN;
  // Sort by uppercase
  sort($arr,SORT_STRING);
  // Concatenate to a string
  $str = implode($arr);
  // Encrypt
  $signature = sha1($str);
  $signature = md5($signature);
  // Convert to uppercase
  $signature = strtoupper($signature);
  return $signature; }}Copy the code

The server side

Accept foreground data for validation

The source code


      
/** * Created by PhpStorm. * User: Administrator * Date: 2017/3/16 0016 * Time: 16:01 */
namespace Server\Controller;
use Think\Controller;
class ServerController extends Controller{
 const TOKEN = 'API';
 // Respond to requests from the foreground
 public function respond(){
  // Verify identity
  $timeStamp = $_GET['t'];
  $randomStr = $_GET['r'];
  $signature = $_GET['s'];
  $str = $this -> arithmetic($timeStamp.$randomStr);
  if($str! =$signature) {echo "1";
   exit;
  }
  // Simulate data
  $arr['name'] = 'api';
  $arr['age'] = 15;
  $arr['address'] = 'zz';
  $arr['ip'] = "192.168.0.1";
  echo json_encode($arr);
 }
 / * * *@param$timeStamp timeStamp *@param$randomStr A random string *@returnString Returns the signature */
 public function arithmetic($timeStamp.$randomStr){
  $arr['timeStamp'] = $timeStamp;
  $arr['randomStr'] = $randomStr;
  $arr['token'] = self::TOKEN;
  // Sort by uppercase
  sort($arr,SORT_STRING);
  // Concatenate to a string
  $str = implode($arr);
  // Encrypt
  $signature = sha1($str);
  $signature = md5($signature);
  // Convert to uppercase
  $signature = strtoupper($signature);
  return $signature; }}Copy the code

The results of

string(57) "{"name":"api","age: 15, ""address":"zz","ip":"192.168.0.1"}"
Copy the code

conclusion

This is just one of many ways that security can be verified.

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database