Afnan Bashir
Afnan Bashir

Reputation: 7419

Get Random Url from website

I want to search number of links or URL on http://public-domain-content.com and store them in an array and then just randomly select any one from array and just display or echo

How can i do that in php

Upvotes: 0

Views: 1756

Answers (1)

Lockhead
Lockhead

Reputation: 2451

If I understood what you're asking, you can achieve this using file_get_contents();

After using file_get_contents($url), which gives you a string, you can loop through the result string searching for spaces to tell the words apart. Count the number of words, and store the words in an array accordingly. Then just choose a random element from the array using array_rand()

However, sometimes there are security problems with file_get_contents(). You can override this using the following function:

function get_url_contents($url)
{
    $crl = curl_init();
    $timeout = 5;
    curl_setopt ($crl, CURLOPT_URL,$url);
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $ret = curl_exec($crl);
    curl_close($crl);

    return $ret;
}

http://php.net/manual/en/function.curl-setopt.php <--- Explanation about curl

Example code:

$url = "http://www.xxxxx.xxx";     //Set the website you want to get content from
$str = file_get_contents($url);    //Get the contents of the website
$built_str = "";                   //This string will hold the valid URLs

$strarr = explode(" ", $str);      //Explode string into array(every space a new element)

for ($i = 0; $i < count($strarr); $i++)  //Start looping through the array
{
    $current = @parse_url($strarr[$i])   //Attempt to parse the current element of the array

    if ($current)                        //If parse_url() returned true(URL is valid)
    {
        $built_str .= $current . " ";    //Add the valid URL to the new string with " "
    }

    else
    {
        //URL invalid. Do something here
    }

}

$built_arr = explode(" ", $built_str)   //Same as we did with $str_arr. This is why we added a space to $built_str every time the URL was valid. So we could use it now to split the string into an array

echo $built_arr[array_rand($built_arr)]; // Display a random element from our built array

There is also a more extended version to checking URLs, which you can explore here:

http://forums.digitalpoint.com/showthread.php?t=326016

Good luck.

Upvotes: 2

Related Questions