简体   繁体   中英

How to use Friendly URLs?

I've been working on a little piece of php script that took me several days (I'm a noob)

Here's my code :

<?php
require ('connect.php');

$requete = mysql_query('SELECT * FROM videos WHERE id="'.$_GET['id'].'"') or die(mysql_error());

if(mysql_num_rows($requete)=='0'){
}else{
    while($resultats = mysql_fetch_array($requete)){ 
?> <!-- some html content --> <?php
    }
}

mysql_close(); 
?>
</body>
</html>

This script retrieves the content from my database, according to the ID.

http: //localhost/mysite/video/atest.php?id=1

I'd like to know which kind of url rewriting i'd have to use in order to retrieve some keywords. I'd like to have that kind of URL:

http: //localhost/mysite/video/1-first-video-title

RewriteEngine On

RewriteCond %{REQUEST_URI} !\.(css|png|jpe?g|gif|js|mp3|3gp|ico)$
RewriteRule atest/([a-zA-Z0-9\-]+)-([0-9]+) atest.php?id=$1&url=$2[L,QSA]

Went something wrong?

I'd also like to use that, but I get nothing shown on the screen (this page cannot be found).

if($resultats["url"]!=$_GET["url"]) {
  header ("location:/mysite/video/".$resultats["url"]."-".$resultats["id"]);
}

It searches in my table where it finds the URL keywords.

Thank you!

I think your problem here may actually be very simple: the RewriteRule is capturing variables the wrong way round RewriteRule atest/([a-zA-Z0-9\\-]+)-([0-9]+) atest.php?id=$1&url=$2[L,QSA] will match "atest/example-42" and map it to "atest.php?id=example&url=42" - $1 referring to the first set of brackets, and $2 to the second. Try a print_r() or var_export() of $_GET

Incidentally, that regex may go wrong in some edge cases, because it doesn't assert that the ID has to come at the very end - so "atest/example-2-word-42" could end up picking out the ID as 2, not 42. Adding a "$" should fix that: RewriteRule atest/([a-zA-Z0-9\\-]+)-([0-9]+)$ atest.php?id=$1&url=$2 [L,QSA]

If the rewrite rule just isn't working at all (your question isn't clear what the result is) it could be some subtlety in Apache's .htaccess handling...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM