+ 10
How to make a url shortener using php?
Please help me... This maybe offtopic but please tell me how this works. I have been willing to make a url shortener using php. But i dont know where to start. After reading some articles, I found out that I should make a database, when a person comes to the short url, php should search database and find where to go. But in this case the url people get will be something like this: www.mysite.com/short.php?key="atom" Here the atom is the shortened url. But i want it to be like this: www.mysite.com/atom Here there is no extension named php also there is no "?". But I dont how to do THIS. Please answer if you know anything related to this, because that could help solve my problem
7 Respostas
+ 6
Steve Sajeev here is one of many examples to help get you started https://nomadphp.com/blog/64/creating-a-url-shortener-application-in-php-mysql
there are many other options
+ 4
Thanks, BroFar
+ 3
Thanks đ©đ»đ»đźđ¶ .
I guess I'll have to learn more about htaccess.
+ 3
This is a great idea Joshua Schaeffer .
+ 1
Hi,
I implemented this using php with no database needed. Each time I create a directory based from the shortened URL and then added a single file called index.php with a redirect to the user specified URL. You can see it in action here https://joshuaschaeffer.work/s/
I will also post the 2 php files I used. Hopefully this helps and maybe gives you some ideas!
+ 1
index.php
<!DOCTYPE html>
<html>
<body>
<h1>URL Shortener</h1>
<form action="./generate.php" method="post">
<label for="shortened_url_label">New shortened URL: https://joshuaschaeffer.work/s/ </label><input type="text" id="shortened_url" name="shortened_url" value=""><br><br>
<label for="full_url_label">Redirect to this URL: </label><input type="text" id="full_url" name="full_url" value=""><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
generate.php
<?php
$full_url = $_POST['full_url'];
$shortened_url = $_POST['shortened_url'];
if(is_dir($shortened_url))
{
echo "Shortened URL already in use!";
}
else
{
//make the directory based on the shortened url
mkdir($shortened_url, 0777, true);
//add index.php file in /shorted_url directory
//this way we can simply link to website.com/shortened_url
$file_handle = fopen($shortened_url . "/index.php", "x+");
//prepare content to write to index.php
//simple redirect to whatever url is specified
$write_to_file = "<?php header(" . "\"Location: " . $full_url . "\"" . "); ?>";
fwrite($file_handle, $write_to_file);
fclose($file_handle);
echo $full_url . " successfully mapped to " . "/s/" . $shortened_url;
}
?>
+ 1
You may create some table in DB that stores short url and long one. When you request web page using short url under the hood you will search DB for matching record then redirect to correct url! In this case I would suggest using storages like Redis instead of relational databases to access data quickly.