2019-01-13 Pujan Niroula 3 Minute(s) Read

Make a Simple URL Shortener System in PHP

img-url shortener with php thumbnail.jpg

Short URL is popular for sharing links over social media because it looks tinycool. There are many free URL Shortener services available on internet but it's cool to use your own.

In this tutorial I will show you how to create own URL shortening application just using PHP. Oh hell! you heard right, Just using PHP.

Let's Start,

How to Create own URL Shortener System with PHP

We have to create 3 files

  1. index.php
  2. url_list.php
  3. .htacess

You must upload all 3 files in server. Which is available to download below.

First of all lets start with, I set URL of web and default message which is empty.

$baseurl = 'https://pujann.com.np/';
$msg = '';

After that I created function named short_url

function short_url($url)
{
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $rand_str = substr(str_shuffle(md5(rand())),0,6);
        $oldfile = file_get_contents('url_list.php')."\n";
        $newfile = '$list[\''.$rand_str.'\']=\''.$url.'\';';
        file_put_contents('url_list.php', $oldfile.$newfile);
        return $rand_str;
    } else {
        return false;
    }
}

It will check url is valid or not using filter_var function and later it Generates Random String of 6 digits. I am lazy one so I use file_get_contents and file_put_contents instead of fopen() fwrite(). I stored all file content in oldfile variable and stored new URL and new random string in newfile variable. And finally I put new file after the old file with file_put_content function.

Now Let's check user visited previously created short URL or not if visited redirect them to their respective URL else back to home.

if (isset($_GET['url'])) {
    require_once('url_list.php');
    if (isset($list[$_GET['url']])) {
        $link = $list[$_GET['url']];
        header('location:'.$link);
    } else {
        header('location:'.$baseurl);
    }
}

Else if user tries to create short URL then it will call short_url function which we created before to add url on other file and set message.

elseif(isset($_POST['url'])) {
    $check = short_url($_POST['url']);
    if ($check) {
        $msg = "<p class=\"success\">Url Created
        <a href=\"{$baseurl}{$check}\">{$baseurl}{$check}</a></p>";
    } else {
        $msg = "<p class=\"error\">Invalid Url</p>";
    }
}

Lets Sum all Codes for index.php file.

<?php
$baseurl = 'http://pujann.com.np/';
$msg = '';

//Lets Short LONG URL
function short_url($url)
{
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $rand_str = substr(str_shuffle(md5(rand())),0,6);
        $oldfile = file_get_contents('url_list.php')."\n";
        $newfile = '$list[\''.$rand_str.'\']=\''.$url.'\';';
        file_put_contents('url_list.php', $oldfile.$newfile);
        return $rand_str;
    } else {
        return false;
    }
}
//check if user visited
if (isset($_GET['url'])) {
    require_once('url_list.php');
    if (isset($list[$_GET['url']])) {
        $link = $list[$_GET['url']];
        header('location:'.$link);
    } else {
        header('location:'.$baseurl);
    }
} elseif (isset($_POST['url'])) {
    $check = short_url($_POST['url']);
    if ($check) {
        $msg = "<p class=\"success\">Url Created
        <a href=\"{$baseurl}{$check}\">{$baseurl}{$check}</a></p>";
    } else {
        $msg = "<p class=\"error\">Invalid Url</p>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Url Shortener-Pujann</title>    
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { padding: 1% 20%; margin: 0 auto; }
        .error{color:red; border: 1px solid red; padding: 5px;}
        .success{color:green; border: 1px solid green; padding: 5px;}
        input{padding: 5px; margin: 0px; background: lightgrey; width: 75%;}
    </style>
</head>
<body>
    <?php echo $msg;?>
    <form action="#" method="post">
        <input type="url" name="url" placeholder="Place Long Url eg:https://google.com">
        <input type="submit" name="submit" value="Short It">
    </form>
    <a href="http://pujann.com.np">By Pujann</a>
</body>
</html>

In url_list.php file just put php opening tags, This will keep increasing each time if you used shortener.

<?php

In .htaccess file just put

RewriteEngine On
RewriteRule ^([a-z0-9]{6})$ index.php?url=$1

Done!!!

This much for today... Hope to see you in comment section below.

Download Attached Files: Simple URL Shortener with PHP.zip
Comments (69) Add New Comment
gel polish2024-06-19 4:06 AM

Hello there! This article couldn't be written much better! Looking at this post reminds me of my previous roommate! He always kept talking about this. I am going to send this article to him. Pretty sure he will have a very good read. Thank you for sharing!

Reply
salon gel polish2024-06-19 3:45 AM

I simply could not depart your web site prior to suggesting that I actually enjoyed the standard information a person supply to your guests? Is going to be again frequently to inspect new posts

Reply
webpage2024-06-19 2:24 AM

Exceptional post but I was wondering if you could write a litte more on this subject? I'd be very thankful if you could elaborate a little bit more. Bless you!

Reply
TTD Surveillance Camerawoman2024-06-18 12:41 AM

Somebody essentially lend a hand to make seriously articles I'd state. That is the very first time I frequented your website page and up to now? I amazed with the analysis you made to make this particular publish incredible. Fantastic activity!

Reply
penipu2024-06-17 12:02 PM

Does your website have a contact page? I'm having problems locating it but, I'd like to shoot you an e-mail. I've got some ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it expand over time.

Reply
media marketing2024-06-17 11:29 AM

Hi! Do you know if they make any plugins to help with Search Engine Optimization? I'm trying to get my website to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Kudos! I saw similar art here: blogexpander.com

Reply
togelsdy.id2024-06-16 8:50 PM

What's up to all, how is everything, I think every one is getting more from this web site, and your views are pleasant in support of new users.

Reply
zizporno.cc2024-06-16 11:01 AM

zizporno.cc

Reply
undress ai2024-06-16 4:53 AM

whoah this weblog is magnificent i like reading your articles. Keep up the great work! You understand, many persons are hunting around for this info, you can aid them greatly.

Reply
mumbai escorts2024-06-16 2:21 AM

What i don't understood is in truth how you are now not actually a lot more smartly-liked than you may be right now. You are so intelligent. You know thus considerably in relation to this subject, produced me in my opinion imagine it from numerous various angles. Its like women and men are not interested except it is something to do with Woman gaga! Your own stuffs excellent. All the time care for it up!

Reply
Dinogame.app2024-06-15 10:47 AM

Kudos, Numerous data!

Reply
kanye west poster seller2024-06-15 6:18 AM

Kanye West prints are a great addition for any fan's decor. The artwork are often vibrant and capture his iconic image. Whether you admire his creativity or simply like pop culture art, there's a wide range available. Having a Mr. West poster not only shows your support for his work, but also gives an artistic flair to your space. From "The College Dropout" to "Jesus Is King", there's a print that captures each phase of his evolution. I recently got a Kanye West poster to my wall, and I love it. The print detail is top-notch, and it really stands out. If you're on the fence about getting one, go for it—you won't regret it.

Reply
Luongson TV2024-06-14 10:51 AM

Very good article. I am dealing with some of these issues as well..

Reply
diplomaxose2024-06-14 4:43 AM

?????? ???????? ??????????? ??? ??? ???????? ???????????? (?????) ?? ????????? ?????? ?????? ??????? ?????? ? ????? ???????. ?????? ??????: ???????????? ??????? ??? ??????????? ?? ??????. ????? ?????????, ?? ?? ??????? ????????, ??????? ?? ?????? ??????? ????? ??????? ? ????? ???. ? ????? ?????? ????? 100 ???????????? ??????????? ???????? ??????? ??????????? ? ????? ???????. ? ??????????? ?? ?????? ??????????? ????????? ??? ??? ???????? ??????? ? ?????? ??? ?? ????? ????????. - interestbook.ru

Reply
info togel2024-06-14 12:02 AM

I got this site from my buddy who told me about this web page and at the moment this time I am browsing this website and reading very informative content here.

Reply
cheap brass organic LPT2024-06-13 8:35 PM

Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing all that over again. Regardless, just wanted to say great blog!

Reply
undress ai2024-06-13 3:39 AM

You ought to be a part of a contest for one of the best websites on the net. I'm going to recommend this website!

Reply
markastoto2024-06-13 2:47 AM

Oh my goodness! Awesome article dude! Many thanks, However I am going through troubles with your RSS. I don't understand the reason why I cannot subscribe to it. Is there anybody else having similar RSS problems? Anyone who knows the answer can you kindly respond? Thanks!!

Reply
GichardantaB2024-06-12 7:41 PM

Attractive section of content. I just stumbled upon your website and in accession capital to assert that I get actually enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently quickly. lastnewsusa.com/2022/02/omicron-variant-pushes-us-coronavirus.html?  regullife.ru/index.php?links_exchange=yes&show_all=yes&page=40?  1abakan.ru/forum/showthread-76051/?  goup.hashnode.dev/garantirovannyj-uspeh-s-nashimi-diplomami?  ediblehomegardensresorts.com/index.php?do=/public/user/blogs/name_Alanpoe/page_7/? 

Reply
deep nude ai2024-06-12 3:59 PM

Hi there! I know this is kinda off topic nevertheless I'd figured I'd ask. Would you be interested in trading links or maybe guest authoring a blog post or vice-versa? My website discusses a lot of the same topics as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to shoot me an email. I look forward to hearing from you! Great blog by the way!

Reply
Crypto Staking2024-06-12 6:49 AM

Hi there i am kavin, its my first time to commenting anywhere, when i read this paragraph i thought i could also make comment due to this sensible paragraph.

Reply
art2024-06-12 2:24 AM

Hello to every one, it's really a fastidious for me to pay a quick visit this website, it contains priceless Information.

Reply
jasa pendirian cv di tangerang2024-06-10 1:13 PM

Nice post. I was checking continuously this blog and I'm inspired! Very helpful information specifically the remaining section : ) I maintain such info a lot. I was seeking this certain information for a very long time. Thank you and best of luck.

Reply
undress ai2024-06-10 4:52 AM

Link exchange is nothing else but it is just placing the other person's blog link on your page at suitable place and other person will also do same for you.

Reply
deep nude ai2024-06-09 8:21 AM

I know this web site offers quality based posts and extra stuff, is there any other site which gives these stuff in quality?

Reply
Yasuko2024-06-09 7:39 AM

Howdy! Do you know if they make any plugins to assist with Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Many thanks! You can read similar article here: Choose your escape room

Reply
deep nude ai2024-06-08 3:19 PM

Somebody essentially help to make significantly articles I might state. That is the very first time I frequented your website page and so far? I amazed with the research you made to make this particular put up incredible. Magnificent activity!

Reply
s Football Necklace2024-04-14 6:19 PM

With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My blog has a lot of unique content I've either created myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement. Do you know any techniques to help stop content from being stolen? I'd really appreciate it.

Reply
ads5082024-02-10 2:36 AM

I've learn several good stuff here. Certainly value bookmarking for revisiting. I wonder how a lot attempt you set to make this sort of magnificent informative site.

Reply
hkg992024-02-10 12:29 AM

Hi, just wanted to say, I loved this article. It was funny. Keep on posting!

Reply
daftar bandotslot2024-02-09 1:01 PM

I do agree with all the ideas you've offered in your post. They are really convincing and can certainly work. Nonetheless, the posts are too short for novices. May you please lengthen them a bit from next time? Thank you for the post.

Reply
Pansy2024-02-09 5:00 AM

I believe that is one of the so much significant info for me. And i am glad studying your article. However should observation on few normal issues, The site taste is wonderful, the articles is in reality great : D. Good job, cheers

Reply
login rejeki8082024-02-09 4:00 AM

When some one searches for his vital thing, so he/she needs to be available that in detail, therefore that thing is maintained over here.

Reply
trending stories2024-02-08 4:52 PM

Howdy just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Internet explorer. I'm not sure if this is a format issue or something to do with web browser compatibility but I thought I'd post to let you know. The style and design look great though! Hope you get the issue fixed soon. Kudos

Reply
lga limousine2024-02-08 4:14 PM

Wonderful post however , I was wondering if you could write a litte more on this subject? I'd be very grateful if you could elaborate a little bit more. Bless you!

Reply
ch?m sóc rùa2024-02-08 3:23 PM

My partner and I stumbled over here from a different web address and thought I might check things out. I like what I see so now i am following you. Look forward to looking over your web page repeatedly.

Reply
SLOTERS882024-02-08 12:23 PM

Asking questions are in fact fastidious thing if you are not understanding anything fully, but this paragraph provides fastidious understanding yet.

Reply
brl cassino script2024-02-08 11:18 AM

Hi, Neat post. There's a problem together with your web site in web explorer, may check this? IE nonetheless is the market leader and a big portion of other people will leave out your fantastic writing because of this problem.

Reply
web page2024-02-07 9:27 PM

Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I'll be subscribing to your feeds and even I achievement you access consistently quickly.

Reply
ads5082024-02-07 7:43 PM

Hello, Neat post. There's a problem together with your web site in web explorer, would check this? IE still is the marketplace chief and a good portion of folks will miss your magnificent writing because of this problem.

Reply
https://ibkr.com.cn2024-02-07 5:29 PM

I get pleasure from, lead to I found exactly what I used to be having a look for. You have ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

Reply
"executive limousine"2024-02-07 2:41 PM

What's up to every body, it's my first visit of this web site; this blog carries awesome and actually excellent stuff designed for readers.

Reply
SLOTPLAZABOLA2024-02-07 2:13 PM

Thanks for finally writing about >[How To] Make a Simple URL Shortener System in PHP <Liked it!

Reply
PASTIPOKER2024-02-07 10:28 AM

Please let me know if you're looking for a article writer for your site. You have some really good articles and I feel I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange for a link back to mine. Please send me an email if interested. Many thanks!

Reply
Bruce Willis2024-02-07 8:06 AM

It's actually a great and useful piece of info. I'm glad that you shared this useful info with us. Please stay us up to date like this. Thank you for sharing.

Reply
slot terpercaya2024-02-07 2:29 AM

Amazing blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Many thanks

Reply
slot gacor2024-02-06 10:11 PM

It's very effortless to find out any topic on net as compared to textbooks, as I found this post at this web site.

Reply
Going Here2024-02-06 4:29 AM

Interesting blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your design. Kudos

Reply
slot gacor2024-02-05 6:50 PM

Please let me know if you're looking for a article author for your blog. You have some really great articles and I believe I would be a good asset. If you ever want to take some of the load off, I'd really like to write some content for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested. Thanks!

Reply
slot2024-02-05 6:27 PM

It is truly a nice and useful piece of information. I'm happy that you just shared this helpful information with us. Please stay us informed like this. Thanks for sharing.

Reply
goldsvet casino2024-02-05 12:23 PM

Remarkable things here. I am very glad to see your post. Thanks so much and I'm looking ahead to contact you. Will you kindly drop me a e-mail?

Reply
betting exchange script2024-02-05 12:08 PM

It's really very complex in this busy life to listen news on Television, thus I just use world wide web for that reason, and take the most up-to-date news.

Reply
jav2024-02-05 7:03 AM

Hello to all, the contents existing at this website are really amazing for people experience, well, keep up the good work fellows.

Reply
joker 812024-02-05 3:40 AM

I get pleasure from, result in I found exactly what I used to be having a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye

Reply
reformas integrales2024-02-05 1:26 AM

It's really a great and useful piece of info. I'm glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

Reply
vintage shirt mens2024-02-03 10:18 AM

I am sure this paragraph has touched all the internet visitors, its really really fastidious paragraph on building up new website.

Reply
depo 25 bonus 252024-02-03 5:58 AM

whoah this blog is wonderful i love studying your articles. Stay up the great work! You know, a lot of individuals are hunting round for this information, you can aid them greatly.

Reply
discuss2024-02-03 5:17 AM

Definitely consider that that you said. Your favorite justification seemed to be at the internet the easiest thing to have in mind of. I say to you, I certainly get annoyed at the same time as other people think about issues that they just don't realize about. You managed to hit the nail upon the top as neatly as defined out the entire thing with no need side-effects , other people can take a signal. Will probably be back to get more. Thank you

Reply
jumper rentals2024-02-02 9:18 PM

I all the time used to study post in news papers but now as I am a user of internet so from now I am using net for articles, thanks to web.

Reply
web page2024-02-02 5:14 PM

Excellent article! We are linking to this particularly great post on our site. Keep up the good writing.

Reply
reformas en zaragoza2024-02-02 12:32 PM

Nice replies in return of this difficulty with firm arguments and describing all concerning that.

Reply
Weed strains Ramona2024-02-02 8:54 AM

If you are going for most excellent contents like myself, just visit this site everyday for the reason that it gives quality contents, thanks

Reply
Sandip Blog2021-03-22 7:35 AM

Nice and Neat Article Awesome content. Keep publishing these articles in future.

Reply
vashikaran Specialist2021-02-06 3:22 AM

Hmm it seems like your site ate my first comment (it was extremely long) so I guess I'll just sum it up what I wrote and say, I'm thoroughly enjoying your blog. I as well am an aspiring blog blogger but I'm still new to everything. Do you have any recommendations for rookie blog writers? I'd definitely appreciate it.

Reply
mumbai escorts2021-01-18 7:29 PM

whoah this blog is excellent i like reading your articles. Stay up the good work! You understand, lots of persons are searching round for this information, you can help them greatly.

Reply
Terence2020-12-20 6:03 PM

Oh my goodness! Awesome article dude! Thank you, However I am encountering troubles with your RSS. I don't understand the reason why I can't subscribe to it. Is there anyone else having identical RSS problems? Anyone who knows the solution can you kindly respond? Thanks!!

Reply
webhelp.nhd.org2020-05-13 7:41 AM

I'm not sure where you're getting your info, but great topic. I needs to spend some time learning more or understandung more. Thanks forr wonderful information I wwas looking for this information for my mission.

Reply
DM2020-05-11 7:49 PM

Awesome issues here. I am very satisfied to see your post. Thnks so much and I am taking a look ahead to touch you. Will you kindly drop me a mail?

Reply
lasertest2019-12-11 7:16 PM

Hello, Neat post. There's an issue along with your site in internet explorer, might check this? IE nonetheless is the market leader and a large component to other people will omit your excellent writing due to this problem.

Reply