简体   繁体   中英

PHP , htaccess: apply page title in URL

I want to apply the page HTML title in the URL

for example in here (stackoverflow) the url is something like that:

http://stackoverflow.com/questions/10000000/get-the-title-of-a-page-url

you can see the "get-the-title-of-a-page-url" part which is the page title

what i mean is when the user go to spowpost.php?post=1

the actual url that shows up when the pages load will be spowpost.php?post=1$title=..the_title..

how can i do that?

EDIT: i was thinking about htaccess , but i don't know this very well so tutorial would help for this CERTAIN case..

You can use .htaccess for this. For example:

RewriteEngine On
RewriteRule ^questions/(\d+)/([a-z-]+) index.php?id=$1&title=$2 [L]

Your PHP page (index.php) receives the id and title as parameters in $_GET[] :

echo $_GET['title'];
// get-the-title-of-a-page-url

You can then use that (or the id, which is easier) to retrieve the correct item from your data source:

// Assuming you didn't store the - in the database, replace them with spaces
$real_title = str_replace("-", " ", $_GET['title']);
$real_title = mysql_real_escape_string($real_title);

// Query it with something like
SELECT * FROM tbl WHERE LOWER(title) = '$real_title';

Assuming you do have an id parameter in the URL of some sort, it's easier to query based on that value. The title portion can be used really only to make a readable URL, without needing to act on it in PHP.

In reverse, to convert the title to the format-like-this-to-use-in-urls , do:

$url_title = strtolower(str_replace(' ', '-', $original_title));

The above assumes your titles don't include any characters that are illegal in a URL...

$article_link = "http://example.com/spowpost.php?post=$postid&$title=$url_title";

Or to feed to .htaccess:

$article_link = "http://example.com/spowpost$postid/$url_title";

From what I understand, your title will be passed to the page as part of the URL. To show it in the title bar, put this in the section:

<?php $title=urldecode($_GET["title"]); echo "<title>$title</title>"; ?>

You might need to change parts of this, for instance dashes to spaces or something. If that is the case, use PHP's str_replace function: http://php.net/str_replace

Not sure about what's the problem you are facing but just according to what you say in your post the anwser would be:

1.You take the ID from the URL.
2.You search in your database for the original title
3. And then display it in the tag in the of your HTML.

Clarify if you have problem with any of the previous points.

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