0

I have a php api endpoint as below.

I need to make changes something like:

  1. need to include all the configurations in the seperate file

  2. validate API request using a server token to ensure to accept only genuine requests

  3. Capture all the error logs in a seperate file, instead of showing in the browser

This is my code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = json_decode(file_get_contents('php://input'), true);

if(!empty($data)):
header('Content-Type:text/plain');


 /*MYSQL CREDENTIALS*/
$hostname = 'localhost';                 
$username = 'root';
$password = '';
$dbname = 'mydb';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

$arraykey=array_keys($data); 
$array=$data[$arraykey[0]]; 

try 
{

    foreach($data as $array)
    {

    //MYSQL execute
    $count = $dbh->exec("INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ('" . implode("', '", $array) . "')" ) or die(print_r($dbh->errorInfo(), true)); 

    echo count($data);
    echo 'Data Successfully inserted!!<br />';
}
//echo $data;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

endif;
?>

For point 1) I have put all the configs in a seperate file like:

<?php
define (DB_USER, "root");
define (DB_PASSWORD, "");
define (DB_DATABASE, "mydb");
define (DB_HOST, "localhost");
?>

Need clarity on the better way to include this config file in my main file.

Since im sharing the API endpoint to client, the main file should be able to read my db config files.

So which is suggested to use:

require ("configuration.php");

OR

$config = parse_ini_file('../config.ini'); 

Suggestion required for other 2 points

Imanuel
  • 3,596
  • 4
  • 24
  • 46
Sach
  • 83
  • 4
  • 24

1 Answers1

0

Here are suggestion for another two points:

  1. validate API request using a server token to ensure to accept only genuine requests

For this you can use CSRF Token to check for valid request. you can find here important use of this.

  1. List item Capture all the error logs in a separate file, instead of showing in the browser

By default PHP log everything in server side. in Ubuntu you can find /var/log/apache/error.log

Just you need to check your apache configuration is properly set for error logs

Read here for more info : Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

if you don't want to show your error in browser then you can set error_reporting(0);

Hope this is what you need !!

Community
  • 1
  • 1
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33