私は、ユーザーが提供された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正規表現を使用して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;
}
?>