Results 1 to 10 of 10

Thread: My first php project - URL redirection site

  1. #1
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default My first php project - URL redirection site

    I have been learning PHP for a month and I have created an URL redirection script using which anyone can create a shorturl for a long url (similar to tinyurl). Once they create a tiny url it will be saved into database, and a password will be given to the user for future editing.

    I want to post my entire code here so that I can get your feedbacks and also I can know what could have been done better. I haven't given much importance to security since I have created this script just to teach basic php to myself...

    This contains two major files index.php and edit.php. First one is for the users to create a short url and the second one is to edit a short url that was already created...

    Apart from that there is a directory called 'conf' which has three simple include files, 1)for database connection variable, 2)for database connection code 3)for a simple function to generate random password...

    It also has a css file and apart from that I have a sql dump file to automatically create the simple table for short urls and thier passwords.. I will post those codes one by one in separate posts here.. Pls give your feedback

  2. #2
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    Include files:

    These include files will be placed in a directory called 'conf'

    1)vars.php

    Code:
    <?php
    
    $siteurl = "http://localhost/";
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "mysql";
    $dbname = "redrt"
    
    ?>
    2)dbconnect.php:

    Code:
    <?php
    include('vars.php');
    
    $con = mysql_connect($dbhost,$dbuser,$dbpass);
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      
      
    if(!mysql_select_db($dbname,$con))
     {
     die('Could not connect: ' . mysql_error());
     }
     
    ?>

    3. func.php

    Code:
    <?php
    
    //this function will create a random password
    
    function createRandomPassword() {
    
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    
        srand((double)microtime()*1000000);
    
        $i = 0;
    
        $pass = '' ;
    
        while ($i <= 7) {
    
            $num = rand() % 33;
    
            $tmp = substr($chars, $num, 1);
    
            $pass = $pass . $tmp;
    
            $i++;
    
        }
        return $pass;
    
    
    
    }
    
    ?>

    4)public.css

    Code:
    /* Site Colors:
    	#1A446C - blue grey
    	#689DC1 - light blue
    	#D4E6F4 - very light blue
    	#EEE4B9 - light tan
    	#8D0D19 - burgundy
    */
    
    
    
    html { height: 100%; width: 100%; }
    
    body { width: 100%; height: 100%; margin: 0px; padding: 0px; border: 0px;
    	font-family: Verdana, Arial, Helvetica, sans-serif; background: #D4E6F4;
    	font-size: 13px; line-height: 15px; }
    
    
    
    img { border: none; }
    
    
    table, tr, td { border-collapse: collapse; vertical-align: top; font-size: 13px; line-height: 15px;}
    
    
    
    a { color: #8D0D19;}
    
    
    
    #header { height: 70px; margin: 0px; padding: 0px; text-align: left; 
    	background: #1A446C; color: #D4E6F4; }
    #header h1 { padding: 1em; margin: 0px;}
    
    
    
    #main { margin: 0px; padding: 0px; height: 800px; width: 100%; background: #EEE4B9; }
    
    
    
    #structure { height: 800px; width: 100%; }
    
    
    
    #footer { height: 2em; margin: 0px; padding: 1em; text-align: center; 
    	background: #1A446C;  color: #D4E6F4; }
    
    
    
    
    
    
    
    
    /* Navigation */
    
    
    
    #navigation { width: 150px; padding: 1em 2em; color: #D4E6F4; background: #8D0D19; }
    
    
    #navigation a { color: #D4E6F4; text-decoration: none; }
    
    ul.subjects { padding-left: 0; list-style: none; }
    
    ul.pages { padding-left: 2em; list-style: square; }
    
    
    .selected { font-weight: bold; }
    
    
    
    /* Page Content */
    
    
    #page { padding-left: 2em; vertical-align: top; background: #EEE4B9; }
    
    
    #page h2 { color: #8D0D19; margin-top: 1em;}
    #page h3 { color: #8D0D19; }

  3. #3
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    sql dump file:


    -- phpMyAdmin SQL Dump
    -- version 2.11.9
    -- http://www.phpmyadmin.net
    --
    -- Host: mysql
    -- Generation Time: Apr 01, 2009 at 09:46 AM
    -- Server version: 4.1.14
    -- PHP Version: 4.3.11

    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

    --
    -- Database: `redrt`
    --

    -- --------------------------------------------------------

    --
    -- Table structure for table `redrt`
    --

    CREATE TABLE IF NOT EXISTS `redrt` (
    `id` int(11) NOT NULL auto_increment,
    `surl` varchar(100) NOT NULL default '',
    `lurl` text NOT NULL,
    `pass` varchar(40) NOT NULL default '0',
    KEY `id` (`id`),
    KEY `id_2` (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

    --

  4. #4
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    index.php:

    Code:
    <?php
    require_once("conf/func.php");
    require("conf/dbconnect.php");
    ?>
    
    <html>
    	<head>
    		<title>Free Url redirection<title>
    		<link href="conf/public.css" media="all" rel="stylesheet" type="text/css" />
    	</head>
    	<body>
    		<div id="header">
    			<h1>Free Url redirection</h1>
    		</div>
                    
                    
                    
    		<div id="main">
                        
                        
                        <table id="structure">
    	<tr>
    		<td id="navigation">
                    <a href= "edit.php">Edit short url</a>
                      
                    </td>
                        
    			
    		<td id="page">
                        
                        <h2>Free url redirection</h2>
        
    <p>This site offers a free url redirection service where you can shorten a long url. If you have a long url
    which is difficult to insert in emails or read over the phone, just enter the url here and we will   shorten it for you.  
    </p>
    
     <p><b><i>Note: Make sure that you include http:// or other applicable prefix (eg: https://,ftp://)</i></b></p>
            
    
    <form method = "get" action = "index.php">
        <table>
          
            
    <tr><td><b>Enter the url you want to shorten : </b> <input type ="text" name = "lurl"></td></tr>
    
    <tr><td>      </td></tr>
    
    <tr><td> <b>Save the url as: </b> <input type ="text" name = "surl"></td></tr>
    
    <tr><td><input type = "submit" value = "submit" name = "submit"></td></tr>
    </table>
    </form>
    
    
    
    
    <?php
    
    if( isset($_GET['submit']))
    
    {
        $surl = $_GET['surl'];
        $lurl = $_GET['lurl'];
        $check_avail = mysql_query("SELECT * FROM redrt WHERE surl = '$surl' LIMIT 1");
        
        //test
        // if(!$check_avail){echo mysql_error();}
        
        $check_av2 = mysql_num_rows($check_avail);
        
        //test
        // echo "number of rows: " . $check_av2 ;
        
        if($check_av2 == 1)
          {
            echo "<p <b>Sorry! This Short url is already taken</b></p>";
          }
    
     else
    
    {
     $lurl = $_GET['lurl'];
     $surl = $_GET['surl'];
     $fp = fopen($surl . '.html','w' );
     
    fwrite($fp, ' <meta http-equiv="REFRESH" content="0;url=' .$lurl. '"> ');
    fclose($fp);
    
    $pass = createRandomPassword();
    $update_surl = mysql_query("INSERT INTO redrt(surl,lurl,pass) VALUES ('$surl','$lurl','$pass')");
    
    //test
       if(!$update_surl){echo mysql_error();}
    
     ?>
      Short URL created. your free short url is <a href = "<?php echo $siteurl . "/" . $surl;?>"><?php echo $siteurl . "/" . $surl;?></a><br />
      
      Your password for this short url is "<b><?php echo $pass; ?></b>"<br />
      Make sure you save your password. You will need it if you ever want to edit your short url
    
      
     <?php
     
     
    }}
    
    ?>
    
                        
                        
                    
    		</td>
    	</tr>
    </table>
                   
                        
                        		</div>
                    
                    
                    
         <div id="footer"></div>                
                    
                    
    		
    	</body>
    </html>

  5. #5
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    edit.php:


    Code:
    <?php
    session_start();
    require_once("conf/func.php");
    require("conf/dbconnect.php");
    ?>
    
    <html>
    	<head>
    		<title>Free Url redirection<title>
    		<link href="conf/public.css" media="all" rel="stylesheet" type="text/css" />
    	</head>
    	<body>
    		<div id="header">
    			<h1>Free Url redirection</h1>
    		</div>
                    
                    
                    
    		<div id="main">
                        
                        
                        <table id="structure">
    	<tr>
    		<td id="navigation">
                    <a href="index.php"> Create short url</a>
                      
                    </td>  
                        
    			
    		<td id="page">
                        
           <h2>Edit a short url</h2>
           
           <form action = "edit.php" method="post">
          <table>
            <tr><td>Enter the short url you want to edit: <input type = "text" name = "surl"> </td></tr>
            <tr><td>Enter password for this url: <input type = "password" name = "pass">  </td></tr>
            <tr><td> <input type="submit" value = "edit" name = "edit"> </td></tr>
           </table>
          </form>
          
          <?php
          
          if(isset($_POST['edit']))
          {
            $surl = $_POST['surl'];
            $pass = $_POST['pass'];
                   
            $query = mysql_query("SELECT * FROM redrt WHERE surl = '$surl' AND pass = '$pass' LIMIT 1");
            $check = mysql_num_rows($query);
            
            
               //following line is just for testing,can be removed or commented out
               // if(!$query){echo mysql_error();}else{echo $check . "<br/>";}
               
               
               
               If ($check == 1)          
               
               {
                
                 $_SESSION['surl'] = $surl;
                 $_SESSION['$pass'] = $pass;
                echo "<b>Note: Make sure that you include http:// or other applicable prefix (eg: https://,ftp://)</b> ";
                 while ($result = mysql_fetch_array($query))
                    { $old_lurl = $result['lurl']; }
                    
                      ?>
                      <form action = "edit.php" method = "get" >
                     <table>
                     <tr><td>
                     <textarea rows="1" cols="60" name = "lurl" > <?php echo $old_lurl; ?></textarea>
                     </tr></td>                    
                     <tr><td>
                     <input type = "submit" value = "update" name = "update">
                     </tr></td>
                     </table>
                     </form>
                     <?php
                     
                     
                   
               
               
               }
               else
               
               {echo "<b>Wrong password or wrong Short-url!</b>"; }
               
               
               }
               
               
                 if(isset($_GET['update']) AND isset($_SESSION['surl']))
                     {
                       //update edited info in database and edit the redirect page 
                        $surl = $_SESSION['surl'] ;
                        $pass = $_SESSION['$pass'];
                        $lurl = $_GET['lurl'];
                        
                       $fp = fopen($surl . '.html','w' ); 
                       fwrite($fp, ' <meta http-equiv="REFRESH" content="0;url=' .$lurl. '"> ');
                       fclose($fp);
                       $update_surl = mysql_query("UPDATE redrt SET lurl = '$lurl' WHERE surl = '$surl' AND pass = '$pass' ");
                       if($update_surl)
                       {echo "<br/><b>Short url successfully updated</b>" ;
                       $_SESSION = array();
                       session_destroy();
                       }
                       else
                       {echo mysql_error();
                        $_SESSION = array();
                       session_destroy();
                       }
                       
                        
                        
                     }
               
               ?>
                        
                        
                    
    		</td>
    	</tr>
    </table>
                   
                        
                        		</div>
                    
                    
                    
         <div id="footer">Copyright 2009, Solveithere.com</div>                
                    
                    
    		
    	</body>
    </html>


    I have submitted all the code here. I don't think that this is the best way to create a url redirection script because in this case, each time a short url is created, a new file will also be created. Pls let me know your suggestions and comments

  6. #6
    Join Date
    Mar 2009
    Posts
    65
    Thanks
    13
    Thanked 4 Times in 4 Posts

    Default

    There are two ways to remove the need to create the htm

    The first way is to basically instead of having a file, simply store a query string, maybe like this http://myredirect.com/redirect?id=shorten_url

    That sort of defeat the purpose (it is not very readable for one). The second way is to use mod rewrite rules such that you can assign change http://myredirect.com/redirect?id=shortern_url into http://myredirect.com/redirect/shorten_url or even just http://myredirect.com/shorten_url

    It is kind of complex though (I don't use it myself, personally), but if you want to find out how to do this, try googling for mod rewrite rules (there are ways to do this without messing with the server settings, I think. I suppose I came across it in google)

  7. #7
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    I googled for mod rewrite rules, and I got a manual of long page in apache website..

    The introduction is scary:
    The Apache module mod_rewrite is a killer one, i.e. it is a really sophisticated module which provides a powerful way to do URL manipulations. With it you can do nearly all types of URL manipulations you ever dreamed about. The price you have to pay is to accept complexity, because mod_rewrite's major drawback is that it is not easy to understand and use for the beginner. And even Apache experts sometimes discover new aspects where mod_rewrite can help.

    In other words: With mod_rewrite you either shoot yourself in the foot the first time and never use it again or love it for the rest of your life because of its power.
    Now, does it have to do anything with .htaccess file? Because I use Yahoo Webhosting and it doesn't support .htaccess files. There is no note on whether it is windows or linux hosting and which web server is used anyway....

    I am wondering what methods are used in popular redirect service websites... Is there any other way which would replace the creation of html files?

    I really don't want to use something like http://myredirect.com/redirect?id=shorten_url since it is not very friendly.

  8. #8
    Join Date
    Mar 2009
    Posts
    65
    Thanks
    13
    Thanked 4 Times in 4 Posts

    Default

    I hope this article on mod rewrite without .htaccess will help. Try googling "mod rewrite without htaccess" and you may turn up something.

    Good luck!

    Edit: Here's another one.
    Last edited by CrazyChop; 04-07-2009 at 12:23 PM.

  9. #9
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    Hi Crazychop,

    Thank you very much for those two links, I just had a short look and I will read it in detail tomorrow. Now, it is Tuesday evening in my place and I will go through the pages tomorrow in the day time.

  10. #10
    Join Date
    Mar 2009
    Location
    Chennai, India
    Posts
    77
    Thanks
    16
    Thanked 7 Times in 6 Posts

    Default

    I looked up much on Google and also read the two links you gave me... It seems that .htaccess file is necessary.. I can also use a 404 not found page to process the $_GET variables and redirect users accordingly, but still it is necessary to configure the server accordingly... Anyway, it seems that if I rewrite the script using mod rewrite I can make it to work with any hosting provider where .htaccess is supported

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •