How would one go about creating a uri based on the information in the database. I know how I can post to a dynamic php page and have it search the database then use htaccess to rewrite that url. But how do I get php to generate a page based on a URI Link clicked lets say in a menu For example: The database will have a Unique title which will be the unique uri of the portion of the URL, Essentially the title is representative of the link uri in the "a href" link in a menu. So if somesite.com/ loads the main page, but if users clicks the link somesite.com/a-dynamic-page/ which would be a dynamically generated page. How do I get the server instead of throwing a 404 error because the page does not exist, have php look through the database and load the data from the database and then generate the page based on what was found in the database for "a-dynamic-page"<--unique uri in database? Let me know if you need any clarity on this question.
You probably want to first tell .htaccess to process all missing pages with some php script you've written, by putting this inside your .htaccess file:
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my_processor.php [L]
</IfModule>
... which would effectively tell apache that all requests to pages that don't exist, should be redirected to a script called my_processor.php, directly on your website's document root.
Once inside the my_processor.php script, you can look at and parse $_SERVER['REQUEST_URI'], and use that to determine what your script should do next. ie:
[my_processor.php]
<?php
//
#$uri=$_SERVER['REQUEST_URI'];
switch($uri)
{
default: die("Error");
case "/some-path-1/":
SomeFunction1();
break;
case "/some-path-2/":
SomeFunction(2);
break;
}
?>
Please forgive how simple the above is, but hopefully you get the idea.
I am trying to use apache-rewrite rule to convert the below URL:
http://localhost/foo/bar/news.php?id=24
Into this format:
http://localhost/foo/bar/news/foo-bar
The number 24 is an id of a random row from a MySQL table, which also contains title and content fields.
MariaDB [blog]> select * from articles;
+----+---------+----------+
| id | title | content |
+----+---------+----------+
| 1 | foo-bar | bla bla |
+----+---------+----------+
1 row in set (0.00 sec)
I have the following rule inside my .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
^news/([A_Za_z0_9_]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L]
I also have a php code that generates a link like this:
$link = "<a href='news.php?id={$row['id']}'></a>";
echo $link;
However, I can't get the rewrite rule to change the path as the desired end result.
The substitution (Real) URL has a number -Code- to identify the link (According to your description): http://localhost/DIRECTORY/AID/news.php?news=42
That code is 42 in this case, but the URL you want displayed doesn't have it. Without that number, we'll get error 404 always. It's like entering only: http://localhost/DIRECTORY/AID/news.php?news=
Have to modify the URL you want displayed by adding the code after "/", for example. Could be a hyphen, etc., but the regex has to be modified accordingly.
Here is an example entering: http://localhost/news/42/ to go to http://localhost/DIRECTORY/AID/news.php?news=42:
RewriteEngine On
RewriteRule ^news/([0-9]+)/?$ DIRECTORY/AID/news.php?news=$1 [NC,L]
That's all you need. To test this example, insert this only code in news.php at http://localhost/DIRECTORY/AID/
<?php
if ( $_GET[ 'news' ] == '42' ) {
echo "HERE I AM<br /><br />";
}
?>
UPDATED according to OP description. Any name can be used instead of This_is_news:
RewriteEngine On
RewriteRule ^news/([0-9a-zA-Z-_]+)/?$ DIRECTORY/AID/news.php?news=$1 [NC,L]
First of all, you would need to change the href in the html, to give the new url format
function news_preview() {
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 5 ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo " ". substr($row['title'], 0,26)."...<br/>".; }
}
The will generate urls like http://localhost/news/24
Note that I removed the /DIRECTORY/AID from the url, as the htaccess suggest you want that to be url, as opposed to what you stated in the text.
But now the get to the http://localhost/news/this_is_article_title type of url. Because there is no correlation between this_is_article_title and the id 24, the only way to achieve this is by either adding the id to the url too, or to have the php lookup the news-article with this title in the database.
This last solution however has some problems, as the you can't just us the title in a url. You have to escape characters. Also you'll have to add a index for the title row in the DB for better performance.
So I'll go with the first solution. We will generate urls like this
http://localhost/news/24/this_is_article_title
First the php part
function news_preview() {
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 5 ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$url = "/news/$row[id]/".preg_replace('/[^a-zA-Z0-9-_]/', '_', $row['title']);
echo " ". substr($row['title'], 0,26)."...<br/>".; }
}
Next comes the htaccess part.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^news/([0-9]+)/([A-Za-z0-9_-]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L]
That should do it I think.
Place RewriteBase right after RewriteEngine On
It will set up rewrite engine correctly before you start redirecting
Unfortunately I'm unable to answer your question in PHP or Apache (although I am using a hand-rolled REST converter to create URL addresses on my current project), but from what I understand, you want your user to type out http://localhost/DIRECTORY/AID/article.php?a_id=24 and the address bar should end up like http://localhost/DIRECTORY/AID/news/this_is_article_title.
I'm not entirely sure what benefits this provides for you, and please bear in mind my solution will NOT allow your end-user to type the RESTful URL and end up at the page with the QueryString address. You'd need some extra legwork to do this, and even more legwork to keep it in sync with the DB (I'd recommend a script that deseminates the RESTFUL URL, queries the DB for the topic then returns the ID or page content ... but that's an different Stack Overflow question for another day.
SOLUTION
My proposed solution requires HTML5 doctype and a very light sprinkling of Javascript.
history.replaceState(null, "history title here", "news/this_is_article_title");
What this does is it changes the URL in the address bar without triggering a page redirect, reload or anything else. This javascript can be dynamically written with your PHP so as the page is served, the address is updated. The higher up in the document it is, the faster the change.
Here's a jsFiddle link: http://jsfiddle.net/uT3RP/1/
Unfortunately they run the code in an iframe so it doesn't control the main address bar, so I included an alert displaying what the address bar location would say, for proof. It's not the most elegant of solutions. I wouldn't even recommend doing what you're doing without the failsafes of making sure the URL displayed can be used to get to the same page. Disclaimer aside ... your problem is solved with 1 line of js and a doctype change (if you aren't using HTML5).
You can stop flogging poor ol' htaccess and get on with your project :)
This is a problem about URL-Rewrite and String-to-Id Algorithm.
Above all, please remember that what ever your url changes by rewrite module, the url in the browser bar always contains the post param like id or string(about your news).
Now to the question. Our purpose is just to rewrite the Url:
http://localhost/DIRECTORY/AID/news/this_is_article_title
to:
http://localhost/DIRECTORY/AID/news.php?a_id=24
With the rewrite module, we can only rewrite it to:
http://localhost/DIRECTORY/AID/news.php?title=this_is_article_title
and here is the htaccess part, alrealdy tested on a htaccess-online-tester
RewriteRule ^DIRECTORY/AID/news/([A-Za-z0-9_]+)$ DIRECTORY/AID/news.php?title=$1 [QSA,L]
The remaining work is build a algorithm for mapping the title to the news which rewrite module cannot help us(especially you manually rewrite the url one by one). We can use php code below:
<?php
//write url reflect to news title.
function build_news_url_by_title(){
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "".substr($row['title'], 0,26)."";
}
}
function get_news_by_title($title){
$real_title = strtr($title, "_", " ");
$query = "SELECT * FROM news WHERE title LIKE %".$real_title."% LIMIT 1";
return mysql_query($query) or die(mysql_error());
}
$title = $_POST['title'];
$news = get_news_by_title($title);
//some code return the news
...
So the url:
http://localhost/DIRECTORY/AID/news/this_is_article_title
can give us the news also.
Finally, from the steps above, if we type url
http://localhost/DIRECTORY/AID/news/this_is_article_title
in the browser bar, it can be also give us the news. And it has none bussiness about the stupid ID. And Though, there maybe some bugs with the code above, do not put it on your product server.
Can you see if this works?
RewriteEngine On
RewriteBase /DIRECTORY/AID/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
^news/([A-Za-z0-9_]+)$ news.php?id=$1 [QSA,L]
EDIT : Fixed the regex character class definitions.
You are missing the title of the URL. If you wish to show that in URL, then you must include it in the link as well, like this:
<a href="news.php?news_id=$id&title=$url_tile">
This seems to be a complicated problem because you do not know where it really is doing wrong.
I would suggest you divide what you want to do into small parts and make each of them work properly before you join them together. For example:
1. Make sure .htaccess file is readable and can do some simple thing, preventing directory indexing for instance.
2. Make sure you can redirect something with simple html code.
3. Make sure you can run Felipe's example code successfully. From here you can get good picture of what is going on.
And as a side note:
It is more common to rewrite like this:
http://localhost/DIRECTORY/AID/news.php?a_id=24 TO -->
http://localhost/DIRECTORY/AID/news/24_this_is_article_title
Notice the id 24 is still carried over to the rewritten url. That will make pattern matching simpler and avoid unnecessary processing of title duplication.
Change the link:
echo " ". substr($row['title'], 0,26)."
to
echo "".$row['title'].""
That way, the link will go to news/$row['title'] instead of news.php?id=.... And now in the page DIRECOTORY/AID/news.php, you should get the id and check if it is a number OR text, and in case of text match it up with the $row['title'] and then load the page accordingly.
Notes:
This assumes that $row['title'] is unique across all other rows.
The title does not contain non HTML content, in which case you will have to URL Escape those characters.
If the title is not going to be unique then you should probably do news/{id}/{title} and then in rewrite it to DIRECTORY/AID/news.php?id={id}&title={title} and then you can base it off of the ID instead of the title.
Hope that helps.
If you feel your .htaccess file is not working as intended then this is a server configuration issue and most likely to do with the AllowOverride directive under the Apache configuration.
In your http.conf file find the section which looks something as follows:
<Directory>
Options FollowSymLinks
AllowOverride None
</Directory>
Change the AllowOverride directive to allow All.
<Directory>
Options FollowSymLinks
AllowOverride All
</Directory>
The next thing is to ensure that the mod_rewrite module is enabled for your XAMPP install. Search for the following line:
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the # so it looks like so:
LoadModule rewrite_module modules/mod_rewrite.so
Restart the Apache service after saving all your changes.
Also ensure you are using the RewriteBase directive in your .htaccess configuration as follows:
RewriteEngine On
RewriteBase /DIRECTORY/AID/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
^news/([A-Za-z0-9_]+)(/)?$ news.php?title=$1 [QSA,L]
The next thing is to ensure your links are pointing to the Rewrite URL. Your echo line should be something like the following:
echo " " . substr($row['title'], 0, 26) . "...<br />";
Now since you can only retrieve titles with this URL rewrite method we need to configure your PHP script accordingly to retrieve the content based on the title. If you still want to use "id" only for retrieving the record then your Rewrite URL should contain the "id" in it in some form. Typical examples of this form are:
news/the_news_title_123
news/123_the_news_title
news/123/the_news_title
I cannot comment so I have to answer.
Reading all answers and your question, it is not clear what you want. At least for me. You say, for example:
http://localhost/DIRECTORY/AID/article.php?a_id=24 to
http://localhost/DIRECTORY/AID/article/this_is_article_title
But I guess that's not quite right, unless you want
http://localhost/DIRECTORY/AID/article.php?a_id=24
to be the URL entered in the browser address bar and if so, what would be the purpose of the redirection? Finally, any visitor would have to type precisely what you don't want them to type.
My guess is that you want the friendly URL to be entered:
http://localhost/DIRECTORY/AID/article/this_is_article_title , so the question should be the other way around:
http://localhost/DIRECTORY/AID/article/this_is_article_title TO
http://localhost/DIRECTORY/AID/article.php?a_id=24
The next thing that does not seem to be clear, is what's displayed in the browser bar? The only answer is: The entered URL. No way it can show anything different.
In short: If you want http://localhost/DIRECTORY/AID/article/this_is_article_title to show in the addres bar, that's what you have to enter. The real URL, the SUBSTITUTION (http://localhost/DIRECTORY/AID/article.php?a_id=24), is never shown and is never typed. That's what redirection is for.
On the other hand, it is not clear either how the ID numbers provided by news.php are expected to be converted to strings like article/this_is_article_title. ¿Where are those strings, how many ID numbers are, what kind of algorithm or formula should be used to achieve that conversion, which of those IDs are 'root" as you mentioned in a comment and how can they be identified, etc.? You should elaborate more on this point because it seems improvised and incoherent with your previous comments.
I might be wrong, of course. I am just guessing to try to help with your question.
Please, geniuses, don't downvote this answer, read it. I am not trying to answer the question and I am really far from being a genius.
Looks like you've forgotten the slash in front of “news.php”.
I'm really new at mod_rewrite and i have been trying to figure this out but really stuck. p
Here is my issue.
I have a page http://example.com/user/?s=81
?s=81 is reading from user id in the db.
What i would like to have is a link
http://example.com/nookie
In the database i have a field called whatuser
so on row 81 in that field i have user nookie
So what i would like is to read from databse what user it is in database
and create easi url from it.
i have also several php pages inside that user folder so i need to be able to link
to them like
example.com/nookie/step1.php
example.com/nookie/step2.php
To my knowledge you can not query databases with mod_rewrite.
how about putting a PHP-script to /user/?s=81, that looks up the user's name in the db and then relocates the user to $url = "/$username"; see PHP's header function passing "Location: $url" to it.
The other possibility (that I haven't thought through too much :) ) is that you add an extra field to the database e.g. user_home = /nookie/. So the logon script grabs it when verifying account details and thats where you send them to on successful validation? No rewrites /extra scripts needed.
Here's what I would suggest: if your username is only alphanumeric chars, you could pass the nick to all your Php files, after an internal rewrite, in the GET query.
Something like:
RewriteRule /([a-zA-Z0-9]+)$ /user/?s=$1 [QSA,L]
RewriteRule /([a-zA-Z0-9]+)/(.*)$ /$2?s=$1 [QSA,L]
And then, just have the "mother of mother" classes in Php that check for a value "s" in the query string ($_GET) which checks in the database if the user exists. If the user doesn't exists, make a 404 in Php.
I have almost sorted it out and here is the solution so far:
Here is the .htaccess row
RewriteRule ^([a-z0-9_-]+)$ user/?s=$1 [L,NC]
Then in the index file i have the following:
$trafikskola_id = mysql_real_escape_string($_GET['s']);
$vilken_trafikskola = mysql_query("SELECT * FROM users where slug='$trafikskola_id'") or exit(mysql_error());
In the database i have create slug field and inside that on row 81 added nookie and my url looks like
http://mypage.com/nookie instead of http://mypage.com/user/?s=81 =))
However i have the issue that i can not have link
http://mypage.com/nookie/ to have a forwardslash
And aswell non of my css - js - images are working.. Any ideas to solve those issues?
i want to redirect
http://testsite.com/campus.php
to
http://testsite.com/campus.php
but the file campus.php doesn't exists. It fetches the page content from database and it must be displayed.
I haven't got any idea.
First of all, your two URLs are the same.
But if you want to call a page that doesn't actually exist but is pulled from the database, you typically redirect some part of the URL to point into a $_GET variable used to access the database. All requests actually go to index.php, and index.php handles the database and displays the correct data.
# Conisde this pseudocode
# Rewrite somepage to index.php?pagename=somepage
RewriteRule /somepage.php /index.php?pagename=somepage
# The actual .htaccess rewrite looks like:
RewriteEngine On
# Assuming pagename is upper/lower letters and numbers only...
RewriteRule /([A-Za-z0-9]+)\.php /index.php?pagename=$1
Now in your PHP, you use $_GET['pagename'] (campus in your case, I think) to call the text from the database and display it.
EDIT I added the \.php to the RewriteRule. Now /campus.php rewrites to /index.php?pagename=campus
Let' say for example one of my members is to http://www.example.com/members/893674.php. How do I let them customize there url so it can be for example, http://www.example.com/myname
I guess what I want is for my members to have there own customized url. Is there a better way to do this by reorganizing my files.
You could use a Front Controller, it's a common solution for making custom URLs and is used in all languages, not just PHP. Here's a guide: http://www.oreillynet.com/pub/a/php/2004/07/08/front_controller.html
Essentially you would create an index.php file that is called for every URL, its job is to parse the URL and determine which code to run base on the URL's contents. So, on your site your URLs would be something like: http://www.example.com/index.php/myname or http://www.example.com/index.php/about-us or http://www.example.com/index.php/contact-us and so on. index.php is called for ALL URLs.
You can remove index.php from the URL using mod_rewrite, see here: http://www.wil-linssen.com/expressionengine-removing-indexphp/
Add a re-write rule to point everything to index.php. Then inside of your index.php, parse the url and grab myname. Lookup a path to myname in somekinda table and include that path
RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]
index.php:
$myname = $_SERVER['REQUEST_URI'];
$myname = ltrim($myname, '/'); //strip leading slash if need be.
$realpath = LookupNameToPath($myname);
include($realpath);
create a new file and change it name to (.htaccess) and put this apache commands (just for example) into it :
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^profile/([0-9]*)$ members.php?id=$1
You must create a rewrite rule that point from http://www.example.com/myname to something like http://www.example.com/user.php?uname=myname.
In '.htaccess':
RewriteEngine on
RewriteRule ^/(.*)$ /user.php?uname=$1
# SourceURL TargetURL
Then you create a 'user.php', that load user information from 'uname' GET variable.
See from your question, you may already have user page based on user id (i.e., '893674.php') so you make redirect it there.
But I do not suggest it as redirect will change the URL on the location bar.
Another way (if you already have '893674.php') is to include it.
The best way though, is to show the information of the user (or whatever you do with it) right in that page.
For example:
<?phg
vat $UName = $_GET['uname'];
var $User = new User($UName);
$User->showInfo();
?>
you need apache’s mod_rewrite for that. with php alone you won’t have any luck.
see: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html