mdhz
mdhz

Reputation: 113

Add multiple constant value in PHP

I have a problem in my php script. This is the script

<?php 
    define("BASE_URL", "http://external.site/xxx/API.php");
    define("APIKEY", "46B067078483416eBedB2f8005586eB7","7285e87c1c7Ac16c5870A4cf5cf166f8");

    $action = $_GET['action'];
    $api_key = APIKEY;
?>

The problem is when my clients access the second key which is 7285e87c1c7Ac16c5870A4cf5cf166f8 the first key(46B067078483416eBedB2f8005586eB7) is being charged,

How can I add multiple keys so each key(whichever is requested) is charged separately?

Thanks.

Upvotes: 1

Views: 1580

Answers (2)

David Kariuki
David Kariuki

Reputation: 1756

To do this, you can use const or define. It all depends on what you want to do.

So you can do use const (PHP 5.6+)

const APIKEY = ['46B067078483416eBedB2f8005586eB7','7285e87c1c7Ac16c5870A4cf5cf166f8']; 

Or use define (PHP 7+)

define("APIKEY", ['46B067078483416eBedB2f8005586eB7','7285e87c1c7Ac16c5870A4cf5cf166f8']);

Getting the values

echo APIKEY[0]; // To get the 1st key => 46B067078483416eBedB2f8005586eB7
echo "<br/>"; // Line break
echo APIKEY[1]; // To get the 2nd key => 7285e87c1c7Ac16c5870A4cf5cf166f8

If you want to have more constants within the definition, you can use define passing an associative array as the second argument. (PHP 7+)

define(
    "APIKEY", array(
        "KEY_1" => "46B067078483416eBedB2f8005586eB7",
        "KEY_2" => "7285e87c1c7Ac16c5870A4cf5cf166f8",
        "KEY_n+1" => "") // As many as you want
);

To get your keys

echo APIKEY['KEY_1']; // To get the 1st key 46B067078483416eBedB2f8005586eB7
echo "<br/>"; // Line break
echo APIKEY['KEY_2']; // To get the 1st key 7285e87c1c7Ac16c5870A4cf5cf166f8

Upvotes: 0

JCH77
JCH77

Reputation: 1363

define() accepts only 2 parameters, not 3.

You can use an array. You have 2 possibilities :

const APIKEY = ['46B067...','7285e8...']; // PHP 5.6+
// OR
define('APIKEY', ['46B067...','7285e8...']); // PHP 7+

// THEN
echo APIKEY[0]; // Access 1st key => 46B067...
echo APIKEY[1]; // Access 2nd key => 7285e8...

Upvotes: 2

Related Questions