Search code examples
phpurlpermalinks

Challenge "Pretty Links"


I have a website with URLs in this format:

http://example.com/teste/link/produto/evento.php?evento=1234&origem=site

What I wish to do is if the user enter this:

http://example.com/SuperEvento2013

and showed the content of

http://example.com/teste/link/produto/evento.php?evento=1234&origem=site.

So, I made a rule on .htaccess and I created a transform.php where I receive the parameter event:

$event = $_REQUEST['event'];

$select_evento = mysql_query("SELECT * FROM evento WHERE alias = '$event'") or die(mysql_error());
$evento = mysql_fetch_array($select_evento);
$count_evento = mysql_num_rows($select_evento);
echo $event;
if ($count_evento > 0) {
    header("Location:/teste/link/produto/evento.php?evento=".$evento['id']);
} else {
    echo "Ops, o evento que tentou acessar não existe. Verifique o endereço digitado."; 
} 

My .htaccess looks like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*transform.php?event=$1 [L]

Where it calls the transform.php where he execute the header(location).

The questions is: How do I make my link keeping with the URL friendly without typing the parameters in front of the URL, without showing to the user this uglies URLs?


Solution

  • You do not need to use a "transform.php" page.

    Instead make your rewrite be RewriteRule .*/teste/link/produto/evento.php?event=$1 [L]

    In your "evento" page, use the code you had in your transform to egt the event ID. Then use this ID to display whatever you need:

    $event = $_REQUEST['event'];
    
    $select_evento = mysql_query("SELECT * FROM evento WHERE alias = '$event'") or die(mysql_error());
    $evento = mysql_fetch_array($select_evento);
    $count_evento = mysql_num_rows($select_evento);
    $event_id = $evento['id'];
    

    The basic idea is, don't redirect the user. Simply use the ID in the final PHP page.

    On a side note, please consider using PDO for your MySQL queries. (lookup "mysql injection").

    http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers