Reputation: 1
Basically I am creating a URL shortener. I have stored URLs in my Database and each URL has unique ID. So what I want now is that whenever somebody visits http://localhost/anyfolder/4
(Here 4
is the ID of the URL, say http://google.com) then he should be redirected to http://google.com. I hope you got my point. Currently with my knowledge I have created following .htaccess file.
RewriteEngine On
RewriteCond $1 !^(redirect\.php)
RewriteRule ^(.*)$ redirect.php?l=$1 [L]
I also have one redirect.php file but don't know how to code it in a way so that it can redirect. Please tell me that how can I code it in such a way so that it can redirect properly. Just want to tell that might be my .htaccess file is also wrong. So if you know then please help me out!
EDIT : I have two more files. One is simple index.html
<form action="process.php" method="post">
URL(with "http://"): <input type="text" name="url">
<input type="submit">
</form>
and the other is process.php which does all the work of storing and giving back the user his unique ID
<?php
$con=mysqli_connect("localhost","root","","url");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$url = $_POST['url'];
$sql=mysqli_query($con,"INSERT INTO url (url)VALUES('$url')");
$result = mysqli_query($con,"SELECT * FROM url WHERE url='$url'");
while($id = mysqli_fetch_array($result))
{
echo " URL Shortened Successfully! ".'<br>'."Your shortened URL is ";
echo 'http://localhost/redirect/' . $id['id'];
}
mysqli_close($con);
?>
Upvotes: 0
Views: 1754
Reputation: 4887
redirect.php
<?php
$LocationId = (isset($_GET['l'])) ? $_GET['l'] : null;
if( $LocationId )
{
$DBConn = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Connection Error");
$Resut = mysqli_query($DBConn,
sprintf("SELECT url FROM url WHERE id LIKE '%s' LIMIT 0,1",
mysqli_real_escape_string($DBConn, $LocationId)
)
) or die( mysqli_error($DBConn) );
if( $Resut )
{
$Row = mysqli_fetch_array($Resut);
if( isset($Row['url']) && !empty($Row['url']) )
{
header('HTTP/1.1 301 Moved Permanently');
header(sprintf('Location: %s', $Row['url']));
exit;
}
}
}
?>
Upvotes: 1