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
Related
How can I do to change the name of the url of my site which is: www.example.com/user/panel.php to www.example.com/username/panel.php where the "username" is unique for each user , And for each login would be the name of the user from database, as it is in jsfiddle.net, could they help me?
Personally I would not use .htaccess for this ( specifically )
that said most the time people do it this way
RewriteEngine On
RewriteRule ^users/([-a-zA-Z0-9_]+)/?$ index.php?user=$1 [L]
So if you had a url like
www.yoursite.com/users/someguy
Then it would pass it to apache ( and php ) as
www.yoursite.com/index.php?user=someguy
Then in PHP you could access it just using $_GET[user].
Now ignoring security concerns I may have ( you shouldn't rely on user input to tell who they are, they can lie about it) for this I would use what I call the URI method ( not URL ) a URI is an imaginary path. This is also the method employed by many MVC systems. So for this I will start with the URI
www.yoursite.com/index.php/users/someguy
Notice where the index.php is ( in the middle ). Then you do a .htaccess like this
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f #if not a real file
RewriteCond %{REQUEST_FILENAME} !-d #if not a real folder
RewriteRule ^(.*)$ index.php/$1 [L] #hide the index.php
So what this does is allow you to remove the index.php giving you a url like this
www.yoursite.com/users/someguy
Which is what we want, and looks basically the same as the first case.
Then you cam use the $_SERVER['QUERY_STRING'] supper global which will give you everything past index.php
/users/someguy
And you can split that up, route it somewhere, do whatever you need to with it. Like this
$uri = array_filter( explode('/', $_SERVER['QUERY_STRING'] ) );
//$uri = [ 'users', 'someguy' ];
Now the reason I like this more, is it's more flexible and it lets you use the query string the ?var part of the url for other stuff. ( like bookmarkable search forms ) ie. it feels less hacky because your not breaking the query parameters of a GET Request. Conversely, with the first method, if your .htaccess is sloppy you could make it were the query part of the URL is unusable on your site, and that just feels wrong to me.
It also easier to maintain, because it requires no further setup for additional pretty urls
For example:
Say you want prettyfy your product. Using the first method you would have to go back to the .htaccess add at least 1 more rule in:
RewriteEngine On
RewriteRule ^users/([-a-zA-Z0-9_]+)/?$ index.php?user=$1 [L]
RewriteRule ^products/(0-9_]+)/?$ index.php?product=$1 [L]
Possibly even more complex levels if you have product categories
RewriteRule ^produts/([-a-zA-Z0-9_]+)/(0-9_]+)/?$ index.php?category=$1&product_id=$2 [L]
After a wile you would wind up with dozens of rules in there, some of which may not be immediately clear as to what they do. Then you realize you spelled products as produts and have to start renaming things. It's just a mess later on.
Now using the second method you don't need to do any additional steps, besides routing it in your index page. You just put the url in
www.yoursite.com/products/123
And pull that stuff from the $_SERVER array with no further messing with rewrite rules.
Here is a previous answer I did that outlines how to build a basic router.
Oop php front controller issue
Make sense.
Hello I was trying to come up with the solution to my problem, but I just was not able to. So here is my problem:
What I used was a .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.+(.*)/(.*)$ ./index.php?mesto=$1&den=$2 [QSA,NC,L]
It will display the url well. as www.site.com/CITY/DAY for example ../Prague/30.3.2014 but i need it to be more complex.
What I need is to have additional parameters, such as Bar or Restaurant in the url for example www-site.com/Prague/30.3.2014/p/bar/restaurant and other time I might have www-site.com/Prague/30.3.2014/p/pizza/bar
That part I have no idea how to do, because I have 5 different parameters
I imagine that the raw url would look this index.php?city=Prague&day=30.3.2014&p1=0&p2=0&p3=0&p4=0&p5=0 where p1 to p5 are the parameters being active (0 not 1 yes).
I don't understand how to detect what parameters are active and how to properly display the pretty url. Could you please help me?
Use
RewriteRule ^(.*)$ ./index.php [QSA,NC,L]
This will redirect all your requests to a single index.php that parses the uri with something like this:
<?php
// Example URI: /florence/30-06-2009
// Remove first slash from REQUEST_URI
$uri = substr($_SERVER['REQUEST_URI'],1);
// Get an array with portions between slashes.
$splittedURI = explode("/", $uri);
// Here you get your city (or anything else that you want)
$city = array_unshift($splittedURI); // In example, $city = "florence"
// Remaining itens in $splittedURI are the arguments/parameters to your page
// Like this:
$date = $splittedURI[0]; // In example, $date = "30-06-2009"
?>
Remember that this is just and example, and you should do additional verifications to avoid PHP exceptions.
If you need complicated routing (and if you sure you want to create your own router instead of using a ready solution as ZF, Symfony etc.) you're better off just passing the whole request uri to a php router object. There you can as complex router logic as you need.
So basically, loose the parsing in the rewrite rule:
RewriteRule ^(.*)$ ./index.php?route=$1 [QSA,NC,L]
Then you can let the index.php create a router object that can parse the route parameter and delegate the job where it needs to.
I'd recommend reading up about existing routing solutions though.
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;
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.
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.