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.
Related
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.
The question is worded a bit strangely, but I couldn't figure out any other way. I'd like to know if there is a better model for doing this. Here's what I have now:
Say I'm editing a user on my application. I submit the form, and it POSTs to apply.php?ref=edituser. Then on apply.php, it has a large conditional to determine which settings are being submitted, based on the ref variable, at which point it runs that part of the script. If it succeeds or has an error, it uses header("Location: uedit.php") to return to the previous page, also setting $_SESSION['err'] with the error code. That page checks to see if the error code is set, and displays and unsets it if it is.
I feel like I might have too much in a single script. Any opinions on this?
Do multiple forms submit to it?
As a general rule a form doesn't submit to a model a form submits to a controller in the MVC structure. The controller then decides how it should handle everything. But if you comment everything well and don't think it is to much I wouldn't worry about it.
Depends on your style. Website I'm working on only uses 2 main php files. Only thing I would recommend is to make sure you comment well
The cons with this kind of system is like mentioned before, it can be hard to keep track of all code in a logic way.
An other con is that php is an interpreted language which means that the whole file need to be parsed on each run. That means that if you separate the code into different files instead of building a big one you will gain performance. But of course, if it is not to big it won't matter.
As the title says, is there another way to pass a variable from "current" page over to "next" (new HTTP request) page without using sessions/cookies/$_GET?
Well, I guess $_POST could be an option too, but the thing here is, that I want to pass this variable from already executed $_POST back to off-the-post environment page, but inbetween I'm having a redirect, to disallow reposting the same form.
In other words, basicly, I'm trying to "make" a seamless PRG, but sessions/cookies/$_GET is not an option.
And yes, I'm working with classes (hence the oop tag). Therefore maybe some kind of magic functions, or output control?
This has to work within PHP environment, no JavaScript or other non server side language.
I also have a bad feeling that it's impossible, but hopefully I'm wrong, and there is a solution.
Thanks in advance!
update no. 1
Basicly, I want to create a PRG with response.
Inside this $_POST I'm adding data to database. I want this response to hold information whether this database query has been successful or not. Kind of make this $_POST process almost invisible to the user. And yes, display a response with the result later on.
All of this happens in one method:
if($_POST){
// insertion
}else{
// display no-post environment, if response exists (therefore posted) display response too
}
Something like that...
Sessions is not an option because this is meant to be some kind of API.
update no. 2
Huh, let me rephrase the question a little. Well, it seems that I don't actually need to pass the variable over. What I want to do, is to have 2 different results after POST so on next page load I could know whether the actions in POST has been successful or not. So, what other options are out there without using sessions/cookies/$_GET to get this result?
Currently there is:
temporary database usage: a good option, but I'd like to see different options;
Since you're already using a database it seems like the easiest way to handle this would be to update some kind of temporary table with the information you want based on the post call, then on the page you're doing a header redirect to, read the information in that table. With the constraints you've placed on this (no GET, SESSION, Cookie or Javascript) you're not going to be able to maintain a variable when you redirect from one page to the next.
So leverage that database and take the work off of PHP. Initially I was going to suggest utilizing cURL but I don't think that will help here (though you may want to look it up if you're unfamiliar with it, as it might be what you're looking for)
HTTP is a stateless protocol; thus, there's not going to be an easy, built-in way to add state. That said, I think sessions are the best way to accomplish what you want to do. If what you're doing isn't in the browser, maybe try some sort of session key setup (like the Facebook platform uses).
Thanks everybody. (For some reason I couldn't up vote answers, so everyone wins today :] thanks again!)
Complete php and javascript novice here, apologize up front for anything half-witted.
I have a portion of a user's profile in which I'd like the user to be able to add additional items of the same thing, with slightly different conditions.
For example, let's say it's favorite books. A fieldset contains some checkboxes for genre and an input text box for the title of a book. After the user checks a genre and fills in a title, they can add the book to their set of favorite books and then have the option to add another. When done adding books, they move on to the next fieldset, complete the form and submit.
How is this done? And more-importantly, is it possible without javascript?
Without JS, I understand this probably entails a lot of reloading of the page to add the items, regardless I'm more confused about how the $_POST data is handled, both before and after the submit.
Sorry for such an open ended question, really just looking for someone to point me in the right direction, as searching for this topic proved to be a bit difficult.
Thanks.
Some Clarification
I'm trying to develop an application that is as independent of javascript as possible. In that sense, I don't know if it's possible to add the new items with PHP alone. My sense is the fieldset in question could have it's own submit button, the action of which POSTS to the page itself (no DB interaction, etc), and variables like $book_genre1, $book_title1 are populated in the page. Then, the "official" submit is sent later, which actually adds the POST data, which contains the books array, to the DB. But I don't know if that is a safe procedure or good logic to begin with.
In reply to the above answer, if that is exactly what you need since I seem to have a different idea.
You simply store each addition in an array stored inside a session variable, and in each page load, parse the data into readable html.
$_SESSION['form'][] = serialized_form_data;
On each load,
foreach ($_SESSION['form'] as $form) {
unserialize_data_and_create_html();
}
add_new_form_element();
I'm assuming you want to show the user already filled forms so he can deal with them as he wishes.
This is a better implementation than what I thought of earlier. I wanted to implement a db version.
Sorry for the delay. I can't comment since I'm mobile (js issues) so I decided to edit instead.
You can simply use the $_SESSION['form'] for your inserts.
A simple foreach will work as well. However, remember to sanitize each value properly before inserting it. That's the key.
If you use prepared statements with binding, you have the advantage of clean input as well as better database performance.
What you're really asking is how to persist information between POSTs of the same form. The most common and effective way of doing so is to just use the inputs on the form. If you have information that shouldn't be displayed then use hidden input elements for them.
Note that storing information in the form like this is not considered secure since it can be manipulated and/or forged, so the next option is to store it in the session; since it is server-side only the cookie/session ID needs to be protected. The values can then be retrieved from the session in PHP after the POST has occurred.
Before you submit a form...there is no data to handle. Once a form is submitted data then is sent to the server in the form of an array.
(From php.net/manual/en/reserved.variables.post.php):
$_POST = "An associative array of variables passed to the current script via the HTTP POST method."
So a user submits some data to the server. Now that data is available to your scripts for use: Populate a database, validate the values before doing "x", write HTML to the client, etc.
I like where #frosty is going with his approach. It does potentially send multiple requests to the server, but it's also a very straight forward approach. A completely server-side solution.
JavaScript or the jQuery Library would allow you to accomplish a similar result, and post to the server just once - by simply hiding/showing populated fields, writing additional fields to the form dynamically (eg: After completing "book #1" the user can click "Add another" and JS writes an identical set of form fields all referencing book #2). Obviously, this approach will get more involved than a straight PHP approach. And you'll need a backup plan if you want to allow users with JS disabled to participate.
I would suggest you use javascript to handle the user adding multiple items. Check out jQuery (http://www.jquery.com) which is a fantastic javascript library that will help you do lots of great dynamic things.
Then once you have all of the information from the user, just once it all at once to your php and save it. For information about to access and use $_POST or $_REQUEST, you'll need to check out some PHP tutorials or pick up a book. That's fairly basic PHP stuff and too large a topic for this thread.
I'm currently working on an in-house CMS and have come to a bit of a standstill. I'm trying to make it easy to paginate between pages of posts in a blog, and can't decide on how it should be tackled. The real problem only arises when I need to allow a user to choose how many results to display per page or the order to sort posts in.
My initial thought was to simply use a querystring: blog/?page=3&count=20&sort=date but I'm not sure whether this method will have adverse effects on SEO.
For example, is Google sensible enough to realise that blog/?page=3&count=20 is the same as blog/?count=20&page=3?
I then thought about using sessions, but again this does not solve the problem above, and possibly makes it worse as some users may not have cookies enabled.
Lastly, I'm already using mod_rewrite for some of the urls, would it be best to use a structure like this: blog/1/20/?
I could really do with some help/suggestions here, there doesn't seem to be a hard-and-fast way of paginating results.
Thanks in advance
As long as those query strings are present on the links on your site (via static, normal 'paging' links which are spiderable) there shouldn't be any adverse effects. If your paging happens via sessions, however, that could have an impact, as that's usually done via cookies or by a long query-string propagated session ID. As far as I know, the order of parameters does not matter, as long as they yield the same output from the server.
The simple GET query string paging method works nicely. Google does it too (e.g.: q=test&start=10&...), the point is to make sure everything is reachable via plain-vanilla anchors.
Avoid using querystrings if you plan your site to get crawled satisfactorily.
Instead, use mod_rewrite and queries like this:
blog/page:3/count:20/sort:date
That will make it more readable, while keeping querystrings out of the way.
Of course, you'll have to parse that before doing the actual query, but it's something fairly simple to do in PHP: using explode() you separate each part of the URI, then parse from there.
Consider not having the order of the parameters fixed, instead allow them to be swapped and omitted, which will give you more flexibility when building the links.
I have always done this with session variables that get set via ajax calls.
I set an onClick event for each column header, and wrap the contents of the page in a div, so I can replace it.
I don't want Google downloading 10 different versions of the same page anyway.
On your comment about session variables:
I then thought about using sessions, but again this does not solve the problem above, and possibly makes it worse as some users may not have cookies enabled.
Session variables are stored on the server and not the client, so disabling cookies does not affect session variables.
Session variables are probably the easiest and most reliable way to solve this problem if you want to avoid google duplication issues.