Skip to content

Securing with phpdotenv

Armando Lüscher edited this page May 23, 2020 · 2 revisions

An easy way to keep your credentials safe, is to use vlucas/phpdotenv.

Here's how it works:

  1. Install using composer

composer require vlucas/phpdotenv

  1. Create a .env file outside of your public web folder, e.g.
|-- .env
|-- src (public facing web folder)
    |-- hook.php
|-- vendor
|-- composer.json
  1. Enter environment variables to the .env file containing your credentials
# Bot vitals
BOT_API_KEY="123456789:abcdefghijklmnopqrstuvwxyz123456789"
BOT_NAME="My_Bot"
BOT_SECRET="super_secret_1"
BOT_WEBHOOK="https://mybot.com/hook.php"

# Database
DB_HOST="127.0.0.1"
DB_USER="mybot"
DB_PASS="super_secret_2"
DB_NAME="mybot"

# Bot optional
BOT_ADMIN=12345
  1. Load phpdotenv and use the environment variables to set up your bot
<?php
// src/hook.php

use Dotenv\Dotenv;
use TelegramBot\TelegramBotManager\BotManager;

require_once __DIR__ . '/../vendor/autoload.php';
(new Dotenv(__DIR__ . '/..'))->load();

try {
  $bot = new BotManager([
    // Vitals!
    'api_key' => getenv('BOT_API_KEY'),
    'botname' => getenv('BOT_NAME'),
    'secret'  => getenv('BOT_SECRET'),
    'webhook' => getenv('BOT_WEBHOOK'),

    // Optional extras.
    'admins'  => [(int) getenv('BOT_ADMIN')],
    'mysql'   => [
      'host'     => getenv('DB_HOST'),
      'user'     => getenv('DB_USER'),
      'password' => getenv('DB_PASS'),
      'database' => getenv('DB_NAME'),
    ],
  ]);

  $bot->run();
} catch (\Exception $e) {
  // Silence is golden!
}
  1. Done!

(Remember, you can use this for all possible parameters, so be sure to check the readme!)

Clone this wiki locally