PDA

View Full Version : Some basic questions



golfball123
23 Nov 2010, 01:55 AM
It's been a long time since I made a website and I have forgotten a few things. Unfortunately I have also forgotten the terms used to describe them so Googling has been unproductive.

Firstly, I want to have it so that the 4 sections of my website are located by going to "www.mysite.com/news/" rather than "mysite.com/news.php". Would creating a directory called "news" and putting a separate index.php in there do the trick?


Lastly, I would like my links to have to title as the URL. So rather than "news.php?ID=2434", the URL would be "mysite.com/news/This-is-the-title/". I cannot remember how that's done, any help would be appreciate.

Alan
23 Nov 2010, 04:44 PM
Firstly, I want to have it so that the 4 sections of my website are located by going to "www.mysite.com/news/" rather than "mysite.com/news.php". Would creating a directory called "news" and putting a separate index.php in there do the trick?

Yes, but it would be the wrong way to do it. What you need to do is tell the web server to rewrite the url. If you're using Apache, then the module is mod_rewrite, IIS has this feature too.

The apache syntax would be something like this (using your example):



RewriteEngine on
RewriteRule ^news/$ news.php [L]



Lastly, I would like my links to have to title as the URL. So rather than "news.php?ID=2434", the URL would be "mysite.com/news/This-is-the-title/". I cannot remember how that's done, any help would be appreciate.

The "This-is-the-title" part is called a 'url slug'. You would have to store this somewhere in your database (or translate it from the title on each request (not the greatest of ideas, as your link is directly tied to the title of the page). Anyway, we need to modify the previous apache mod_rewrite commands.



RewriteEngine on
RewriteRule ^news/(.+)$ news.php?title=$1 [L]


So just to clarify. You write links in your pages as the rewritten ones. e.g. <a href="/news/a-sample-title">A Sample Title</a>

So when the new page loads you will have a HTTP GET variable in your $_GET array. You can then use that to lookup the news content in your data store.



<?php
if (isset($_GET['title']) && !empty($_GET['title'])) {
$titleSlug = $_GET['title']; // Still needs to be validated

// Use the $titleSlug to look up a database or whatever.
} else {
// not found page or default page etc.
}


Check out the apache documentation on using mod_rewrite. :)