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 (104) Add New Comment
rumahidr2024-02-23 9:39 AM

Amazing! This blog looks exactly like my old one! It's on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

Reply
rumahidr2024-02-23 8:29 AM

Wow, that's what I was looking for, what a stuff! present here at this website, thanks admin of this web page.

Reply
Hermelinda2024-02-23 6:14 AM

Nicely put. Kudos!

Reply
Army Green2024-02-23 5:31 AM

What's up, always i used to check web site posts here early in the daylight, for the reason that i enjoy to gain knowledge of more and more.

Reply
bokep indo2024-02-22 8:37 PM

This information is priceless. Where can I find out more?

Reply
kontol2024-02-22 8:11 PM

Wow, fantastic blog layout! How long have you been blogging for? you make running a blog look easy. The full glance of your site is excellent, let alone the content!

Reply
ladangtoto2024-02-22 7:57 PM

I think the admin of this web site is really working hard in support of his website, for the reason that here every data is quality based information.

Reply
Buyproxies2024-02-22 7:35 PM

This piece of writing will assist the internet visitors for building up new web site or even a weblog from start to end.

Reply
sklep online2024-02-22 5:08 PM

Wow, amazing weblog format! How long have you ever been blogging for? you made blogging look easy. The entire look of your site is magnificent, as well as the content material! You can see similar: sklep online and here sklep internetowy

Reply
Romeo2024-02-22 3:47 PM

I have read so many articles or reviews about the blogger lovers except this paragraph is genuinely a fastidious piece of writing, keep it up.

Reply
download2024-02-22 7:39 AM

Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

Reply

Every weekend i used to visit this website, because i want enjoyment, since this this web page conations in fact good funny information too.

Reply
jackpot betting2024-02-21 10:15 PM

It's hard to come by well-informed people for this topic, however, you sound like you know what you're talking about! Thanks

Reply
1xbet giri?2024-02-21 9:15 PM

What's up, I log on to your new stuff regularly. Your story-telling style is awesome, keep it up!

Reply
Dominic2024-02-21 8:49 PM

Excellent post however I was wondering if you could write a litte more on this topic? I'd be very thankful if you could elaborate a little bit more. Appreciate it!

Reply
trending stories2024-02-21 4:19 PM

Hi i am kavin, its my first occasion to commenting anyplace, when i read this piece of writing i thought i could also make comment due to this sensible piece of writing.

Reply
slot gacor2024-02-21 12:22 PM

Howdy! I know this is kinda off topic however , I'd figured I'd ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My website covers a lot of the same topics as yours and I believe we could greatly benefit from each other. If you might be interested feel free to send me an e-mail. I look forward to hearing from you! Awesome blog by the way!

Reply
Kassie2024-02-21 9:08 AM

You have made your point.

Reply
???????? ????????2024-02-21 8:42 AM

Excellent post. I was checking continuously this blog and I'm impressed! Very useful info specially the last part :) I care for such information a lot. I was seeking this certain information for a very long time. Thank you and best of luck.

Reply
cooking advice2024-02-21 6:34 AM

Spot on with this write-up, I seriously feel this website needs far more attention. I'll probably be returning to read more, thanks for the information!

Reply
Alex Fox2024-02-20 6:02 PM

It's a shame you don't have a donate button! I'd definitely donate to this outstanding blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this site with my Facebook group. Talk soon!

Reply
akun pro slot gacor2024-02-20 11:50 AM

Yes! Finally someone writes about ceria123.

Reply
Link alternatif bunda jitu2024-02-20 10:26 AM

Hi there it's me, I am also visiting this website regularly, this web page is truly fastidious and the visitors are really sharing fastidious thoughts. Link alternatif bunda jitu

Reply
scam2024-02-19 9:31 PM

When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Bless you!

Reply
????????? ???? ???? ??????2024-02-19 8:06 PM

This text is worth everyone's attention. Where can I find out more?

Reply
Robopragma2024-02-19 2:44 PM

You are so cool! I don't suppose I've truly read a single thing like this before. So great to discover somebody with unique thoughts on this issue. Seriously.. thank you for starting this up. This site is one thing that is required on the internet, someone with a little originality!

Reply
LINK LGO4D2024-02-19 1:49 AM

Sweet blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I've been trying for a while but I never seem to get there! Cheers

Reply
Juliann2024-02-18 4:08 AM

whoah this blog is great i really like studying your posts. Keep up the good work! You recognize, a lot of individuals are searching round for this information, you could aid them greatly.

Reply
Winifred2024-02-18 4:08 AM

Hello, i think that i saw you visited my web site thus i came to “return the favor”.I'm trying to find things to improve my web site!I suppose its ok to use a few of your ideas!!

Reply
news2024-02-16 4:54 PM

Pretty! This was an extremely wonderful article. Many thanks for providing this info.

Reply
SLOT ONLINE2024-02-16 7:51 AM

Do you have any video of that? I'd love to find out more details.

Reply
bokep2024-02-16 6:59 AM

Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My website is in the exact same niche as yours and my visitors would truly benefit from some of the information you provide here. Please let me know if this alright with you. Thank you!

Reply
bokep2024-02-16 6:58 AM

Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My website is in the exact same niche as yours and my visitors would truly benefit from some of the information you provide here. Please let me know if this alright with you. Thank you!

