I'm developping a website using php and the "template.inc" class.
The problem is that I want to create a mini-cms that allows the admin to create an "html" page with these mysql attributes:
Table Name : Page
-----------------
id :auto-icremented)
name :varchar
In the architecture, if he created the page number "5", the url is
"ww.mywebsite.com/index.php?id=5".
But, this isn't very esthectic so, as I'm very bad at url rewriting even if i read many tutorials, i want to type the name+"html" to access to the page.
If we take the example of the
"www.mywebsite.com/index.php?id=5"
if the admin created a page with the following values:
id : 5
name : 'home'
i want that the user can type
"www.mywebsite.com/home.html"
and with no redirection as i want that this last url must still appear and become the official url.
Thanks for your answer,
i know how to rewrite www.mywebsite.com/index.php?id=5 to www.mywebsite.com/5.html ... but the problem is that i want, first, to get the "name" vale before and in my example, the name value is "home" (5 =>'home').
How can i access to my database with the url rewriting engine?
Thank you very much,
regards.
Use the .htaccess file from a standard Wordpress install to redirect everything to one PHP file. Something like this...
<IfModule mod_rewrite.c>
RewriteEngine On
# Base is the URL path of the home directory
RewriteBase /
RewriteRule ^$ /index.php [L]
# Skip real files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.php [L]
</IfModule>
Then use $_SERVER['REQUEST_URI'] to figure out what the user was looking for. Modify the .* if you want to make the rule more specific, like .*\.html.
Zakaria,
After using Renesis's rewrite rule, $_SERVER['REQUEST_URI'] will be equal to 'home.html'.
Try something like:
<?php
// clean
$page = mysql_real_escape_string($_SERVER['REQUEST_URI']);
// make query
$query = sprintf("select Page.* from Page where name = '%s'", $page);
// find page ID
if($result = mysql_query($query)){
$page = mysql_fetch_assoc($result);
echo "<pre>", print_r($page, true), "</pre>";
}
?>
Possible output
Array (
[id] => 5
[name] => 'home.html'
)
Use Apache URL Rewriting for this. there are many many examples on this site alone of this. You could also try the official Apache rewriting docs.
You will need to make sure your database enforces uniqueness on name, or you will have problems.
Edit
Have your index.php take a name= parameter instead of a id parameter. You will need to make sure your db has the name field indexed so you don't do a table scan for every page request.
Related
I want to know how to page url without .php extension
for ex here is my website :
http://mywebsite.com/ now from the home page whenever i click on any gallery it will goes to the page gallery.php with querystring of galleryID for ex
http://mywebsite.com/gallery.php?id=29
So instead of this gallery.php?id=29 I want to make the url something related to the page title
http://mywebsite.com/9-WEDDING-GIFT-IDEAS
Thanks in advance
I'd recommend using a PHP framework once you start going down this path, that gives your application/site a structure, and the ability to setup routes (paths) like you're requesting.
I'm a fan of Laravel, this allows you to use http://example.com/index.php/friendly-url/goes-here if you haven't setup Apache (the web server) to remove them.
You can remove the index.php/ part and just have http://example.com/friendly-url/goes-here by using the Apache mod_rewrite which Laravel includes for you. Check out the documentation under Pretty URLs
Hope that helps.
There are two ways you can do this. If you don't have a ton of URLs, you can add them in to your '.htaccess' file manually.
RewriteEngine On
# MANUAL
RewriteRule ^9-WEDDING-GIFT-IDEAS/?$ gallery.php?id=29 [L]
RewriteRule ^MOST-BEAUTIFUL-WEDDING-LOCATIONS/?$ gallery.php?id=30 [L]
# ...
Otherwise, you can have 'gallery.php' handle looking up which article to display based on the title. So if it receives a title of '9-WEDDING-GIFT-IDEAS', then it can look up that title in the database and fetch the article for that title. Here, the article title will be passed as the 'id' parameter to 'gallery.php'.
RewriteEngine On
# PARSING HANDLED IN gallery.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ gallery.php?id=$1 [L]
EDIT:
<?php
// gallery.php
$article_title = $_GET['id'];
// ...
// DO A DB LOOKUP TO GET THE ARTICLE ID WHERE TITLE = '$article_title'
// OR JUST GET THE ARTICLE BASED ON THE TITLE INSTEAD
I am new to .htacces and for ages I have been trying to get my domain from:
www.domain.com/post.php?post_id=20
to something such as this:
www.domain.com/post/this-is-the-title/
As I said I am new to .htaccess but anything would help please!
NOTE: I would be getting the titles of my blog posts from an SQL database somehow
If the page titles are database-driven (or otherwise dynamic), I don't see how you could get away with .htaccess rewrites. It would make more sense to use routing in your PHP script.
I have written about an extremely simple routing method here. It's for people only getting into the subject, but you should be able to build a database-driven router based on that.
Essentially, route all your traffic through index.php and there, get the request URI and decide what resources to load.
[EDIT]
Let me elaborate a bit, using the info from my blog post.
Assuming you have your site set up and running, first direct the traffic to index.php. You do that in .htaccess and it can be done like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
Then, in index.php (or in a script that's called from index.php), you can get the request URI:
$uri = $_SERVER["REQUEST_URI"];
OK, so far so good. Now let's assume your database holds page content along with the page aliases. The uri will most probably be the page alias, so all you need to do is something like this:
$pdo = new PDO(/* your db connection params */);
$page = $pdo
->query("SELECT * FROM pages WHERE alias = :alias",
array("alias" => $uri)
)
->fetch();
At this point you should have the page content corresponding to the title (or alias) in the URI string. All you need to do now is display it any way you want:
echo $page["content"];
You can't. You have to put the title on the query string.
An .htaccess cannot safely get anything from the database.
Since you are going to rewrite the url, why not simply write the post title in the URI?
You can't do this with an .htaccess cause you need to get "the titles of your blog posts from an SQL database somehow", do a redirect with PHP. :)
If you have a url such as the one as follows:
http://www.example.com/400x200
is it possible to create a page which echos out 400x200 when the user visits that url using php?
I know how to echo the path - that is easy enough (ltrim($_SERVER['PATH_INFO'], '/')), but do not know how to create the page dynamically.
Any help would be much appreciated, thanks in advance
The request URI (/400x200) is stored in the server superglobal: $_SERVER["REQUEST_URI"].
You need to take that and route the URI accordingly. The simplest possible scenario: in your index.php, place this code:
$uri = trim($_SERVER["REQUEST_URI"],"/");
if (preg_match("/\d+x\d/")) {
list($width,$height) = explode("x",$uri);
// some logic with the above vars, e.g. include a view script
}
What this does is check whether the URI has the format {number}x{number}, extracts both numbers and stores them in the variables $width and $height. You can then do whatever you like with the variables.
In order to make the request always point to the file containing this code, edit your .htaccess and put in something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
(the .htaccess code is copied from the default Zend Framework project, in case anyone asks).
You may want to look at Apache Rewrites for rewriting your URL:
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
Do not know what do You mean by creating the page dynamically but I guess that using of mod_rewrite is what You need.
In Your .htaccess file You have to create some rules that will rewrite the URL to something distinguishable by Your PHP script - like from URL
http://www.example.com/400x200
to get
http://www.example.com/index.php?param=400x200
And then You can in Your index.php script do echo $_GET['param'];...
Google something about PHP and mod_rewrite: http://www.google.com/#q=PHP+mod_rewrite
Assuming you're using Apache, this can be done using something called URL rewriting. Create a file called .htaccess in your document root, and add this:
# Turn URL rewriting on
RewriteEngine on
Options +FollowSymlinks
# Rewrite rule
RewriteRule ^(\d+x\d+)/?$ index.php?dimensions=$1 [L]
The first two lines turn the rewrite engine on, and the third line defines a RewriteRule. The first part ^(\d+x\d+)/?$ is a regular expression that the part of the URL after the domain will be matched against.
The second part index.php?dimensions=$1 is the URI that will be rewritten to. The client doesn't see this, but PHP will.
If I do a print_r($_GET) in index.php with the URL http://localhost/400x300, I get this:
Array ( [dimensions] => 400x300 )
This is from the standard $_GET superglobal array in PHP and can be used as normal. URL rewriting leaves the URL as it is in the browser, yet allows you to turn it into one usable by PHP with a query string.
To make your script a bit easier to use, you could split the expression up to get separate X and Y values:
RewriteRule ^(\d+)x(\d+)/?$ index.php?x=$1&y=$2 [L]
Which will give an array like this:
Array ( [x] => 400, [y] => 300 )
Make it a GET variable like
http://www.example.com?size=400x200
Then you can retrieve the String with
$size = $_GET['size'];
What I'd recommend you to do is to get the values based on split or explode()
$lw = $size.explode('x',$size);
$length = $lw[0];
$width = $lw[1];
//Manipulate the values accordingly like
echo $length.'x'.$width;
How can I make www.mydomain.com/folder/?id=123 ---> www.mydomain.com/folder/xCkLbgGge
I want my DB query page to get it's own URL, like I've seen on twitter etc etc.
This is known as a "slug" wordpress made this term popular. Anyway though.
Ultimately what you need to do is have an .htaccess file that catches all your incoming traffic then reforms it at the server level to work with your PHP in the sense, you will still keep the ?id=123 logic intact, but to the client side '/folder/FHJKD/' will be the viewable result.
here is an example of an .htaccess file I use a similar logic on.. (so does wordpress for that matter).
RewriteEngine On
#strips the www out of the domain if there
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
#applies logic that changes the domain from http://mydomain.com/post/my-article
#to resemble http://mydomain.com/?id=post/my-article
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?id=$1 [QSA,L]
what this will do is take everything after domain.com/ and pass it as a variable to index.php the variable in this example would be 'id' from this you have to device a logic that best suits your sites needs.
example
<?php
//the URL for the example here: http://mydomain.com/?id=post/my-article
if($_GET['id'])
{
$myParams = explode('/', $_GET['id']);
echo '<pre>';
print_r($myParams);
echo '</pre>';
}
?>
now the logic for this would have to go much deeper, this is only pure example at a basic level, but overall and especially cause your working with a database I assume, your gonna wanna make sure the $myParams is clean of malicious code, that can inject into your PHP or Database.
The output of the above $myParams via print_r() would be:
Array(
[0] => post
[1] => my-article
)
To work with it you would need to do at the very least
echo $myParams[0].'<br />';
or you could do it like this cause most browsers will add a final /
<?php
//the URL for the example here: http://mydomain.com/?id=post/my-article
if($_GET['id'])
{
//breaks the variable apart, removes any empty array values and reorders the index
$myParams = array_values(array_filter(explode('/', $_GET['id'])));
if(count($myParams > 1)
{
$sql = "SELECT * FROM post_table WHERE slug = '".mysql_real_escape_string($myParams[1])."'";
$result = mysql_query($sql);
}
}
?>
Now this admitedly is a very crude example, you would want to work some logic in there to prevent mysql injection, and then you will apply the query like you would how you are now in pulling your articles out using just id=123.
Alternatively you could also go a completely different route, and explore the wonders of MVC (Model View Control). Something like CodeIgniter is a nice easy MVC framework to get started on. But thats up to you.
This can be achieved with mod_rewrite e.g. via the .htaccess file.
In your .htacess, you need add RewriteEngine on.
After that, you will need to do some regexs to make this little beast work. I'm assuming ?id is folder.php?id=123.
For example the folder piece: RewriteRule ^folder/([a-zA-Z0-9_-]+)/([0-9]+).html$ folder.php?id=$123
I'm trying to write an .htaccess file that will make my URLs more attractive to search engines. I know basically how to do this, but I'm wondering how I could do this dynamically.
My URL generally looks like:
view.php?mode=prod&id=1234
What I'd like to do is take the id from the url, do a database query, then put the title returned from the DB into the url. something like:
/products/This-is-the-product-title
I know that some people have accomplished this with phpbb forum URLs and topics, and i've tried to track the code down to where it replaces the actual URL with the new title string URL, but no luck.
I know I can rewrite the URL with just the id like:
RewriteRule ^view\.php?mode=prod&id=([0-9]+) /products/$1/
Is there a way in PHP to overwrite the URL displayed?
At the moment you're wondering how to convert your ugly URL (e.g. /view.php?mode=prod&id=1234) into a pretty URL (e.g. /products/product-title). Start looking at this the other way around.
What you want is someone typing /products/product-title to actually take them to the page that can be accessed by /view.php?mode=prod&id=1234.
i.e. your rule could be as follows:
RewriteRule ^products/([A-Za-z0-9-])/?$ /view.php?mode=prod&title=$1
Then in view.php do a lookup based on the title to find the id. Then carry on as normal.
One way to do it, would be just like most mvc frameworks. You can redirect all your pages to the same index.php file, and you use your script to determine which page to load.
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>
and your php file will have a script like this one:
// get the url
$uri = (isset($_SERVER['REQUEST_URI']))?$_SERVER['REQUEST_URI']: false;
$query = (isset($_SERVER['QUERY_STRING']))?$_SERVER['QUERY_STRING']: '';
$url = str_replace($query,'',$uri); // you can edit this part to do something with the query
$arr = explode('/',$url);
array_shift($arr);
// get the correct page to display
$controller =!empty($arr[0])?$arr[0]:'home'; // $arr[0] could be product/
$action = isset($arr[1]) && !empty($arr[1])?$arr[1]:'index'; // $arr[1] can be product-title
}
of course you will have to work this code to fashion your application
I hope this helps
One way would be to output a Location: header to force a redirect to the chosen URL.