Liam
Liam

Reputation: 9855

Generate pages on the fly with PHP

I'm new to PHP and I'm curious as to how you generate pages on the fly?

I have a table of users that I'm pulling from my DB and displaying on my homepage and that I know I can pass their user ID as a POST variable to 'mysite.com/profilepage.php' and then have a query on that page that would pull all relevant information for that ID, but say I wanted the page to be 'mysite.com/user-profiles/john-doe.php' ?

Would this be done with a .htaccess file? Any help is greatly appreciated!

Upvotes: 1

Views: 1222

Answers (2)

Trevor North
Trevor North

Reputation: 2296

If you are new to PHP and havent looked at any frameworks, have a look at the agiletoolkit. It does some neat integration between jquery and php which will give you a nice look and feel to your pages. It also encourages you to use ModelViewController (MVC) to segregate the parts of your code that are for database access and functionality from those which are purely for web page layout.

The options for URL rewriting mentioned above are the same but when a user is logged in, you have access to the user information from $this->api->auth('xxx') where xxx is the column in the users table.

The framework takes a little bit of learning but so does PHP and it's easy to get into very bad habits writing PHP code which means as the websites get bigger, you will find it harder to maintain your code.

Upvotes: 1

KRyan
KRyan

Reputation: 7598

If you must have the page be called mysite.com/user-profiles/john-doe.php, you can use URL rewriting as mellamokb mentioned in the comment to change the URL to that.

But as far as PHP is concerned, the way to do this is to create a PHP page (I'm going to suggest user-profiles.php), and then pass usernames to it with either GET or POST. Assuming that you're only reading and that the information in question is public, GET seems fine and it's easier to explain here.

You access the relevant page (generated "on the fly" by PHP) by pointing your browser to user-profiles.php?username=John-Doe and including code like this in user-profiles.php:

if ( isset($_GET['username']) )
{
    $username = $_GET['username'];
    // you now know the passed username
}
else
{
    // some kind of error handling for when there is no username
}

You now know you have the relevant username within your PHP file, and can use it to create the page as you want it. You can also use URL rewriting to change user-profile.php?username=John-Doe to user-profiles/John-Doe if you like.

WARNING: Do not use $_GET if the page in question is either going to be modifying the database in any way, or if it's going to be getting private information from the database. It is not in any way secure. Please read up on PHP security before creating pages that do either of those things.

Upvotes: 1

Related Questions