I am running into the following issue:
Our members have a desire for personalized sites directly from our primary domain in the form of http://www.example.com/membername. I am looking at possibly solutions in two ways but neither are ideal (will be explained below).
Method 1 - ?Member=
In this method, I simply create a custom URL and store the information in the member's database profile. For example: if I want my "custom" URL to be jm4, for a consumer to visit my site, they must type in http://www.example.com?Member=jm4.
The site, of course, does a $_GET['Member'] to lookup the member information, stores the primary data in Session from the index page, then redirects to a homepage. The consumer no longer sees the membername in the URL but instead sees all the page names for www.example.com as if they simply visited the parent domain to start (each member's page has custom information however).
While this method works it presents the following problems:
The URL is not nearly as easy as /jm4
and any errors typing out the
wildcard ?Members= will result in
page error. Also, This method keeps
that particular member's information
in session (which is necessary
browing from page to page on that
particular member domain) and
prevents somebody from simply typing
http://www.example.com?Member=name2 to
visit another site without clearing
their session or closing the browser.
Method 2 - /membername
While the preferred method, currently the only way we know how to create is to manually generate an index file in a subfolder, redirect to the primary index then allow the consumer to view the member's personal site.
For example, if I visit www.example.com/jm4, I am hitting the /jm4 folder which contains index.php. Within this file simply contains:
<?php
session_start();
ob_start();
$_SESSION['AgentNumber'] = "779562";
header("Location: ../index.php");
exit;
?>
the primary index recognizes this with:
<?php
session_start();
ob_start();
if ($_SESSION['MemberNumber'] == NULL) {
header("Location:ac/");
exit;
}
$conn = mysql_connect("localhost", "USER", "PW");
mysql_select_db("DB",$conn);
$sql = "SELECT * FROM table WHERE MemberNumber = $_SESSION[MemberNumber]";
$result = mysql_query($sql, $conn) or die(mysql_error());
while ($newArray = mysql_fetch_array($result)) {
$_SESSION['MemberName'] = $newArray['MemberName'];
$_SESSION['MemberPhone'] = $newArray['MemberPhone'];
$_SESSION['MemberMobile'] = $newArray['MemberMobile'];
$_SESSION['MemberFax'] = $newArray['MemberFax'];
$_SESSION['MemberEmail'] = $newArray['MemberEmail'];
$_SESSION['MemberAddress'] = $newArray['MemberAddress'];
$_SESSION['MemberCity'] = $newArray['MemberCity'];
$_SESSION['MemberState'] = $newArray['MemberState'];
$_SESSION['MemberZip'] = $newArray['MemberZip'];
$_SESSION['MemberAltName'] = $newArray['MemberAltName'];
}
mysql_close($conn);
header("Location: home/");
exit;
?>
We would certainly prefer to use the second method in terms of 'ease' for the member but keep running into the following issues:
We are forced to manually create a
sub-folder and unique index.php file
for each new member we onboard
While the above probably could be
automated (when new member creates
profile, automatically generate php
file and folder) but this is more
complicated and we don't want to
have 3000 subfolders on the primary
domain.
Has anybody run into similar issues? If so, how did you go about solving it? What would you recommend based on my details above? Any advice is appreciated.
Also - using as subdomain (membername.example.com) is not preferred because our current SSL does not allow for wildcards.
EDIT 1 - EXISTING .HTACCESS FILE
My existing .htaccess file on the site looks like this for reference:
ErrorDocument 404 /404.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /?Member=$1 [L]
You can do your prefered method by just adding some lines to the .htaccess in your root directory:
This site should get you started
Or this one
If you are using apache, then you could use mod_rewrite to change urls like http://host/membername to http://host/memberpage.php?name=membername.
You could use this in a .htaccess file for your second method. It will rewrite http://yoursite.com/membername to http://yoursite.com/?Member=membername
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /?Member=$1 [L]
</IfModule>
Related
I know that similar questions were already asked, but i could not find any information for my specific "problem".
What i want to do is the following in a very dynamic way, which means that a "SuperUser" should be able to define new routes in a admin interface:
If a user enters http://www.example.com/nice-url/
he should get redirected to http://www.example.com/category.php?id=123 without changing the url.
Now there are a few ways i can achieve this. Either i use .htaccess like this:
RewriteEngine on
RewriteRule ^nice-url category.php?id=123 [L]
This works, but is not very dynamic. I would need to let a php script append new rules at the bottom which is not something i would like to do.
Or this:
.htaccess
FallbackResource /process.php
process.php
$path = ltrim($_SERVER['REQUEST_URI'], '/');
$elements = explode('/', $path);
if(count($elements) == 0) {
header("Location: http://www.example.com");
exit;
}
$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements));
$result = execQuery($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$target = $row['Target'];
header("Location: ".$target);
exit;
This also works, but sadly the url in the address bar gets changed. Is there a way in the middle of both? Having the flexibilty of PHP and the "silentness" of RewriteEngine? How do great CMS like joomla do it? Do they generate a htaccess file for each new page you create?
Thanks!
You can have this code in root .htaccess:
RewriteEngine on
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA]
PS: Note this will route /nice-url to /category.php?uri=nice-url. Then inside category.php you can dip into your database and translate $_GET['uri'] to id.
It would be more dynamic if you use regular expressions. That's how it works in CMS systems like Joomla. Good idea is to install Joomla with 'nice' URLs on and look over .htacces file to get to know how does it work.
You can start here:
http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
So I was thinking of a way to remove the parameters from url when page is downloaded to client and respond different in each different value of the get parameter.
Let me take it clearer for you. Say I have this url: www.abc.com/?q=jsdfnjns. Ideally, I am thinking of shortening this url with goo.gl and then send it to the customer. When customer clicks on it, it will automatically go to www.abc.com clean url and set a cookie to the client with the q's value. I have seen it before in many affiliate links except that the initial url had no get parameters but value was actually a sub-folder e.g www.abc.com/jsdfnjns
So what's the way to actually get the value of a get parameter and manipulate it with php, while removed from the url without user's notice, or setting a cookie when parameter is given as a sub-folder. I suspect it must be some htaccess rules and php tricks but can't find a way.
With given url www.abc.com/jsdfnjns how can i redirect immediately to www.abc.com
and have the jsdfnjns saved ideally server-side in apache or in a user cookie ?
Is there any way to make it also happen with actual get parameters too ?
And a schematic:
www.abc.com/jsdfnjns convert it to -> goo.gl/sjbjsb -> when clicked, user is going to www.abc.com but somehow i get the jsdfnjns and respond in the main page different.
Hope my question is well defined, any ideas will be appreciated.
Thanks.
Firstly you need to set .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?q=$1 [QSA,L]
</IfModule>
index.php code:
session_start();
if(isset($_REQUEST['q'])) {
$_SESSION['q'] = $_REQUEST['q'];
header('Location:index.php');
die();
}
else{
if(isset($_SESSION['q'])) $q = $_SESSION['q'];
else $q = null;
//YOUR CODE
var_dump($q);
}
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 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.
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.