Robert Jones
Robert Jones

Reputation: 408

PHP split the visitors to two different urls

I am working on my PHP script to split the visitors to 2 different urls as as I am doing this for split tests to see which site conversion the best.

Example: http://clicks.domain.com/439aa03e2de3e7fd95cb7cb28a4396c519c129eb0cef4f7b3ca48c43effd3269a8706f1bd0e3e33813929f8570f37fc32963e5715d020d38f38e60856c21b2ea

When the user click on the link, the first user will go to site A www.siteA.com, the second user will go to site B www.siteB.com, the third user will go to site A and so on.

Here is the code:

<?php


//Connect to the database
include('config.php');

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

if (!empty($url))
{
    $clicked_query = $link->prepare('SELECT clicked_today, campaign from tracking WHERE link = ? LIMIT 1');
    $clicked_query->execute([$url]);


    if ($clicked_query->rowCount() == 1)
    {
        $split_test_query = $link->prepare('SELECT site_A, site_B, campaign from split_test WHERE link = ? LIMIT 1');
        $split_test_query->execute([$url]);
        $row = $split_test_query->fetch(PDO::FETCH_ASSOC)
        $split_url_A = $row['site_A'];
        $split_url_B = $row['site_B'];

        if ($split_url_A !== site_B)
        {
            $split_test_query = $link->prepare('UPDATE split_test SET site_A = 1 WHERE id = ?');
            $split_test_query->execute([$id]);

            //User will visit Site A
            header('Location: http://www.sitea.com');
        }
        else
        {
            $split_test_query = $link->prepare('UPDATE split_test SET site_B = 1 WHERE id = ?');
            $split_test_query->execute([$id]);

            //User will visit Site B
            header('Location: http://www.siteb.com');
        }

        //Close connection
        $split_test_query = null;
    }

    //Close connection
    $$clicked_query = null;
}

I have stored 2 different urls in the database, so my question is do I have to use the database to update the value to allow me to control which site the users will visit?

Is that how it works? or i can do that by using .htaccess?

I have tried to find the answer on google but I couldn't be able to find it.

Thank you.

Upvotes: 0

Views: 274

Answers (1)

Vladan
Vladan

Reputation: 1632

In general, the approach is fine. Although, I'd recommend not to rely on the URL but on ID from the tracking table. Also, the condition to decide if is to go to site A or B is weird if ($split_url_A !== site_B). I would just use rand(1,2) and based on that pick the appropriate site.

EDIT:

Something like this can decide for you which site you need and then you'd just need a single SELECT query to find the appropriate link and a single UPDATE query to update the appropriate site.

$choices = [1 => 'site_A', 2 => 'site_B'];
$siteKey = rand(1,2);
$goToSite = $choices[$siteKey];

Upvotes: 1

Related Questions