Jump to content


Photo

URL Shortening


  • Please log in to reply
10 replies to this topic

#1 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 22 January 2011 - 10:07 PM

So a friend is making a URL shortening site, well hes already made it and got it working but he wanted me to do some work on it and then he showed me the code and I just felt like shooting myself in the head for offering to help. Its an absolute mess the are tonnes of folders with tonnes of files in each with more folders in them that contain code that could easily be functions. He said he added on top of some other code he got from somewhere.

So I'm thinking of just starting again. Everything that needs to be done I can do except for the URL shrinking. How do I make a redirect without actually creating the file. So say www.clickme.com/randomnumbers but that random numbers isn't a file and just comes up with a page with adverts then a link to continue on.

Posted Image


#2 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 558 posts
  • LocationPennsylvania, United States
  • Age:21

Posted 22 January 2011 - 10:29 PM

You can use a meta with the url being grabbed from pathinfo() or you can use a variable and $_GET ... either way.  pathinfo would be what you would use to use the URL as you've shown above, and $_GET would use something like http://clickme.com/?...tp://google.com

Also, you can just use Base64 to encrypt/decrypt if you want it to not be obvious the site you're going to.

#3 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 22 January 2011 - 11:21 PM

Ok So I browsed around and found this code:
Index:
<?php /* index.php ( lilURL implementation ) */

require_once 'includes/conf.php'; // <- site-specific settings
require_once 'includes/hjurl.php'; // <- lilURL class file

$lilurl = new lilURL();
$msg = '';

// if the form has been submitted
if ( isset($_POST['longurl']) )
{
	// escape bad characters from the user's url
	$longurl = trim(mysql_escape_string($_POST['longurl']));

	// set the protocol to not ok by default
	$protocol_ok = false;
	
	// if there's a list of allowed protocols, 
	// check to make sure that the user's url uses one of them
	if ( count($allowed_protocols) )
	{
		foreach ( $allowed_protocols as $ap )
		{
			if ( strtolower(substr($longurl, 0, strlen($ap))) == strtolower($ap) )
			{
				$protocol_ok = true;
				break;
			}
		}
	}
	else // if there's no protocol list, screw all that
	{
		$protocol_ok = true;
	}
		
	// add the url to the database
	if ( $protocol_ok && $lilurl->add_url($longurl) )
	{
		if ( REWRITE ) // mod_rewrite style link
		{
			$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['PHP_SELF']).'/'.$lilurl->get_id($longurl);
		}
		else // regular GET style link
		{
			$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?id='.$lilurl->get_id($longurl);
		}

		$msg = '<p class="success">URL is: <a href="'.$url.'">'.$url.'</a></p>';
	}
	elseif ( !$protocol_ok )
	{
		$msg = '<p class="error">Invalid protocol!</p>';
	}
	else
	{
		$msg = '<p class="error">Creation of your lil&#180; URL failed for some reason.</p>';
	}
}
else // if the form hasn't been submitted, look for an id to redirect to
{
	if ( isSet($_GET['id']) ) // check GET first
	{
		$id = mysql_escape_string($_GET['id']);
	}
	elseif ( REWRITE ) // check the URI if we're using mod_rewrite
	{
		$explodo = explode('/', $_SERVER['REQUEST_URI']);
		$id = mysql_escape_string($explodo[count($explodo)-1]);
	}
	else // otherwise, just make it empty
	{
		$id = '';
	}
	
	// if the id isn't empty and it's not this file, redirect to it's url
	if ( $id != '' && $id != basename($_SERVER['PHP_SELF']) )
	{
		$location = $lilurl->get_url($id);
		
		if ( $location != -1 )
		{
			header('Location: '.$location);
		}
		else
		{
			$msg = '<p class="error">Sorry, but that lil&#180; URL isn\'t in our database.</p>';
		}
	}
}

