Page 1 of 1

Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 12:25 pm
by wee493
I'm making a tiny URl site and I want to have it auto generate a number (maybe even letters) at the end of the url automatically. this script is a one file index.php tiny url script. I would like to see if there is an easy way to have it generate random numbers/letters at the end of the url. It would be nice if they where consecutive.

Code: Select all

<html>
<head>
<Title>Wiurl - Make any url a wi one</title>
<style type="text/css">
<!--
.style1 {font-size: medium}
.style2 {font-size: large}
-->
</style>
</head>
<body>
<table width="315" border="0" align="center">
  <tr>
    <td width="582">&nbsp;
<?php
$domain = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$url = "http://" . $domain . $path . "?" . $queryString;
$url2 = "http://" . $domain . $_SERVER['REQUEST_URI'];
?>
 
<h2><span class="style2">Please enter a URL Below</span></h2>
<form  method="post">
Your Long URL: <input name="oldurl" type="text" value="http://" size="25">
<br>
New wi URL: wiurl.com/l/
<input type="text" name="newurl"><br>
<input type="submit" name="submit" value="Shorten">
</form>
<?php
 
srand ((double) microtime( )*1000000);
$random_number = rand(0,150);
 
if ($_POST['submit']) {
 
$newurl = $_POST['newurl'];
$oldurl = $_POST['oldurl'];
$title= $_POST['title'];
$urlcloking= $_POST['urlcloking'];
$redirect = "<html><head><title>$title</title></head><body>
<iframe src='$oldurl' height='100%'  width='100%' frameborder='0'>
</body></html>";
 
if(file_exists("l/$newurl/")) die("Sorry, there is already a URL with that name.");
 
mkdir("l/$newurl");
 
if ($urlcloking=="yes") {
 
$filename = "l/$newurl/index";
$filename .= ".php";
$Content = "<html><head><title>$title</title></head><body>
$redirect
</body></html>";
$handle = fopen($filename, 'x+');
fwrite($handle, $Content);
fclose($handle);
?>Yourr new URL is <a href=http://wiurl.com/l/<?php echo "$newurl"; ?>>http://wiurl.com/l/<?php echo"$newurl"; ?></a> 
 
<?php
 
die();
}
 
$filename = "l/$newurl/index";
$filename .= ".php";
$Content = "<META http-equiv='refresh' content='0;URL=$oldurl'>";
$handle = fopen($filename, 'x+');
fwrite($handle, $Content);
fclose($handle);
?>
<br>
<h2 class="style1">Success!</h2>
Your new URL is <a href=http://wiurl.com/l/<?php echo "$newurl"; ?>>http://wiurl.com/l/<?php echo"$newurl"; ?></a>
<?php
}
//THIS MUST STAY INTACT!
echo $copyright;  
 
?></td>
  </tr>
</table>
<div align="center"></div>
<div align="center"></div>
 

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 12:37 pm
by andyhoneycutt
I can't tell for sure what you're trying to accomplish, but I think it's one of two different things:
1 - You want to generate a URL, a number, and append a letter to it based on what other letters have already been used by your script, e.g. 1891941A, 1923801B, 12418157C, etc.
Or do you mean: 2 - 1923914ABC, 18491419ABC ...

-Andy

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 12:42 pm
by wee493
andyhoneycutt wrote:I can't tell for sure what you're trying to accomplish, but I think it's one of two different things:
1 - You want to generate a URL, a number, and append a letter to it based on what other letters have already been used by your script, e.g. 1891941A, 1923801B, 12418157C, etc.
Or do you mean: 2 - 1923914ABC, 18491419ABC ...

-Andy
I would like something like 123456a, 123457a, 123456b, 123458a

If that is possible, or something like what youtube does. If that is not easily done then just random numbers like ( 6542 , 98654 , 32165) would be fine.
I really dont care too much what is does, I just dont want it repeating the addresses

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 12:49 pm
by jayshields
Since you want it as small as you can, you should probably use every character that is allowed in a query string. Without looking I don't know what they all are, but they are atleast all the (English) alphanumeric characters. You probably won't want a random string either, because you want to start off with query strings of as small as possible (1 character) and eventually have to go longer when you're indexing more URLs.

It's pretty trivial to do something like this if you're using a database, which I guess you are. If (like I suggested) you are going to use all the characters possible, then you'll probably be able to find a snippet somewhere with every one of these characters hardcoded into an array for you to iterate over, or make your own function.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 1:05 pm
by wee493
jayshields wrote:Since you want it as small as you can, you should probably use every character that is allowed in a query string. Without looking I don't know what they all are, but they are atleast all the (English) alphanumeric characters. You probably won't want a random string either, because you want to start off with query strings of as small as possible (1 character) and eventually have to go longer when you're indexing more URLs.

