I am making a social networking site where I have created my own PHP mvc but I am having problems in url rewriting. My mvc works this way.
If this is the domain www.example.com/manage/posts/11111 , manage is the class, post is the method in that class & 1111 is a parameter.
The problem is that I cannot create vanity profile urls since they will not work. I want each user to have vanity profile url ie www.example.com/username but this will search for a class named username.
Kindly advise me on how
a) I can achieve vanity profile urls such as www.example.com/username without adding anything such as www.example.com/users/username.
I know there a other PHP MVCs but I just want to use my own
This is my current htaccess code::
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ index.php?ref_url=$1 [NC,L,QSA]
</IfModule>
I don't know why all people try to build their own frameworks there are so many really good frameworks that have a look at security and many more. But ok i think your problem is your rewrite rule.
RewriteRule ^(.*)$ index.php?ref_url=$1 [NC,L,QSA]
Normally you should rewrite all your input to a given file and parse the url and call the controller you need. To get a better understanding take a look at the Symfony2 Routing component.
http://symfony.com/doc/current/components/routing/introduction.html
You should first create a router to route your urls to controllers/classes. I will prefer klein router or FastRoute for its simplicity.
After placing a router do what u want:
(Example)
$router=new Router;
$router->addroute("/[:username]",
function(){
//Bring UserAccount Details from DB using [:username]
}
);
$router->addroute("/manage/posts/[:id]",
function(){
//Get Post details using [:id]
}
$router->dispatch();
**NB:**This is only a basic representation of usage of a router
Related
Is there any way I can have good looking URL in PHP? any default php URL would look like this: http://example.com/something/?post=something But Is It possible to have It like this: http://example.com/something/user Is It possible to remove ?post= without using .htaccess
Here is some example code that I have been working on, Which on click of a post It would access my database and load the content:
<?php
if(!isset($_GET['post'])) {
$q = mysql_query("SELECT * FROM posts WHERE postID='something'");
} else {
$id = $_GET['post'];
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT * FROM posts WHERE postID='$id'");
}
$p = mysql_fetch_object($q);
?>
Thank you for your Time!
To get clean URLs you'll have to use mod_rewrite module, but you can minimize it's use, if you leave url parsing to your own script and have only one entry point. Look how it's made in WordPress:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
So if there's no real file or directory that is requested in URL, each and every request is redirected to index.php and then parsed by some internal route mapping script.
There's an example of such script in similar question.
I suggest for having clean URL use one of php frameworks which default have this ability.
if you want to use pure php you should use a Router in your project which means you should write your own php framework.
have you ever worked with any php framework??
I suggest using laravel or cakephp for entry point of learning php frameworks.
You need to define a Router and Dispatcher in your project.The Router extracts url and dispatcher calls that function related to url.in the other word,you should impelement frontcontroller design pattern in your project.I suggest check this tutorial
http://www.sitepoint.com/front-controller-pattern-1/
I am trying to create my own PHP MVC framework for learning purpose. I have the following directory structure:
localhost/mvc:
.htaccess
index.php
application
controller
model
view
config/
routes.php
error/
error.php
Inside application/config/routes.php I have the following code:
$route['default_controller'] = "MyController";
Now what I am trying to achieve is when any user visits my root directory using browser I want to get the value of $route['default_controller'] from route.php file and load the php class inside the folder controller that matches with the value .
And also if any user tries to visit my application using an url like this: localhost/mvc/cars, I want to search the class name cars inside my controller folder and load it. In case there is no class called cars then I want to take the user to error/error.php
I guess to achieve the above targets I have to work with the .htaccess file in the root directory. Could you please tell me what to code there? If there is any other way to achieve this please suggest me.
I have tried to use the .htaccess codes from here, but its not working for me
It all sounds well and good from a buzzword standpoint, but to me this is all a little confusing because I see PHP's model as an MVC model already. It's providing the API for you to program with and deliver your content to your web server Apache and your database (something like MySQL). It translates the code(model) for you into HTML(view) ... provided that's what you intend, and you're supplying code as the user input (control). Getting too wrapped up in the terminologies gets a little distracting and can lead to chaos when you bring someone in to collaborate who isn't familiar with your conventions. (This should probably never be used in a production environment for a paying gig.)
I can tell you that on the page that you referenced they guy's .htaccess file needs a little work. The [L] flag tells mod_rewrite that this is the last command to process when the rule returns true. So you would either need to do this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Or the following... but he was using a passthru flag which means that he is implying there are other things that could be processed prior to the last rule (eg. might be rewrite_base or alias), but that's not actually the case with his .htaccess file since it's a little bare. So this code would work similar to the code above but not exactly the same. They can't be used together though, and really there would be no need to:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1
</IfModule>
The difference is the in the way it's processed. On the first .htaccess example you're passing any file to index.php regardless of whether it exists or not. You can [accidentally] rewrite a path that has a real file so that the real file is never accessed using this method. An example might be you have a file called site.css that can't be accessed because it's being redirected back to index.php.
On the second ruleset he's at least checking to see if the server doesn't have a file or a directory by the name being requested, then they're forwarding it to index.php as a $_GET variable (which seems a little pointless).
The way I typically write these (since I know mod_rewrite is already loaded in the config) is to to this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule .* index.php
In my PHP code I pull the $_SERVER['REQUEST_URI'] and match it against a list of URIs from the database. If there's a match then I know it's a real page (or at least a record existed at some point in time). If there's not a match, then I explode the request_uri and force it through the database using a FULLTEXT search to see what potentially might match on the site.
Note: if you blindly trust the request_uri and query the database directly without cleaning it you run the risk of SQL injection. You do not want to be pwnd.
<?php
$intended_path = $_SERVER['REQUEST_URI'];
if(in_array($intended_path,$uris_from_database)){
//show the page.
} else {
$search_phrase = preg_replace('!/!',' ',$intended_path);
$search_phrase = mysqli_real_escape_string($search_phrase);
$sql = "SELECT * FROM pages WHERE MATCH (title,content) AGAINST ('$search_phrase');"
}
Sorry if this sounds a bit pedantic, but I've had experience managing a couple of million dollar (scratch) website builds that have had their hurdles with people not sticking to a standard convention (or at least the agreed upon team consensus).
I am currently coding a pagination script into many parts of my site, this has been a well needed and requested feature and I have finally been able to come round and start coding it, it is all going well, until I find that my rewritten urls don't like working with the pagination urls.
So, an example page on my site would be news.php. This file structure can be something like news.php?id=5. I have rewritten the url like so:
/news/5/
## Rewrite URL's for News & Dev ##
RewriteRule ^news/([0-9]+)/$ /news.php?id=$1 [L]
RewriteRule ^news/([0-9]+)$ /news.php?id=$1 [L]
RewriteRule ^news$ /news.php [L]
RewriteRule ^news/$ /news.php [L]
The pagination script I am using prepends two new variables in the url, the new url turns out to be this:
news.php?page=1&ipp=55id=5
I would really appreciate it if anyone could assist me in making the urls look better, as it defeats the object of having it in the first place if after they use the pagination, it changes the url back to a clunky and ugly url.
I don't want it to be required to have parts of the url, that is something I really don't want..
e.g I don't want the url to be required to be /news/1/55/5, instead id like it to be optional.
Thank you for your time, it is appreciated!
Additional Information
The links in my news script currently display like so:
news.php?page=1&ipp=55id=5
I don't like to see ugly urls like that, and want to make the url look better using mod_rewrite, It would be better if the urls would display like so:
/news/PAGE/IPP/ID/ -> return news.php?page=1&ipp=55id=5
Also, to make it as user friendly as possible, I don't want any of the fields to be required as such, so for example I would like to have the following link accessible at all times without it requiring the other fields.
/news/ID/
Then, when the user clicks a pagination link, it would use the following link structure:
/news/PAGE/IPP/ID/ -> return news.php?page=1&ipp=55id=5
This is all from user feedback of my site, and is something that people have been asking for. Problem is, I don't understand even simple .htaccess
Thanks
RewriteBase /
# add slash to end of url if not present (and do a redirect)
RewriteCond $0 !/$
RewriteRule ^news([^\.]*)$ $0/ [L,R=302]
# rewrite url with format /news/[<id>/[<page>/[<ipp>/]]]
RewriteRule ^news/(?:([0-9]+)/)?(?:([0-9]+)/)?(?:([0-9]+)/)?$ /news.php?id=$1&page=$2&ipp=$3 [L]
Not sure what ipp is supposed to be, but my guess is it shows the number of item per page. I would personally not like to have that in my url.
You can have :
news/id/page/ipp with
RewriteRule ^news(/?)$ news.php [L]
RewriteRule ^news/([0-9]+)-(.*)_([0-9]+)(/?)$ news.php?page=$1&ipp=$2&id=$3 [L]
news/1222-subjet-for-example_34
return :
news.php?page=1222&ipp=subject-for-example&id=34
use (/?) instead of create many rules ;)
Hope it's works for you.
The standard GET query as a link for each user is easy but ugly for the users and search engines.
// This looks UGLY
website.com/index.php?userid=43232
//This is what I want
website.com/coolUser
How to make a custom link for every user without creating folders all the time?
It's called "routing". You may begin with this article: http://www.phpaddiction.com/tags/axial/url-routing-with-php-part-one/
What you mentioned called "clean URL", and what you need something known as "mod-rewrite" capability in Apache configuration.
Sergei and Zulkhaery direct you to it with their comments. Also you can take a look at the link below:
http://wettone.com/code/clean-urls
But don't forget you may see some problems with you css, js, and image files. But they have their own solutions too. You can find them if you get these problems.
Simple way to make URL like that, using .htaccess (create .htaccess file and upload to your public_html / wwwdir)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9a-zA-Z-]+)/?$ index.php?userid=$1 [L]
Now, you can access http://yoursite.com/43232 OR http://yoursite.com/index.php?userid=43232
I have been trying to get my urls to be more user friendly and I have come up with this set up
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ userpage?user=$1 [NC,L]
I added this to my .htaccess but I'm now i'm confused as to how to access these urls.
in my index.php when a user logs in i have tried to redirect the user using
userpage.php?user=s2xi
but the url parses as www.foo.bar/userpage.php?user=s2xi and not www.foo.bar/s2xi
and also tried this as a check to see if user exists (is there a better way?)
if($_GET['user'] != $_SESSION['username']){
header("Location: no_user.php");
}else{
//load page
}
I am using the Smarty template engine on my site and I have my 'themes' in directories that belong to members file
www.foo.bar/users/s2xi/themes
but i want www.foo.bar/s2xi to point to the persons profile page that is viewable by everyone else and not their accounts page.
You're missing the .php in your RewriteRule, if that's verbatim - eg, userpage? => userpage.php?.
However, you're going to run into some problems with this unless you're using a framework to help you distinguish between routes. If you switched to using a separate URI format for user pages (eg /user/foo) you wouldn't have conflicts; but as it stands currently, using .htaccess to rewrite your URLs in that format could potentially cause problems with many other parts of your app.
To do it with a separate URI format, change your last .htaccess line (the RewriteRule) to:
RewriteRule ^user/(.+)/?$ userpage.php?user=$1 [NC,L]
may want to consider adding QSA as well.