// print the form

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

	<head>
		<title>HarryJerry.com Linx Generator</title>
		
		<style type="text/css">
		body {
			font: .8em "Trebuchet MS", Verdana, Arial, Sans-Serif;
			text-align: center;
			color: #333;
			background-color: #fff;
			margin-top: 5em;
		}
		
		h1 {
			font-size: 2em;
			padding: 0;
			margin: 0;
		}

		h4 {
			font-size: 1em;
			font-weight: bold;
		}
		
		form {
			width: 28em;
			background-color: #eee;
			border: 1px solid #ccc;
			margin-left: auto;
			margin-right: auto;
			padding: 1em;
		}

		fieldset {
			border: 0;
			margin: 0;
			padding: 0;
		}
		
		a {
			color: #09c;
			text-decoration: none;
			font-weight: bold;
		}

		a:visited {
			color: #07a;
		}

		a:hover {
			color: #c30;
		}

		.error, .success {
			font-size: 1.2em;
			font-weight: bold;
		}
		
		.error {
			color: #ff0000;
		}
		
		.success {
			color: #000;
		}
		
		</style>

	</head>
	
	<body onload="document.getElementById('longurl').focus()">
		
		<h1>HarryJerry URL Generator</h1>
		
		<?php echo $msg; ?>
		
		<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
		
			<fieldset>
				<label for="longurl">Enter a long URL:</label>
				<input type="text" name="longurl" id="longurl" />
				<input type="submit" name="submit" id="submit" value="Make it sexy!" />
			</fieldset>
		
		</form>

		<h4>Powered by <a href="http://harryjerry.com">HarryJerry.com</a></h4>
	
	</body>

</html>
		
Conf.php
<?php /* conf.php ( config file ) */

// page title
define('PAGE_TITLE', 'lil&#180; URL Generator');

// MySQL connection info
define('MYSQL_USER', 'test');
define('MYSQL_PASS', 'password');
define('MYSQL_DB', 'Clx');
define('MYSQL_HOST', 'localhost');

// MySQL tables
define('URL_TABLE', 'lil_urls');

// use mod_rewrite?
define('REWRITE', true);

// allow urls that begin with these strings
$allowed_protocols = array('http:', 'https:', 'mailto:');

// uncomment the line below to skip the protocol check
// $allowed_procotols = array();

?>
hjurl.php
<?php /* lilurl.php ( lilURL class file ) */

class lilURL
{
	// constructor
	function lilURL()
	{
		// open mysql connection
		mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die('Could not connect to database');
		mysql_select_db(MYSQL_DB) or die('Could not select database');	
	}