Reply
trang ch?2024-02-16 4:56 AM

What's up to every body, it's my first pay a visit of this webpage; this website consists of remarkable and really excellent data in support of visitors.

Reply
slot terpercaya2024-02-15 11:02 PM

Why users still make use of to read news papers when in this technological world all is presented on web?

Reply
??2024-02-15 8:12 PM

I visited various web sites however the audio feature for audio songs existing at this site is in fact wonderful.

Reply
ROYAL 1682024-02-15 7:06 PM

I was able to find good advice from your blog posts.

Reply
2 Dads Bounce Houses2024-02-15 5:09 PM

I'm amazed, I have to admit. Seldom do I come across a blog that's both equally educative and engaging, and without a doubt, you've hit the nail on the head. The problem is something not enough people are speaking intelligently about. I'm very happy I stumbled across this in my hunt for something concerning this.

Reply
situs slot2024-02-15 4:47 PM

Yes! Finally something about slot.

Reply
slot gacor2024-02-15 4:06 PM

Dengan banyak bonus didapatkan berasal dari Galaxy138 pastinya amat menguntungkan kamu dan termasuk sanggup mengimbuhkan sensasi lebih didalam bermain slot gacor belum ulang jackpot besar menanti.

Reply
RTP GACOR MALAM INI2024-02-15 3:06 PM

Wonderful web site. Lots of useful information here. I am sending it to a few pals ans also sharing in delicious. And certainly, thanks on your effort!

Reply
www.bookpikks.com2024-02-15 10:16 AM

Thanks for sharing your thoughts on url shortener system. Regards

Reply
Svá?ení2024-02-15 9:33 AM

This text is worth everyone's attention. Where can I find out more?

Reply
Rupatadine2024-02-15 3:00 AM

Right here is the perfect webpage for everyone who hopes to find out about this topic. You understand so much its almost tough to argue with you (not that I personally will need to…HaHa). You definitely put a fresh spin on a subject that has been discussed for many years. Great stuff, just wonderful!

Reply
slot gacor2024-02-14 10:02 PM

It's an amazing paragraph in support of all the online visitors; they will take advantage from it I am sure.

Reply
depo 10k2024-02-14 6:19 PM

It's in fact very difficult in this busy life to listen news on Television, therefore I just use the web for that reason, and get the most up-to-date information.

Reply
Alternative Lending2024-02-14 1:52 PM

I really like it when people come together and share thoughts. Great website, continue the good work!

Reply
Situs Togel Terpercaya2024-02-14 12:56 AM

Daftar Toto

Reply
e-visa to japan2024-02-13 11:26 PM

My partner and I stumbled over here from a different web address and thought I should check things out. I like what I see so now i'm following you. Look forward to exploring your web page again.

Reply
spa pool2024-02-13 6:08 PM

Pretty nice post. I just stumbled upon your weblog and wanted to say that I have truly enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again soon!

Reply
slot online2024-02-13 1:15 PM

hello!,I really like your writing very a lot! proportion we communicate more about your post on AOL? I need a specialist in this space to resolve my problem. May be that's you! Looking ahead to see you.

Reply
going gluten free2024-02-13 9:50 AM

Simply desire to say your article is as astonishing. The clarity for your post is simply excellent and that i can suppose you are a professional on this subject. Fine with your permission let me to take hold of your RSS feed to stay up to date with forthcoming post. Thank you 1,000,000 and please carry on the rewarding work.

Reply
ads5082024-02-13 9:34 AM

Hi there, You've done a great job. I'll certainly digg it and personally suggest to my friends. I'm confident they'll be benefited from this site.

Reply
MAX88 LOGIN2024-02-13 3:09 AM

Hi everyone, it's my first pay a visit at this web site, and article is really fruitful in support of me, keep up posting these articles or reviews.

Reply
??? ???2024-02-13 2:59 AM

Thanks in favor of sharing such a good thought, paragraph is pleasant, thats why i have read it completely

Reply
?????2024-02-13 2:40 AM

Hi! Do you know if they make any plugins to assist with SEO? 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. Cheers!

Reply
Reginald2024-02-12 5:14 PM

What's up, yes this paragraph is in fact pleasant and I have learned lot of things from it about blogging. thanks.

Reply
trending stories2024-02-12 4:22 AM

Good day! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I'm getting tired of Wordpress because I've had problems with hackers and I'm looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

Reply
hiburan1382024-02-11 10:05 AM

It's really very complicated in this full of activity life to listen news on Television, therefore I simply use the web for that reason, and obtain the most recent information.

Reply
trending stories2024-02-10 10:10 AM

Greetings I am so delighted I found your webpage, I really found you by accident, while I was searching on Digg for something else, Regardless I am here now and would just like to say kudos for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don't have time to read through it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the fantastic job.

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

This article presents clear idea for the new people of blogging, that actually how to do blogging.

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
crash casino script2024-02-05 12:54 PM

Pretty part of content. I just stumbled upon your website and in accession capital to say that I acquire actually enjoyed account your weblog posts. Anyway I will be subscribing for your augment or even I success you get right of entry to persistently quickly.

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
situs slot2024-02-02 8:52 AM

I am no longer sure where you are getting your info, but great topic. I needs to spend some time studying more or working out more. Thanks for fantastic information I was in search of this info for my mission.

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