Burak Dede Burak Dede - 1 month ago 10
MySQL Question

How do append URL code from database to domain name and redirect with PHP?

I am on half of URL shortening system. I get the URL from the user and then create code in MySQL for that. Then I have to append coming code to my domain name (now I am working on localhost) like http://localhost/a5c3 then redirect it to real domain.

I stuck in here. A code snippet would be good for me at least to understand what I am going to do or you can explain what I am going to do.

Answer

if you are not associating short code with a url then you need to do that, and redirection will be easy.

Algorithm:

Save url from the form and generated code to the database for later use.

$url = $_POST['url']
generate code
Concatenate your url with the code
$full_url = $url.$code

show shortened url to user.

if you want redirect user, after he/she put the url in the browser addres then do this. create .htaccess file add following lines to it and drop it to your root folder.,

RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?code=$1 [L]

.htaccess file will redirect everything to your index.php. for example if user types http://example.com/ujijui then .htaccess will call http://example.com/index.php?code=ujijui. so you can capture query string in the url by using $_GET.

in your index.php

$code = $_GET['code']
mysql_connect('localhost', 'user', 'password')
mysql_select_db('your_db')
$sql = "SELECT url from Table where code=$code" 
$result = mysql_query($sql)
loop through result and get url

header("Location: $url")

get it, this is just algorithm.