	// return the id for a given url (or -1 if the url doesn't exist)
	function get_id($url)
	{
		$q = 'SELECT id FROM '.URL_TABLE.' WHERE (url="'.$url.'")';
		$result = mysql_query($q);

		if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['id'];
		}
		else
		{
			return -1;
		}
	}

	// return the url for a given id (or -1 if the id doesn't exist)
	function get_url($id)
	{
		$q = 'SELECT url FROM '.URL_TABLE.' WHERE (id="'.$id.'")';
		$result = mysql_query($q);

		if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['url'];
		}
		else
		{
			return -1;
		}
	}
	
	// add a url to the database
	function add_url($url)
	{
		// check to see if the url's already in there
		$id = $this->get_id($url);
		
		// if it is, return true
		if ( $id != -1 )
		{
			return true;
		}
		else // otherwise, put it in
		{
			$id = $this->get_next_id($this->get_last_id());
			$q = 'INSERT INTO '.URL_TABLE.' (id, url, date) VALUES ("'.$id.'", "'.$url.'", NOW())';

			return mysql_query($q);
		}
	}

	// return the most recent id (or -1 if no ids exist)
	function get_last_id()
	{	
		$q = 'SELECT id FROM '.URL_TABLE.' ORDER BY date DESC LIMIT 1';
		$result = mysql_query($q);

		if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['id'];
		}
		else
		{
			return -1;
		}
	}	

	// return the next id
	function get_next_id($last_id)
	{ 
	
		// if the last id is -1 (non-existant), start at the begining with 0
		if ( $last_id == -1 )
		{
			$next_id = 0;
		}
		else
		{
			// loop through the id string until we find a character to increment
			for ( $x = 1; $x <= strlen($last_id); $x++ )
			{
				$pos = strlen($last_id) - $x;

				if ( $last_id[$pos] != 'z' )
				{
					$next_id = $this->increment_id($last_id, $pos);
					break; // <- kill the for loop once we've found our char
				}
			}

			// if every character was already at its max value (z),
			// append another character to the string
			if ( !isSet($next_id) )
			{
				$next_id = $this->append_id($last_id);
			}
		}

		// check to see if the $next_id we made already exists, and if it does, 
		// loop the function until we find one that doesn't
		//
		// (this is basically a failsafe to get around the potential dangers of
		//  my kludgey use of a timestamp to pick the most recent id)
		$q = 'SELECT id FROM '.URL_TABLE.' WHERE (id="'.$next_id.'")';
		$result = mysql_query($q);
		
		if ( mysql_num_rows($result) )
		{
			$next_id = $this->get_next_id($next_id);
		}

		return $next_id;
	}

	// make every character in the string 0, and then add an additional 0 to that
	function append_id($id)
	{
		for ( $x = 0; $x < strlen($id); $x++ )
		{
			$id[$x] = 0;
		}

		$id .= 0;

		return $id;
	}

	// increment a character to the next alphanumeric value and return the modified id
	function increment_id($id, $pos)
	{		
		$char = $id[$pos];
		
		// add 1 to numeric values
		if ( is_numeric($char) )
		{
			if ( $char < 9 )
			{
				$new_char = $char + 1;
			}
			else // if we're at 9, it's time to move to the alphabet
			{
				$new_char = 'a';
			}
		}
		else // move it up the alphabet
		{
			$new_char = chr(ord($char) + 1);
		}

		$id[$pos] = $new_char;
		
		// set all characters after the one we're modifying to 0
		if ( $pos != (strlen($id) - 1) )
		{
			for ( $x = ($pos + 1); $x < strlen($id); $x++ )
			{
				$id[$x] = 0;
			}
		}

		return $id;
	}

}

?>

Now this is the important part here:
// if the id isn't empty and it's not this file, redirect to it's url
	if ( $id != '' && $id != basename($_SERVER['PHP_SELF']) )
	{
		$location = $lilurl->get_url($id);
		
		if ( $location != -1 )
		{
			header('Location: '.$location);
		}
		else
		{
			$msg = '<p class="error">Sorry, but that lil&#180; URL isn\'t in our database.</p>';
		}
	}
}
How do I manipulate that to show a page but keep the url the same like www.clickme.com/453456 but with the banner page on it, even though that page doesn't exist?

Posted Image


#4 trq

trq

    Advanced Member

  • Administrators
  • 30,917 posts
  • LocationSydney, Australia.

Posted 22 January 2011 - 11:50 PM

I haven't bothered looking through all that code but the idea is quite simple. Firstly, you need a form which will take a users long url, this part is simple. Once you have this long url, you need to store along side it in the database a unique random string, (again a simple task).

From there all you need is to create a script which excepts the unique string through $_GET and looks that up in the database to find the actual long url. Something like....

<?php
if (isset($_GET['key'])) {
  $key = mysql_real_escape_string($_GET['key']);
  $sql = "SELECT url FROM urls WHERE key = '$key' LIMIT 1";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_assoc($result);
      header ("Location: {$row['url']}");
    } else {
      echo "Sorry, that key does not match any url in our database";
    }
  }
}

You then just create a simple mod_rewrite rule to rewrite the short url to a query string.

RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /redirector.php?url=$1 [L]

