I'm trying to do a rewrite of /example-friendly-url
to display the content of /posts.php?id=1
.
Both the friendly url value and the id are stored in a mysql table.
Here's what I've written so far but something's not right:
posts.php:
include('/functions.php');
$post = getPost($_GET['id']);
$param = getSlug($_GET['param']);
functions.php:
function getPost($id) {
$id = (int) $id;
$query = mysql_query("SELECT * FROM list WHERE id = '$id'") or die(mysql_error());
return mysql_fetch_assoc($query);
}
function getSlug($param) {
$query = mysql_query("SELECT id FROM list WHERE slug = '$param'") or die(mysql_error());
return mysql_fetch_assoc($query);
}
.htaccess:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/posts.php
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]
Any help would be much appreciated.
The leading slash is removed when mod_rewrite rules are processed in an htaccess file, so you don't want the ^/
in front of the regex:
RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]
You are passing a "slug" as _GET['param']
. There's no "id". What you need to do in your posts.php
is turn that slug into an ID:
include('/functions.php');
$post_id = getSlug($_GET['param']);
$post = getPost($post_id);
Of course, making sure that $_GET['param']
is sanitized, using something like mysql_real_escape_string (deprecated, you really want to be using mysqli ).
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.