Use a while loop:
$random_string = randString(10);
$is_unique = false;
while (!$is_unique) {
$result = query_the_database('SELECT id FROM table_with_random_strings WHERE random_string_column = "'.$random_string.'" LIMIT 1');
if ($result === false) // if you don't get a result, then you're good
$is_unique = true;
else // if you DO get a result, keep trying
$random_string = randString(10);
}
I left the database code generic, since I am not sure what you're using... but I hope it is mysqli or PDO :)
Also wanted to mention, there are functions out there that generate unique strings for you, for example uniqid. Such functions would probably have more success at generating a unique string in the first go, making the while loop unnecessary most of the time -- which is a good thing.
echo uniqid(); // 502ec5b8ed2de
However, you don't have as much control over the length, and if that is important than you can stick with your homebrew random generator -- just expect the likelihood of collisions to be greater.
Edit Another thing: usually, instead of a random string that is meaningless to your user, many content publishing systems will use the article title. This is called (sometimes) a "post slug". If you have a title of "November 17th: Gorillas Gone Wild, Topless Apes Live!", the url would be:
http://www.mywebsiteaboutgorillas.com/november-17th-gorillas-gone-wild-topless-apes-live
Such a URL has more meaning to your user than:
http://www.mywebsiteaboutgorillas.com/jh7sj347dfj4
To make a "post slug":
function post_slug($url='', $sep='-') {
// everything to lower and no spaces begin or end
$url = strtolower(trim($url));
// adding - for spaces and union characters
$find = array(' ', '&', '\r\n', '\n', '+',',');
$url = str_replace ($find, '-', $url);
//delete and replace rest of special chars
$find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
$repl = array('', '-', '');
$url = preg_replace ($find, $repl, $url);
if ($sep != '-')
$url = str_replace('-', $sep, $url);
//return the friendly url
return $url;
}
... you do still have to watch out for uniqueness there, sometimes CMSes will append the date or id as a pseudo-subdirectory to help mitigate against repetition. You might be able to work something like that into your URL shortener, to give the user at least some indication of what they're about to click.
Documentation
pas a get variable that holds the random string, then fetch the url from the database that belongs to that string?