Say I am rolling out a CMS. Each user gets their own page at domain.com/username/index.php. At the moment I'm considering having a new account create a folder at said location and make an index file like so:
<?php
$username=blahblah;
require("../indextemplate.php");
?>
Which would work fine. Everyone gets their own custom pages and such. What seems stupid to me is that I have to make identical folders and files for every unique user. Is there a way instead to catch people using a domain.com/username. And send them directly to indextemplate.php?
As I'm typing this I realized I might be able to use the 'that page does not exist' redirect that apache has in combination with $_SERVER["REQUEST_URI"] (not sure if the apache redirect will mess w/ the url) to go to the correct page.
I guess I'm asking then which approach is better (creating millions of folders/pages was the solution i found googling but it really seems worse). Is their a horrible downside to the second option? Or a third way perhaps.
Use a .htaccess file if you want to use these url redirects.
Basically the .htaccess could tell the server to treat example.com/user/Idiomatic as example.com/index.php?q=user&name=Idiomatic, then it's all php/mysql to load the data by these $_GET variables. This is used by many CMS'es like Drupal.
http://en.wikipedia.org/wiki/Rewrite_engine
Creating a new file each time is pointless, way to many files would be created.
May be,
<?php
$username=blahblah;
require("../indextemplate.php?username=".$username);
?>
And then, I guess you need use $_GET['username'] in your indextemplate script. Tray it!
Have a look at mod_rewrite.
For example, you have user.php:
$username = $_GET['username'];
require("../indextemplate.php");
Rewrite could be configured something like this:
RewriteEngine On
RewriteRule ^(\w+)/?$ user.php?username=$1 [L]
Related
This is probably a dumb question. I have a Web site that uses php and html with a bit of Javascript. I am trying to set it up so there are multiple landing pages. I think it would work if all the remaining .php files on the site were kept identical but there were separate index_a.php, index_b.php files, etc. The only problem is when the user clicks "Home" they of course get the root index.php. Is there a way to store the name (or some other indication) of what the user's landing page was for that session (using PHP session variables or I don't know what) and have the user directed to that page again when they click Home ?
Any help would be much appreciated (keeping in my mind I am a relative newby and any solution would need to be pretty simple and safe to load on a server). Any straightforward way way to do this ? It must be something that is fairly commonly required.
Short answer: yes
Smart answer: use a (mvc) framework of some kind which implements views and routes everything through a front controller.
Quick and dirty answer:
// anywhere
session_start();
$_SESSION['landing_page'] = 'landing-2.html';
// in your index.php
session_start();
include $_SESSION['landing_page'];
Note: if you use the code above, be sure the torn of the security gods will fall upon you.
I would like to know how to handle a problem which I guess is somewhat generic. But i am just not sure how it is supposed to be done. So hopefully people can find the way around what may be ill formed thoughts and bad terminology.
I did a tinyurl-like service just as an example, nothing which should be actually used. It's written in php and uses mysql. All well it's only one problem I couldn't really figure out, and I feel like I've run into this before.
The problem is when expanding the generated url (for simplicity let's assume that the base url is http://a.com and that the links are ordered by an auto-incremental index so i just give the database index when giving a tinified url.
For tinyurl a link would be for example: http://tinyurl/abcd
I however used a parameter and end up doing something like http://q.com?u=0
I guess that if I want to have a format like the first one I could set up .httaccess in my apache server to use a custom 404 page so when going to: http://a.com/0 I would actually get a 404, redirected to my own 404.php and in that page handle the database lookup and redirect to the real url.
My problem is that I just have this gut feeling that using 404 as a "feature" is a bit dirty. And my question is if this would be the general way to do it, or if there are some other ways which I just don't know about.
Sorry for the rant and thanks for any information!
You should have a look at mod_rewrite!
In your .htaccess File you could do something like this:
RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?u=$1
That might not be the best rule, but there are plenty tutorials out there!
I have a website where each person has his personal profile. I would like to have static URL like mywebsite/user1, mywebsite/user2, but actually I would remain in the same page and change the content dynamically. A reason is that when I open the site I ask to a database some data, and I don't want to ask it each time I change page.
I don't like url like mywebsite?user=1
Is there a solution?
Thank you
[EDIT better explenation]
I have a dynamic page that shows the user profile of my website. So the URL is something like http://mywebsite.me?user=2
but i would like to have a static link, like
http://mywebsite.me/user2name
Why I want this? Because it's easy to remember and write, and because i can change dynamically the content of the page, without asking each time data to my database (i need some shared info in all the pages. info are the same for all the pages)
Yes there are solutions to your problem!
The first solution is server dependend. I am a little unsure how this works on an IIS server but it's quiet simple in Apache. Apache can take directives from a file called .htaccess. The .htaccess file needs to be in the same folder as your active script to work. It also needs the directive AllowOverride All and the module mod_rewrite loaded in the main server configuration. If you have all this set up you need to edit your .htaccess file to contain the following
RewriteEngine on
RewriteRule ^mywebsite/([^/\.]+)/?$ index.php?user=$1 [L]
This will allow you to access mywebsite/index.php?user=12 with mywebsite/12.
A beginner guide to mod_rewrite.
You could also fake this with only PHP. It will not be as pretty as the previous example but it is doable. Also, take into concideration that you are working with user input so the data is to be concidered tainted. The user needs to access the script via mywebsite/index.php/user/12.
<?php
$request = $_SERVER['REQUEST_URI'];
$request = explode($request, '/'); // $request[0] will contain the name of the .php file
$user[$request[1]] = $request[2];
/* Do stuff with $user['user'] */
?>
These are the quickest way I know to acheive what you want.
First off, please familiarise yourself with the solution I have presented here: http://codeumbra.eu/how-to-make-a-blazing-fast-ajax-call-to-a-zend-framework-application
This does exactly what you propose: eliminates all the unnecessary database queries and executes only the one that's currently needed (in your case: fetch user data). If your application doesn't use Zend Framework, the principle remains the same regardless - you'll just have to open the database connection the way that is required by your application. Or just use PDO or whatever you're comfortable with.
Essentially, the method assumes you make an AJAX call to the site to fetch the data you want. It's easy in jQuery (example provided in the article mentioned above). You can replace the previous user's data with the requested one's using JavaScript as well on success (I hope you're familiar with AJAX; if not, please leave a comment and I will explain in more detail).
[EDIT]
Since you've explained in your edit that what you mean is URI rewriting, I can suggest implemensting a simple URI router. The basics behind how it works are described here: http://mingos.eu/2012/09/the-basics-of-uri-routing. You can make your router as complex or as simple as needed by your application.
The URL does not dictate whether or not you make a database call. Those are two separate issues. You typically set up your server so example.com/username is rewritten internally to example.com/user.php?id=username. You're still running PHP, the URL is just masking it. That's called pretty URLs, realized by URL rewriting.
If you want to avoid calling the database, cache your data. E.g. in the above user.php script, you generate a complete HTML page, then write it into a cache folder somewhere, then next time instead of generating the page again the script just outputs the contents of the already created page. Or you just cache the database data somewhere, but still generate the HTML anew every time.
You could write an actual HTML file to /username, so the web server will serve it directly without even bothering PHP. That's not typically what you want though, since it's hard to update/expire those files and you also typically want some dynamic content on there.
Select all from your database.
Then create file containing the scripts contents(index.php?user='s) for each one. set the file name to user_id/user_name you got from the SELECT statement.
This will create a page for each user in the present folder.
To avoid having to recreate 'static' pages, you could set a new column named say 'indexedyet' and change it to 1 on creating a file. You select only files which have this as 0. You could perform this via cronjob once a day or so.
This leaves you vulenderable to user data changes though, as they won't autmatically update. a tactic to use here is to update the static page on any editing.
Another, probably better (sorry not had enough coffee yet-) ideal would be to create a folder on a users registration. Make the index.php page tailored to them on registration and then anything like www.mysite.com/myuser will show their 'tailored version'. Again update the page on user updates.
I would be happy to provide examples depending on your approach.
My problem is not so easy to describe ... for me :-) so please be lenient towards me.
I have several ways to view a list. which means, there are some possibilities how to come to and create the view which displays my list. this wokrs well with parallel opend browser tabs and is desired though.
if I click on an item of my list I come to a detail-view of that item.
at this view I want to know from which type of list the link was "called". the first problem is, that the referrer will allways be the same and the second: I should not append a get variable to the url. (and it should not be a submitted form too)
if I store it to the session, I will overwrite my session param when working in a parallel tab as well.
what is the best way to still achive my goal, of knowing which mode the previous list was in.
You need to use something to differentiate one page from another, otherwise your server won't know what you're asking for.
You can POST your request: this will hide the URL parameters, but will hinder your back button functionality.
You can GET your request: this will make your URLs more "ugly" but you should be able to work around that by passing short, concise identifiers like www.example.com/listDetail?id=12
If you can set up mod_rewrite, then you can GET requests to a url like www.example.com/listDetails/12, and apache will rewrite the request behind the scenes to look more like www.example.com/listDetails?id=12 but the user will never see it -- they will just see the original, clean/friendly version.
You said you don't have access to the server configuration -- I assume this is because you are on a shared server? Most shared servers already have mod_rewrite installed. And while the apache vhost is typically the most appropriate place to put rewrite rules, they can also be put in a .htaccess file within any directory you want to control. (Sometimes the server configuration disables this, but usually on a shared host, it is enabled) Look into creating .htaccess files and how to use mod_rewrite
I'm writing an application that gets data from URLs, but I want to make it an option whether or not the user uses "clean" urls (ex: http://example.com/hello/world) or "dirty" urls (ex: http://example.com/?action=hello&sub=world).
What would be the best way to get variables form both URL schemes?
If your mod_rewrite has a rule like the following:
RewriteRule ^hello/world /?action=hello&sub=world [NC,L]
or, the more generalised:
// Assuming only lowercase letters in action & sub..
RewriteRule ^([a-z]+)/([a-z]+) /?action=$1&sub=$2 [NC,L]
then the same PHP script is being called, with the $_REQUEST variables available whichever way the user accesses the page (dirty or clean url).
We recently moved a large part of our site to clean urls (still supporting the older, "dirty" urls) and rules like the above meant we didn't have to rewrite any code that relied on $_REQUEST params, only the mod_rewrite rules.
Update
Mod_rewrite is an Apache module, but there are a number of options available for IIS also.
Whichever web server you decide to support, the mod_rewrite approach will likely result in the least amount of work for you. Without it, you'd likely have to create a load of files to mimic the structure of your clean urls, e.g. in your webserver root you'd create a directory hello, placing a file world into it, containing something like the following:
// Set the $_REQUEST params to mimic dirty url
$_REQUEST['action'] = 'hello';
$_REQUEST['sub'] = 'world';
// Include existing file so we don't need to re-do our logic
// (assuming index.php at web root)
include('../index.php');
As the number of parameters you wish to handle 'cleanly' increases, so will the number of directories and stub files you require, which will greatly increase your maintenance burden.
mod_rewrite is designed for exactly this sort of problem, and is now supported on IIS as well as Apache, so I'd strongly recommend going in that direction!
If you're application is running in Apache server, I would recommend the use of mod_rewrite.
Basically, you code your application to use "dirty" URLs inside. What I mean by this is that you can still use the "clean" URLs in the templates and such, but you use the "dirty" version when parsing the URL. Like, you're real and "diry" URL is www.domain.com/index.php?a=1&b=2, inside of your code you are still going to use $_GET['a'] and $_GET['b']. Then, with the power of mod_rewrite just make the URLs like www.domain.com/1/2/ point to the "dirty" URL. (this is just an example of how things can be done)
sounds like a pain, but i guess create a function that analyzes the URL for every request. First determine if it's "dirty" or "clean" URL. For that, I would first look for the presence of the question mark character and proceed from there (additional checking will obviously be requried). For the "dirty" URL, use PHP's normal Get method retrieval capabilities ($variable_name). For the "clean" one, I would use Regular Expressions. That would be the most flexible (and efficient) way to parse the URL and extract potential variables.
A quick and dirty way might be to simply check for GET variables. If there are any, it's dirty, if not, it's clean. Of course this depends on what exactly you mean by dirty URLs.