Creating static php array to store values

383 Views Asked by At

im having a redirect feature in my own website where users are redirected to sites which are white listed and ridirect enabled.

as an example, if the user url is

mydomain.ridirect.com/rdrct?site=www.goog.com

now the relevent script makes a database call and in the db theres a table to check whitelisted domains, and also it tells whether the domain name is redirect enabled

id  domain_name  redirect
1   www.yah.com  1
2   www.go.com   0
3   www.goo.com  1
4   www.foo.com  1

now the example user will be redirected since it whitelisted and redirect enabled.

Now to the problem, this design is a pretty expensive one in the live run.. most of the time it consumes a lot of time. everytime a user comes it makes a db call.

Therefore now im declaring array before the database call is made,

$redirect = array();

if its a correct domain name by meeting its criterias, the values will be added to the above array

array_push($redirect, $trusted_domain, $id, $row["redirect"]);
var_dump($redirect);

so my design is, if the user types the same domain names again, it will not make db call instead it will chk the array an proceed.

therefore can anybody help me to create a staic array(persist the array over the course of multiple requests) matching to this scenario...

2

There are 2 best solutions below

0
On

I'm just guessing you need something like this :

$arr = array();
$arr['www.example.com'] = array('redirect' => true);
$arr['www.example2.com'] = array('redirect' => true);
$arr['www.example3.com'] = array('redirect' => false);

//and then on the request

if(isset($arr[$_GET['site']]) && $arr[$_GET['site']]['redirect']){
    //redirect logic
}

I used array on the url key(redirect => true) to allow future options.

If this list will get too big, it's gonna be a pain to maintain.

I suggest you have a database the manage it and automatically create a static file out of it.

1
On

If you need to persist the array over multiple requests have a look at:

APC http://php.net/manual/en/book.apc.php

APCU Please use apcu for newer versions of PHP https://pecl.php.net/package/APCu as mentioned in the comment below.

Using apc the solution would be: To add the redirect url to the cache after loading it via. the database using apc_add and after that use apc_exists to check if the url is allowed.

Alternatively you can try to use some other key-value storage like http://redis.io/