Generate pages on the fly with PHP - 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!

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.

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.

Related

Choosing between superglobals for navigation in admin section

I'm creating a custom admin page that will enable the client to navigate the content list and edit/delete/add items to and from database(myPhpAdmin) in PHP and I was wondering about the correct way to do it.
For the front-end part (non-admin pages) I used links to store variables in URL and then retrieve it using the $_GET superglobal, example: http://localhost/myWebsite/pages/products.php?***main_id=1***.
<?php
if(isset($_GET['main_id'])) {
$mainID = $_GET['main_id'];
getSubGroupsWithMainID($mainID);
}
?>
Now, I'm not really sure that should be visible in the admin section (or should it?), so my idea was to use the $_POST superglobal in a similar manner to retrieve the necessary query parameters. My only concern is that links or <a> tags can't really send the data into the $_POST.
I hope I was clear enough with the explanation of the problem.
Any help is much appreciated.
Thanks
This seems like a very general question (almost opinion-based), but if I understand you correctly, this is my advice:
If loading a script that is READing from the database, use $_GET.
If you want to incorporate permissions with regard to certain pages, you can associate your users' privileges with the page ids.
If loading a script that runs a CREATE/UPDATE/DELETE query, use $_POST.
p.s. There is no benefit in declaring $mainID. Just write getSubGroupsWithMainID($_GET['main_id']); inside of the if block.

retrieve user->ID from wordpress to aanother php site

I have a PHP application custom_appli in /var/www/httpdocs.
Wordpress is installed on the same server in /var/www/httpdocs/new_cms/wordpress.
I need to retrieve user->ID using SESSION of custom_appli.
I have tried to insert :
require( './new_cms/wp-snapshots/wp-blog-header.php' );
global $user;
$user = wp_get_current_user();
echo "ID :".$user->ID;
writing wp-load instead of wp-blog-header doesn't change anything no matter whether I use include or require_once.
Could you please give me a link or advice on how to obtain user from SESSION?
Thanks in advance
Details and info are sparse, but here's how I would do it (I know about 5 methods, these are the least painful):
As mentioned, wp_get_current_user() gets you close, but that is generally only usable on the page for the user as in "on load" only. So from the WP served page you can get user ID (and all other info) and the session and have something that is usable. There are many ways to use that data to solve your problem, not really smooth all the time. Session data is etherial, beware.
Another way to go about it is to use wp-load.php and wrap it in middleware. this script bootstraps WP and allows queries and similar in the "bootstrapped" wordpress environment providing the applications internal API. I would consider adding wp-load to custom_appli "in the right way" and use that as middleware between the 2 applications. You will still need to identify the user as in many cases.
Without more information it is hard to guide you, but I can tell by your needs and the code already in the post that you are setting up for possible problems with dependencies, possible name-spacing collisions($user is something that could bite you as a global), and a myriad of other ways to loose time. If custom_appli needs a user ID, send it the user from WP on page load or similar.
When/why do you need that info? What is the flow?
You can also traverse a lot via session ID info too (depending on configuration).
FWIW I have passed user information successfully from 2 freestanding applications on different servers, it was very hard to do correctly, but it is possible.
Update after clarification
As mentioned "wordpress-user and cusstom-appli have same users" is possibly a replication of functionality, specifically running 2 tables(?) or logic. Just some feedback.
Basically you are wanting to hook the "logged in" status of a WP user. I see no mention of:
FK/relationships built on user (easy but a little more work)
ACL/permission based access on custom appl
No serializing of data or similar to the WP user (user in general)
Any of the above might have me change the solution. Here is a pretty clean prototype I wrote for you that is about 15 lines of code.
It follows some code from wp and essentially:
Makes sure PHP session is initialized via the theme functions.php
Uses the WP login (authentication) success to add a var to the session
On logout unsets the var (!IMPORTANT!)
Also makes sure the session is set when not logged in or the key is not present
Is easy to pick up outside of WP via session (custom_appl.php)
I tested this and it worked fine locally on one of my installs, I don't see any reason why it would give you problems. I would harden this a little more, but this is only a prototype showing how to use the key tools in PHP and WP.
wp_get_current_user() is a function in wp-includes/pluggable.php, which is loaded by wp-settings.php. I'm not sure how exactly WordPress bootstraps itself but I'd try to include wp-settings.php if anything.

Can session variables be used to separate landing pages geographically?

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.

have different static url in dynamic page

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.

Creating a user change language script for a website

UPDATE!!
I am sorry for this post, the code I had written for this prior to posting wasnt working and I had run out of ideas, only to then have a 5 minute break and came back to it only to realise I had accidently changed the $_GET to a $_SESSION without realising and thus rendering the script useless :(
Lesson learnt? to have breaks now and again and look through my code efficiently before wasting stockoverflow's users time :)
I am looking to script into a site a language function, the site will have 3 language options; english, korean and brazilian.
I have tried building this from scratch for the past day, first using javascript/jquery/ajax with php and secondly with simple php $_GET.
I was hoping to succeed with the former attempt as I dont really want to mess about with the URL as im using mod re-write atm and cant be bothered to mess about re coding the new URL.
So what I am hoping for is some help in picking the best way in which to create a language system, remember I would rather not use URL $_GET if at all possible.
I would also like the users choice to remain as they navigate the site using php sessions which I have tried to use but have come unstuck.
I have not placed any code in this post as atm I am looking for some tutorials or some guides on how to do this. I may add code later if there is no solution.
Thank you in advance
Dan.
IMHO you should put this into the URL. If you select the language depending on a setting in a cookie or session data, it's very confusing, because the same URL will produce different contents, which is very bad for example when proxies cache your page or search engines index them.
The usuall way is to put the language in the path of the URL instead of a GET parameter (http://www.example.com/en/, http://www.example.com/ko/, http://www.example.com/pt/ or http://www.example.com/pt-BR/).
You can store selected language in the cookies or session. If you have any problems - don't hesitate to ask.

Categories