Foros del Web » Programando para Internet » PHP »

Problema con acortador de URLs

Estas en el tema de Problema con acortador de URLs en el foro de PHP en Foros del Web. Hola amigos. He decidido montar un nuevo proyecto, el de acortar urls. La url es http://a.crix.us El problema es, que cuando acortas una url, queda ...
  #1 (permalink)  
Antiguo 17/11/2008, 19:37
 
Fecha de Ingreso: noviembre-2008
Mensajes: 3
Antigüedad: 15 años, 5 meses
Puntos: 0
Problema con acortador de URLs

Hola amigos. He decidido montar un nuevo proyecto, el de acortar urls.

La url es http://a.crix.us

El problema es, que cuando acortas una url, queda con dos barritas la url acortada, no sé que será el problema. El Script que uso es lilurl. Aqui les pondré los dos archivos más importantes. La url final funciona perfecto, pero es anormal que tenga dos barritas

Index.php

Cita:
<?php /* index.php ( lilURL implementation ) */

require_once 'includes/conf.php'; // <- site-specific settings
require_once 'includes/lilurl.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">Your lil´ 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´ 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´ 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><?php echo PAGE_TITLE; ?></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><?php echo PAGE_TITLE; ?></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 lil´!" />
</fieldset>

</form>

<h4>Powered by <a href="http://lilurl.sourceforge.net">lilURL</a></h4>

</body>

</html>
Lilurl.php

Cita:
<?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;
}

}

?>
Esos son los dos archivos principales. Ya que ademas de esos estan el config.php y el .htaccess que no creo que sean el problema. Gracias de antemano, son los unicos que me pueden ayudar.
  #2 (permalink)  
Antiguo 18/11/2008, 10:30
Avatar de eft0  
Fecha de Ingreso: junio-2003
Ubicación: Santiago - Chile
Mensajes: 635
Antigüedad: 20 años, 10 meses
Puntos: 9
Respuesta: Problema con acortador de URLs

No entendi muy bien el problema, tienes un ejemplo ?
__________________
eft0's stuff! - http://estebanfernandez.net
  #3 (permalink)  
Antiguo 18/11/2008, 10:38
Avatar de masterojitos  
Fecha de Ingreso: julio-2008
Ubicación: Lima Callao Chucuito
Mensajes: 1.931
Antigüedad: 15 años, 8 meses
Puntos: 105
Respuesta: Problema con acortador de URLs

un favor, no pongas todo tu codigo y mas aun si es inmenso.....
mejor dinos cual es tu error o en que parte del codigo tienes dudas y te ayudamos.

suerte.
__________________
Atte. MasterOjitos :ojotes:
Todo sobre Programación Web
Las ultimas tendencias en Efectos y Recursos Web: MasterOjitos Blog
  #4 (permalink)  
Antiguo 18/11/2008, 11:25
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Problema con acortador de URLs

mm.. por lo que vi te salen URLs así

http://foo.com//b
http://foo.com//cj
http://foo.com//nmk

y según vi tu código, se debe al... dirname($_SERVER['PHP_SELF'])

digo, si sabemos que el PHP_SELF no hay (vaya sin, index...) nos devuelve / y es por eso que se agrega así.. ¿la solución?

analiza esto, y se creativo... no mas

suerte!
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 18/11/2008, 13:22
 
Fecha de Ingreso: noviembre-2008
Mensajes: 3
Antigüedad: 15 años, 5 meses
Puntos: 0
Cita:
analiza esto, y se creativo... no mas
Muchas gracias... Pero queria que me ayudes. :(

Listooo!! Sólo tenia que borrar dirname($_SERVER['PHP_SELF'])

Gracias!

Última edición por GatorV; 18/11/2008 a las 14:07
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:49.