У меня есть проект, в котором пользователи переходят на предоставленный shortURL, который перенаправляет всех на похожую форму с разными названиями компаний.
В настоящее время у меня есть MySQL база данных, которая выглядит следующим образом:
tbl_Codes
- shortURL (string of 5 alphanumeric characters)
- businessID (ID of business which matches the ID in the table below)
tbl_Business
- businessID
- businessName
- other fields....
Итак, кто-то, кто переходит на example.com / 12345 , видит форму с названием компании, которая соответствует businessID, а кто-то, кто переходит на example.com / abcde , видит в той же форме, но с названием другого бизнеса.
Будет ли что-то вроде этого лучшим способом сделать это? Если нет, то как?
Связанный скрипт использует PHP regex , чтобы получить shortURL, сопоставить строку в базе данных, затем выполнить 301 перенаправление . Если не совпадает, он перенаправляет на страницу 404 (хотя я, вероятно, не сделал бы 404 бит).
Заранее спасибо.
Вот код, если вы не хотите нажимать на ссылку. Это из учебника:
<?php
$expectedURL = trim($_SERVER['URL']);
$split = preg_split("{:80\/}",$expectedURL);
$shortURL = $split[1];
// security: strip all but alphanumerics & dashes
$shortURL = preg_replace("/[^a-z0-9-]+/i", "", $shortURL);
// Check this string to see if it matches a short URL in our database.
$isShortURL = false;
$result = getLongURL($shortURL);
if ($result) { $isShortURL = true; }
$longURL = $result['longURL'];
// Finally, we check to see if our $isShortURL flag is set.
// If a matching short URL was found, we’ll redirect to it.
// If not, we’ll display our standard 404.
if ($isShortURL)
{
redirectTo($longURL, $shortURL);
} else {
show404(); // no shortURL found, display standard 404 page
}
//The primary function:
// Get the long URL associated with the passed short URL, if it exists.
function getLongURL($s)
{
// define these variables for your system
$host = ""; $user = ""; $pass = ""; $db = "";
$mysqli = new mysqli($host, $user, $pass, $db);
// you may just want to fall thru to 404 here if connection error
if (mysqli_connect_errno()) { die("Unable to connect !"); }
$query = "SELECT * FROM urls WHERE shorturl = '$s';";
if ($result = $mysqli->query($query)) {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
return($row);
}
} else {
return false;
}
} else {
return false;
}
$mysqli->close();
}
//Perform the URL redirection.
function redirectTo($longURL)
{
// change this to your domain
header("Referer: http://www.your-domain-here.com");
// use a 301 redirect to your destination
header("Location: $longURL", TRUE, 301);
exit;
}
//Finally, display your standard 404 page here.
function show404()
{
// display/include your standard 404 page here
echo "404 Page Not Found.";
exit;
}
?>