This would then allow users to type address such as http://short.com/he8dne to be redirected to whatever address is stored with the key of he8dne.

http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#5 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 23 January 2011 - 12:05 AM

Well this is the thought I had:
if ( $id != '' && $id != basename($_SERVER['PHP_SELF']) )
	{
		$location = $lilurl->get_url($id);
		
		if ( $location != -1 )
		{
			header('Location: '.$location);
		}
		else
		{
			$msg = '<p class="error">Sorry, but that lil&#180; URL isn\'t in our database.</p>';
		}
	}

In that section to add another if inside the current one which uses $_SERVER['REQUEST_URI'] and removes the first 5 letters (the domain and slashes) and the last 4 (extension) which then only leaves the numbers, then run something ( I got a bit lost here) which checks that number against all the records in the number base then if it exists POST the number to the advert page and direct the person there. Then on the advert page check the number against the database and pull the link and apply it to wherever its needed. What can I do for the part that I got lost in, I'm not sure if I'm meant to use an if loop inside a for loop.

Posted Image


#6 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 558 posts
  • LocationPennsylvania, United States
  • Age:21

Posted 23 January 2011 - 02:21 AM

Load page inside the page just use a frame.  Also, that allows you to do the adverts and whatnot you spoke of earlier which can be placed at the top or anywhere you wish.

Sorry if I missed a few things as I haven't read every post & reply.

#7 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 23 January 2011 - 02:29 AM

Ok I got the url shortening working but I have hit a problem that is annoying me.
<?php 
include 'config.php';
$result = mysql_query("SELECT * FROM lil_urls WHERE id=$text") or die(mysql_error());
$result2 = mysql_query("SELECT id FROM adverts") or die(mysql_error());
$link = mysql_fetch_array($result);
$mixed = mysql_fetch_array($result2);
$advert = shuffle($mixed);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
</head>
<body>
<a href="<?php echo $link['url']; ?>" onclick="window.open('<?php echo $advert['1']; ?>')">Banner #1</a>

<?php echo $advert['1']; ?>


</body>
</html>
What I'm trying to do is choose one of the ads at random from the array but it won't work. I really can't figure out why.

Posted Image


#8 trq

trq

    Advanced Member

  • Administrators
  • 30,917 posts
  • LocationSydney, Australia.

Posted 23 January 2011 - 02:33 AM

mysql_fetch_array returns 1 record each time it is called until there are no records left. Instead of....

$mixed = mysql_fetch_array($result2);
$advert = shuffle($mixed);

You would need....

$mixed = array();
while ($row = mysql_fetch_array($result2);
  $mixed[] = $row;
}
$advert = shuffle($mixed);

http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#9 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 23 January 2011 - 02:38 AM

Oh. I thought that it got everything. Now I understand.

Posted Image


#10 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 23 January 2011 - 02:55 AM

Eh that didn't work. I tried a heap of variations but couldn't work it out.
<?php 
include 'config.php';
$result2 = mysql_query("SELECT * FROM adverts") or die(mysql_error());

$mixed = array();
while ($row = mysql_fetch_array($result2)){
  $mixed[] = $row;
}
$advert = shuffle($mixed);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
</head>
<body>

<?php echo $advert['1']; ?>


</body>
</html>

Posted Image


#11 President Obama

President Obama

    Advanced Member

  • Members
  • PipPipPip
  • 55 posts
  • LocationIn your attic watching you though the ceiling lights.

Posted 23 January 2011 - 03:36 AM

Don't worry, got it working. heres the code I used:
<?php 
include 'config.php';
$result2 = mysql_query("SELECT * FROM adverts") or die(mysql_error())

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
</head>
<body>

<?php 
$ads = array();
$A = 0;
while($row = mysql_fetch_array($result2)){
	$ads[] = $row['url'];
}
shuffle($ads);

echo $ads['1'];
 ?>


</body>
</html>

Posted Image





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com