It's pretty trivial to do something like this if you're using a database, which I guess you are. If (like I suggested) you are going to use all the characters possible, then you'll probably be able to find a snippet somewhere with every one of these characters hardcoded into an array for you to iterate over, or make your own function.
I'm not using a database. What the script does is creates a directory with an index file in it. the index file redirects to the url.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 1:51 pm
by panic!
you should, definitely, definitely use a database for this. Unless you're planning on having less than a few hundred URLs.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 1:56 pm
by wee493
panic! wrote:you should, definitely, definitely use a database for this. Unless you're planning on having less than a few hundred URLs.
do you know of any good free url shrinkers that use a database?

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 2:02 pm
by panic!
All of them I'd imagine.

or do you mean a script you can download?

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 2:51 pm
by s.dot
Why do you request it be consecutive? For such a purpose, it seems randomness would be the key. :P

Code: Select all

<?php
 
function genRandString($strlen)
{
    $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9), array('-', '_'));
    shuffle($chars);
 
    $str = '';
    for ($i = 0; $i < $strlen; $i++)
    {
        $str .= $chars[mt_rand(0, count($chars))];
    }
 
    //check here to see if $str has been used before
    //if ($str_has_been_used_before)
    //{
    //    //get a new string
    //    genRandString(8);
    //}
 
    return $str;
}
 
echo genRandString(8);
echo '<br />';
echo genRandString(12);
echo '<br />';
echo genRandString(4);
Produces this:

Code: Select all

xvIfOWpS
brKqci-mDJhq
R6Tc
If you're adament about not using a database, store all the random strings you've used in a flat file and then check against that to see if it has been used before.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 3:46 pm
by panic!
Agreed with Scottay.

Code: Select all

<?
/*    make this database
CREATE TABLE urls (
         id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        url varchar(16), realurl varchar(512)
       );
*/
 
     $address = "localhost";    // the address at which your database resides, eg localhost
     $database = "urls";    // the database name
     $user = "root";        // the user name for the database
     $password = "root";     // the password
    
    
    mysql_connect($address,$user,$password);
    
    mysql_select_db($database); 
    
 
    
    if($_POST['realurl'])
    {
    
            
            $uri='123';
            
            $uri=random_generator(rand(3,6));
            
            while(mysql_num_rows(mysql_query("select realurl from urls where url='$uri' limit 1"))==1)
            {
                $uri=random_generator(rand(3,6));
            
            }
            
            mysql_query("insert into urls (url,realurl) values ('".$uri."','".$_POST['realurl']."')");
            print mysql_error();
            ?>
            <a href="/<?=$uri;?>"><?=$uri;?></a>
            <?
            die();
    }
    
    
    if($_SERVER['REQUEST_URI']!='/')
    {
        $uri=str_replace('/','',$_SERVER['REQUEST_URI']);
        
        $uriRs=mysql_query("select realurl from urls where url='$uri'");
        
        $url=mysql_fetch_row($uriRs);
        
        header('location: '.$url[0]);
        
        die();
        
    }
    
        // i copied and pasted this from http://www.plus2net.com/php_tutorial/random-string.php
        
        function random_generator($digits){
        srand ((double) microtime() * 10000000);
        //Array of alphabets
        $input = array ("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q",
        "R","S","T","U","V","W","X","Y","Z");
        
        $random_generator="";// Initialize the string to store random numbers
        for($i=1;$i<$digits+1;$i++){ // Loop the number of times of required digits
        
        if(rand(1,2) == 1){// to decide the digit should be numeric or alphabet
        // Add one random alphabet
        $rand_index = array_rand($input);
        $random_generator .=$input[$rand_index]; // One char is added
        
        }else{
        
        // Add one numeric digit between 1 and 10
        $random_generator .=rand(1,10); // one number is added
        } // end of if else
        
        } // end of for loop
        
        return $random_generator;
        } // end of function
    
    
    
    
    
    
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html>
    <head>
        <title>hehe</title>
    </head>
    <body>
    <form action="/" method="POST">
        <input type="text" name="realurl"/><input type="submit" value="do it!">
    </form>
    </body>
</html>
 
 
 
 


put this in your .htaccess file

Code: Select all

 
 
RewriteEngine On
 
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
 
RewriteRule ^(.+)$ index.php [L]
RewriteRule ^()$ index.php [L]
 
options -indexes
 


there you go, that should work as a starting point.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 4:32 pm
by marcth
Couldn't you store the URIs in a database table that has a primary key? At minimum something like:

ID integer
URI varchar

Then, when one submits a URI you can insert it into the database and refer to it via its primary key and produce URI's like index.php?id=1. You could also convert the primary keys into HEX so that index.php?id=255 could be presented as index.php?id=FF.

Re: Create consecutive numbers - tiny URl

Posted: Sun Sep 07, 2008 4:52 pm
by andyhoneycutt
searching the filesystem for unique identifiers for directories would become a nightmare after a few thousand entries. not to mention the fact of total unportability. i would recommend at least, as others have said, using a flat-file, if not a full fledged database for this task.