...

View Full Version : Using template for any content after user login



LearningCoder
10-22-2012, 07:39 PM
Hi, I have a site which is probably half way to being completed. I have created all my navigation pages and completed user registrations and logins.

What I wanted to do, is use only the 'membersarea.php' (which is the page they go to after logging in) to display any content, rather than having to recreate a new page for different data.

For instance, I'm trying to implement a profile feature and have an 'edit profile' link on the page. I want to show the user a form for example once they click the link, but I don't want to recreate a new page for this, I want to display everything all in my membersarea.php.

I want to use a template system but do not know how to implement it. I have my page, membersarea.php:



<?php
session_start();

$content = (isset($_GET['content'])) ? mysql_real_escape_string($_GET['content']) : file_get_contents("default_template.htm");

switch ($content) {
case 'edit': $content = file_get_contents("edit_profile.htm"); break;
case 'view': $content = file_get_contents("view_profile.htm"); break;
case 'uploads': $content = file_get_contents("user_uploads.htm"); break;
case 'new': $content = file_get_contents("new_upload.htm"); break;

default: $content = file_get_contents("default_template.htm");
}

$output = $content;

$page = $_SERVER['REQUEST_URI'];
$name = ucwords(str_replace(array(".php","_"),array(""," "),substr($page,strrpos($page, "/", -1)+1)));
$lower = strtolower($name);

if(!isset($_SESSION['username'])){
header("Location: index.php");
exit(0);
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo-Central <?php print $name; ?> Page</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript" src="javascripts/advert.js"></script>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<link rel="stylesheet" type="text/css" href="css/fontface.css" />
<link rel="stylesheet" type="text/css" href="css/menu.css" />
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico" />
</head>
<body onload="window_onload()">

<?php require("header_include.php"); ?>

<div id="content">
<p id="welcome_member">Welcome,
<span id="member"><?php echo $_SESSION['username'];?></span>
<span id="logout"><a href="logout.php">Logout</a></span>
</p>
<hr id="welcome_hr" noshade="noshade" />

<?php print($output);?>

</div>

<?php require("footer_include.php"); ?>

</body>
</html>



As you can see from the switch statement, I also have different files which contain just plain html which I would like to load into the membersarea.php page when they perform a certain action.

This is my default_template.htm, which is the first template the user sees when they login:



<div id="profile_div">
<a href='membersarea.php?content=edit'>
<img src="images/outline.png" alt="Profile" name="Profile" id="profile_pic" border="0" />
</a>
</div>

<div id="memberInfoDiv">
<div id="date_div"></div>

<a href="#">View your profile.</a>
<a href="#">View your uploaded files.</a>
<a href="#">Upload a new file.</a>

</div>

<div id="game_updates">
<h3>Game Updates</h3>
</div>

<div id="games_files_div">
<h3>Files</h3>
</div>


As you can see from the first link on the page within the profile_div div when that link is clicked I pass in the value 'edit' through the url which is used in the switch statement to determine what to display. This works and loads in my form (which is located in edit_profile.htm), but I'm just not sure if I am doing the whole template thing correctly. I had issues with my form processing.

Would I process the form data within the edit_profile.htm page or in the membersarea.php page?

I also had issues styling the form, tried adding a stylesheet link in both of the pages but the form still didn't get styled.

Just looking for some advice or criticism of my code to help put me in the right direction.

Thanks in advance!

Kind regards,

LC.

tangoforce
10-22-2012, 08:02 PM
I had issues with my form processing.

Would I process the form data within the edit_profile.htm page or in the membersarea.php page?

Keep all your php logic together. That would mean you process the form data in your membersarea.php page NOT in the edit_profile.htm page.

In your form, place a hidden field call it content (like you pass via the url) and call it something like process_edit. Check for it in your switch. Inside that part of your switch, process it and then grab the html page you want to output after you've finished.



I also had issues styling the form, tried adding a stylesheet link in both of the pages but the form still didn't get styled.


Can't help with that I'm afraid, my client side design is seriously erm.. :o :D

LearningCoder
10-22-2012, 08:20 PM
Keep all your php logic together. That would mean you process the form data in your membersarea.php page NOT in the edit_profile.htm page.

Ah I just ran an isset() in my membersarea.php after submitting the form and it echo'd out the value ok. I did try it last night in both files, I think I got confused with the error, it seems to 'hide' other links on the page when it echo'ds out. I think it's because it moves my content down a line. My bad, thanks anyway.



In your form, place a hidden field call it content (like you pass via the url) and call it something like process_edit.

Not quite sure what you mean dude, do you mean create the <__content__> tag like you showed me before or do you mean <input type="hidden" name="content" value="process_edit" />?



Check for it in your switch. Inside that part of your switch, process it and then grab the html page you want to output after you've finished.


I process the form data inside my switch? I like to keep switch statements simple so could I set a variable to true for example and then break out of the switch, check if the variable was set to true and then process from there?



Can't help with that I'm afraid, my client side design is seriously erm.. :o :D

Haha I remember you saying :p Well you make up for it with your php knowledge! ;)

Kind regards,

LC.

tangoforce
10-22-2012, 09:38 PM
Not quite sure what you mean dude, do you mean create the <__content__> tag like you showed me before or do you mean <input type="hidden" name="content" value="process_edit" />?

I said to use a hidden form field. I said nothing about a tag So.. in your form you use a hidden form input. That means the second version of what you asked - <input type="hidden" etc.



I process the form data inside my switch? I like to keep switch statements simple so could I set a variable to true for example and then break out of the switch, check if the variable was set to true and then process from there?

I would personally run the processing code inside the switch. There's not much point using a boolean to escape it because any part of your switch could use it and then the following code would be testing that boolean to see if its true and not knowing what to do next. Thats the whole point of a switch.. you determine what you are supposed to be doing and then doing it there.

Look:



$Mode = $_REQUEST['mode'];

switch($Mode)
{
case 'test':
$Break = true;
break;
case 'this':
$Break = true;
break;
}

//Now what do I do with $Break? - Which part of the switch set the boolean?
//This would not work because you wouldn't know.


//Therefore use the switch as its intended like this:

switch($Mode)
{
case 'test':
//Do something here
break;
case 'this':
//Do something here
break;
}

LearningCoder
10-23-2012, 02:04 PM
Ok thank you for that, I will take your advice and process the data inside the switch.

Getting an error with the $_REQUEST['mode'] line of code. Telling me 'mode' is an undefined index. I tried to research the $_REQUEST as I've never used it, php.net doesn't really give any detail about the keys which can be used. For example, the $_SERVER superglobal can use $_SERVER['REQUEST_METHOD'] and on php.net it gives a list of the different keys which can be used with the superglobal but with REQUEST it gives no information apart from that it contains an associative array of the contents of $_GET,$_POST and $_COOKIE. But on first login, nothing is sent with $_GET which I think is why I'm getting the error.

When I click on the edit profile link, the error goes away but on first logging in, it shows that error above. What I am thinking is that because nothing was sent through the URL when first logging in, $_REQUEST will contain nothing. I tried modifying my code to this:


$content = (isset($_REQUEST['mode'])) ? mysql_real_escape_string($_REQUEST['mode']) : file_get_contents('default_template.htm');


This got rid of the error message when I first login, but now when I click the edit profile link, it goes to membersarea.php with the default content still showing, rather than loading in the form.

Not really sure what I'm doing wrong. Kinda hard to know when I can't find any information about what 'mode' does.

Hope you can shed some light for me.

Kind regards,

LC.

tangoforce
10-23-2012, 02:32 PM
$_REQUEST['mode'] was an example.

$_REQUEST is basically an array full of $_GET and $_POST data together. It would be the same as this:

$_REQUEST = $_GET + $_POST;

mode is array index I use in my own scripts so I just chucked it into my demo for good measure. The reality is that you set the index to whatever you've used - in your case the word content as that is what you are passing in your url so you'd be wise to use it in your form too as the name of the hidden element.

Don't get too comfy using $_REQUEST though, there are security implications (alledgedly) so you should keep its usage to a minimum however I've always accepted $_REQUEST all over my site with no issues. It's more to do with XSS attacks where an attacker could submit form data by get instead of post (as I understand it anyway) but then a hidden form and javascript could send post data so to me it makes no difference anyway.

So to reaffirm..


$content = $_REQUEST['content'];

switch($content)

should do the trick.

Why did I call it mode? Because that is the mode that the code is running in - edit, delete, etc. Content is what you output to the user :thumbsup:

LearningCoder
10-23-2012, 03:13 PM
Ah I see what you mean so for instance if multiple variables were passed with $_GET, the $_REQUEST array would look like so: ?


Array (
$_REQUEST['content'] = value1;
$_REQUEST['2ndvar'] = value 2;
)

I've used the ternary operators again to determine whether anything was sent and if it wasn't I set $mode to an empty string to ensure the default case statement executes on first logging in.



$mode = (isset($_REQUEST['content'])) ? mysql_real_escape_string($_REQUEST['content']) : "";


This gets rid of the error message. I'm just trying to work out the logic with my code.

Here is my processing code in membersarea.php:


<?php
session_start();

$mode = (isset($_REQUEST['content'])) ? mysql_real_escape_string($_REQUEST['content']) : "";

switch ($mode) {
case 'edit': $mode = file_get_contents("edit_profile.htm"); break;
case 'view': $mode = file_get_contents("view_profile.htm"); break;
case 'uploads': $mode = file_get_contents("user_uploads.htm"); break;
case 'new': $mode = file_get_contents("new_upload.htm"); break;

default: $mode = file_get_contents("default_template.htm");
}

$output = $mode;

$page = $_SERVER['REQUEST_URI'];
$name = ucwords(str_replace(array(".php","_"),array(""," "),substr($page,strrpos($page, "/", -1)+1)));
$lower = strtolower($name);

if(!isset($_SESSION['username'])){
header("Location: index.php");
exit(0);
}

?>


So, on first logging in, my default case inside the switch will execute and output the default content. I then click the edit profile link which sends the value 'edit' through the link, which then executes my first case statement, thus grabbing the contents of the file, breaking out of the switch and outputting the file contents to the page. I would then fill the form in and submit, consequently sending all $_POST data and saving it into $mode via $_REQUEST statement.

Here is where I am stuck. Let's say i have 3 fields whose data were sent, those inputs would all have different names, so when trying to access them in my script, at which point would I do it? I know you've said inside the switch but it doesn't seem right for me. I realize it will also be sending the hidden field value, which will be 'content' which would have the value 'edit'. Again my membersarea.php page will run, the switch will execute and go into the first case, but it again uses file_get_contents().

Am I totally on the wrong track? I'm not sure if I'm over complicating this or what...

i know this is straightforward to some people but this is really pecking my head. Once I know how though, I've got it forever!

Kind regards,

LC.

tangoforce
10-23-2012, 03:52 PM
Ah I see what you mean so for instance if multiple variables were passed with $_GET, the $_REQUEST array would look like so: ?


Array (
$_REQUEST['content'] = value1;
$_REQUEST['2ndvar'] = value 2;
)


Yes. It will be the same as a $_GET array or $_POST array but combined.



I've used the ternary operators again to determine whether anything was sent and if it wasn't I set $mode to an empty string to ensure the default case statement executes on first logging in.



$mode = (isset($_REQUEST['content'])) ? mysql_real_escape_string($_REQUEST['content']) : "";



Ok thats good.



Here is my processing code in membersarea.php:


<?php
session_start();

$mode = (isset($_REQUEST['content'])) ? mysql_real_escape_string($_REQUEST['content']) : "";

switch ($mode) {
case 'edit': $mode = file_get_contents("edit_profile.htm"); break;
case 'view': $mode = file_get_contents("view_profile.htm"); break;
case 'uploads': $mode = file_get_contents("user_uploads.htm"); break;
case 'new': $mode = file_get_contents("new_upload.htm"); break;

default: $mode = file_get_contents("default_template.htm");
}

$output = $mode;

$page = $_SERVER['REQUEST_URI'];
$name = ucwords(str_replace(array(".php","_"),array(""," "),substr($page,strrpos($page, "/", -1)+1)));
$lower = strtolower($name);

if(!isset($_SESSION['username'])){
header("Location: index.php");
exit(0);
}

?>


Why are you changing the $mode variable in every part of your switch only to change it to $output later? - Just use the $output variable inside your switch parts instead.



Here is where I am stuck. Let's say i have 3 fields whose data were sent, those inputs would all have different names, so when trying to access them in my script, at which point would I do it? I know you've said inside the switch but it doesn't seem right for me.

Two things:
1) There is often no 'right' way of doing many things in code because they can be done several different ways. Often however its a case of finding the best and nost efficient way in your situation.

2) I think the way you have structured your switch puts you off processing anything inside it.

This is what you've done:



switch ($mode) {
case 'edit': $mode = file_get_contents("edit_profile.htm"); break;
case 'view': $mode = file_get_contents("view_profile.htm"); break;
case 'uploads': $mode = file_get_contents("user_uploads.htm"); break;
case 'new': $mode = file_get_contents("new_upload.htm"); break;

default: $mode = file_get_contents("default_template.htm");
}


Now, this is what I would do:



switch ($mode)
{
case 'edit':
$output = file_get_contents("edit_profile.htm");
change_details(); //Demo function - not real
do_something_else();// More demo
update_db();//Another line of example code
break;
case 'view':
$output = file_get_contents("view_profile.htm");
update_db_hit_counter();//Another demo line - function not real
break;
case 'uploads':
$output = file_get_contents("user_uploads.htm");
update_db_hit_counter();//Another demo line - function not real

//Some more junk / maths / processing calculations
$a = 224;
$b = 430;
$Answer = ($a * $b) * 112;

//Do some more stuff here - add some VAT
$Answer = ($Answer * 0.2);

$Accept_multiple_lines_of_processing_code_inside_switches = true;
break;
case 'new':
$output = file_get_contents("new_upload.htm");
update_db_hit_counter();//Another demo line - function not real
break;

default:
$output = file_get_contents("default_template.htm");
update_db_hit_counter();//Another demo line - function not real
}


Do you see what I've done? - I've restructured the way you were laying out your switch. Now each part of the switch can operate over multiple lines and adding more lines in there looks and feels more natural because there is no break; at the end of the only line. Thats what I do with all of my code that uses switches. I've never once put it all on one line like you have because that way you're playing a trick on your mind that makes you think you can only have one line of code there. It's all psychological.



I realize it will also be sending the hidden field value, which will be 'content' which would have the value 'edit'. Again my membersarea.php page will run, the switch will execute and go into the first case, but it again uses file_get_contents().

Nothing wrong with using file_get_contents(). It does a job of reading a file into a string and thats what you want. It's doubts like that which hold you back. It does what it does and thats what you want it to do so use it!



Am I totally on the wrong track?

Kind of.. you need to learn to accept new methods of doing things. The switch thing felt wrong to you because of the way you've laid it out yet I clearly told you that was the way forward. It's ok to question things for a further explanation but if you don't understand them, sometimes the best way is to follow the advice and just try it. Only then can you see how things work that have been advised to you.



I'm not sure if I'm over complicating this or what...


No not really its just learners nerves.

LearningCoder
10-23-2012, 04:10 PM
Now, this is what I would do:



switch ($mode)
{
case 'edit':
$output = file_get_contents("edit_profile.htm");
change_details(); //Demo function - not real
do_something_else();// More demo
update_db();//Another line of example code
break;
case 'view':
$output = file_get_contents("view_profile.htm");
update_db_hit_counter();//Another demo line - function not real
break;
case 'uploads':
$output = file_get_contents("user_uploads.htm");
update_db_hit_counter();//Another demo line - function not real

//Some more junk / maths / processing calculations
$a = 224;
$b = 430;
$Answer = ($a * $b) * 112;

//Do some more stuff here - add some VAT
$Answer = ($Answer * 0.2);

$Accept_multiple_lines_of_processing_code_inside_switches = true;
break;
case 'new':
$output = file_get_contents("new_upload.htm");
update_db_hit_counter();//Another demo line - function not real
break;

default:
$output = file_get_contents("default_template.htm");
update_db_hit_counter();//Another demo line - function not real
}


Do you see what I've done? - I've restructured the way you were laying out your switch. Now each part of the switch can operate over multiple lines and adding more lines in there looks and feels more natural because there is no break; at the end of the only line. Thats what I do with all of my code that uses switches. I've never once put it all on one line like you have because that way you're playing a trick on your mind that makes you think you can only have one line of code there. It's all psychological.

I see, this does look better. I'll re-format the switch after this post!



Nothing wrong with using file_get_contents(). It does a job of reading a file into a string and thats what you want. It's doubts like that which hold you back. It does what it does and thats what you want it to do so use it!


I just didn't know if reading the file again is what I wanted because it will eventually output the form again, after processing the code which is not ideally what I wanted.



Kind of.. you need to learn to accept new methods of doing things. The switch thing felt wrong to you because of the way you've laid it out yet I clearly told you that was the way forward. It's ok to question things for a further explanation but if you don't understand them, sometimes the best way is to follow the advice and just try it. Only then can you see how things work that have been advised to you.

No not really its just learners nerves.

Thanks for the guidance, I notice in your switch you're using imaginary functions. Are you hinting that I should create different functions to perform different tasks, or would you process the data actually inside the case like:



switch ($variable){
case 'blabla':
file_get_contents("edit_profile.htm");

//process the form data, for instance:

$name = $_REQUEST['firstname'];
//etc etc
break;
}


Kind regards,

LC.

tangoforce
10-23-2012, 04:41 PM
I just didn't know if reading the file again is what I wanted because it will eventually output the form again, after processing the code which is not ideally what I wanted.

You can output whatever you want. You don't have to output the form again, you can just output the default file instead if you want. Thats the beauty of using file_get_contents(), you can grab whatever file you want and output it.



Thanks for the guidance, I notice in your switch you're using imaginary functions. Are you hinting that I should create different functions to perform different tasks, or would you process the data actually inside the case like:



switch ($variable){
case 'blabla':
file_get_contents("edit_profile.htm");

//process the form data, for instance:

$name = $_REQUEST['firstname'];
//etc etc
break;
}


No I wasn't suggesting you use your own functions but you can do that if you want to make it look cleaner. I wasn't intentionally suggesting it but accidentally i have done just that OR you can just process it there and then without the use of functions. Thats the whole point.. as long as you do *something* inside that part of the switch it doesn't really matter how you do it as long as it gets done :thumbsup:

In some of my php scripts I have switches that reach over 1000 lines all handling different things. Some bits process the code right there, others call functions that I've written. At the end of the day its getting the job done that counts. As long as the logic is there (in this case using a switch to handle different modes) you'll be ok.

LearningCoder
10-23-2012, 11:04 PM
You can output whatever you want. You don't have to output the form again, you can just output the default file instead if you want. Thats the beauty of using file_get_contents(), you can grab whatever file you want and output it.

So let's say I submit the form and my membersarea.php page runs again, goes into switch and gets the 'edit_profile.htm' page with file_get_contents() again. After processing the data inside the switch, can I use file_get_contents() again to grab the contents of my default_template.htm and send that to my $output variable so that it can be printed later?

For example:


switch ($variable){
case 'blabla':
file_get_contents("edit_profile.htm");

//process the form data, after this use file_get_contents() once more:
$output = file_get_contents("default_template.htm");

break;
}


Then output that below as I have done in my html? Just want to be absolutely clear before going and writing this. :)



No I wasn't suggesting you use your own functions but you can do that if you want to make it look cleaner. I wasn't intentionally suggesting it but accidentally i have done just that OR you can just process it there and then without the use of functions. Thats the whole point.. as long as you do *something* inside that part of the switch it doesn't really matter how you do it as long as it gets done :thumbsup:

Ah ok thank you. Considering your reply, I think I will create different functions for different tasks and just call them within the switch. I think that looks a lot neater than having a lot of lines in there.

That leads me to a question actually, is it good practice to use if/if else statements inside a switch or should that be avoided?



In some of my php scripts I have switches that reach over 1000 lines all handling different things. Some bits process the code right there, others call functions that I've written. At the end of the day its getting the job done that counts. As long as the logic is there (in this case using a switch to handle different modes) you'll be ok.

Wow, my whole scripts have never reached 1000 lines, let alone just a switch statement :p. I take your points on board though and will process all the data within my switch.

Another question popped into my head.....Is it good practice to use $_POST data within a function? I remember when I first started studying PHP and forms, I had an issue and someone advised me not to use my $_POST data inside a function because it is accessible in all scripts, so to use the data at global level. What are your recommendations?

Kind regards,

LC.:thumbsup:

tangoforce
10-24-2012, 12:29 AM
So let's say I submit the form and my membersarea.php page runs again, goes into switch and gets the 'edit_profile.htm' page with file_get_contents() again. After processing the data inside the switch, can I use file_get_contents() again to grab the contents of my default_template.htm and send that to my $output variable so that it can be printed later?

For example:


switch ($variable){
case 'blabla':
file_get_contents("edit_profile.htm");

//process the form data, after this use file_get_contents() once more:
$output = file_get_contents("default_template.htm");

break;
}



You can.. but why would you want to use it twice in one switch section? :confused: - You might just as well not bother with the first one if its not going to be used.



That leads me to a question actually, is it good practice to use if/if else statements inside a switch or should that be avoided?

Why would it be bad practice?

if/else does a job just like any other piece of code. If you need to use it somewhere then you need to use it - that includes inside blocks of code in switch sections :thumbsup:



Wow, my whole scripts have never reached 1000 lines, let alone just a switch statement

Once you're confident in what you're doing it won't take you long.. :D



Another question popped into my head.....Is it good practice to use $_POST data within a function? I remember when I first started studying PHP and forms, I had an issue and someone advised me not to use my $_POST data inside a function because it is accessible in all scripts, so to use the data at global level.

Different coders have different attitudes towards different aspects of coding.

Personally it wouldn't worry me. $_POST is a superglobal meaning it can be used inside functions without needing to declare it as a global. That said, if you call that function from another part of your program that has no $_POST data available then your function will crash purely because the $_POST array doesn't exist (unless you test using isset() in your function and act accordingly).

What that person meant by available in all scripts is a bit confusing and I'm not sure if you're actually describing what you were told in the same detail to be honest. Yes its true that any script that shares your included functions file will also have access to that function however as long as your code and logic is structured correctly there shouldn't be an issue hence I think you've only told me half the story of what this other coder mentioned.

LearningCoder
10-24-2012, 01:26 AM
You can.. but why would you want to use it twice in one switch section? :confused: - You might just as well not bother with the first one if its not going to be used.

Like I said, when I submit the data, the switch is going to re-enter the 'edit' case (because the hidden field has this value), so it will end up grabbing the form file contents again but I wanted to output the 'default_template.htm' after they update thier profile. Should I change the value of the hidden form field to something like 'process_data' and create a new case to deal with it?



Different coders have different attitudes towards different aspects of coding.

Personally it wouldn't worry me. $_POST is a superglobal meaning it can be used inside functions without needing to declare it as a global. That said, if you call that function from another part of your program that has no $_POST data available then your function will crash purely because the $_POST array doesn't exist (unless you test using isset() in your function and act accordingly).


Ah ok I'll process it all in a function then to save readability!



What that person meant by available in all scripts is a bit confusing and I'm not sure if you're actually describing what you were told in the same detail to be honest. Yes its true that any script that shares your included functions file will also have access to that function however as long as your code and logic is structured correctly there shouldn't be an issue hence I think you've only told me half the story of what this other coder mentioned.

To be honest it was quite a while ago and at that point, I was really new to the idea of getting $_POST data and stuff so I didn't really understand his explanation. I'd have to re-read the topic.

Thanks for your help, just spent a bit of time styling my form and deciding what fields to use.

Will get on with the processing now. I'll have to go over Fou's explanation of the table relationships because I currently haven't created any tables to deal with profiling.

Kind regards,

LC.:thumbsup:

tangoforce
10-24-2012, 02:52 AM
Like I said, when I submit the data, the switch is going to re-enter the 'edit' case(because the hidden field has this value) , so it will end up grabbing the form file contents again but I wanted to output the 'default_template.htm' after they update thier profile. Should I change the value of the hidden form field to something like 'process_data' and create a new case to deal with it?

Right I see what you mean.. you're intending to use the edit part of your switch to output the form AND process it right?

In that hidden form field, what do you think might happen if you give it a different name like 'edsub' (edit submission) and create a nice new switch section with the same value to handle it?

I'll tell you.. Your code will be a lot easier and you'll only need one file_get_contents() in each part.

Just to demo that..



switch(mode)
{
case 'edit':
$output = file_get_contents('edit-form.htm');
break;
case 'edsub':
//Process details
process(); //Fake function - demo only

//Output something different
$output = file_get_contents('confirm.htm');
break;
}


See what I'm doing? - The switch can have a different section for everything. No need for multiple file_get_contents() calls, overwriting variables etc.

LearningCoder
10-24-2012, 10:57 AM
Ah, that is the answer I was looking for :p

I started coding it last night, gave the hidden form field a name of process_edit then created a new case for it.

Working great now. I just need to process the form data and eventually insert it into the database.

Here is what I came up with (pretty much the same as what you typed above):



<?php
session_start();

function process_form_data(){

if (isset($_POST['firstname'],$_POST['location'],$_POST['age'],$_POST['gender'],$_POST['hobbies'],$_POST['favgames'])) {

$no_value = (empty($_POST['firstname']) &&
empty($_POST['location']) &&
empty($_POST['age']) &&
empty($_POST['gender']) &&
empty($_POST['hobbies']) &&
empty($_POST['favgames'])
) ? FALSE : TRUE;
}

if (!$no_value) return; //if all those indexes are empty, no need to carry on processing data which doesnt exist, so return.
}

$mode = (isset($_REQUEST['content'])) ? mysql_real_escape_string($_REQUEST['content']) : "";

switch ($mode) {
case 'edit':
$output = file_get_contents("edit_profile.htm");
break;

case 'process_edit':
process_form_data();
$output = file_get_contents("default_template.htm");
break;
case 'view':
$output = file_get_contents("view_profile.htm");
break;

case 'uploads': $output = file_get_contents("user_uploads.htm"); break;
case 'new': $output = file_get_contents("new_upload.htm"); break;

default: $output = file_get_contents("default_template.htm");
}

$page = $_SERVER['REQUEST_URI'];
$name = ucwords(str_replace(array(".php","_"),array(""," "),substr($page,strrpos($page, "/", -1)+1)));
$lower = strtolower($name);

if(!isset($_SESSION['username'])){
header("Location: index.php");
exit(0);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo-Central <?php print $name; ?> Page</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript" src="javascripts/advert.js"></script>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<link rel="stylesheet" type="text/css" href="css/fontface.css" />
<link rel="stylesheet" type="text/css" href="css/menu.css" />
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico" />
</head>
<body onload="window_onload()">

<?php require("header_include.php"); ?>

<div id="content">
<p id="welcome_member">Welcome,
<span id="member"><?php echo $_SESSION['username'];?></span>
<span id="logout"><a href="logout.php">Logout</a></span>
</p>
<hr id="welcome_hr" noshade="noshade" />

<div id="profile_div">
<a href="membersarea.php?content=edit">
<img src="images/outline.png" alt="Profile" name="Profile" id="profile_pic" border="0" />
</a>
</div>

<div id="memberInfoDiv">
<div id="date_div"></div>

<a href="membersarea.php?content=view">View your profile.</a>
<a href="uploads">View your uploaded files.</a>
<a href="new">Upload a new file.</a>

</div>

<?php print($output);?>

</div>

<?php require("footer_include.php"); ?>

</body>
</html>



I was thinking to just use that function to check which inputs are empty and then return the list of the fields which actually have values (seeing as though none of the form fields are 'required', I just want to use the variables which have values, note the function isn't finished yet!). Not sure if I should carry on processing within the function as I don't feel I am making much use out of it.

Busy today but as soon as I get on tonight I'm gonna give this a good push and try to complete the processing of the profile's and being able to access your own profile and eventually I want to give the users the ability to view other members profiles. That's another issue altogether though..

Another question I've just thought of. When you create mysql table fields, should the 'length/values' column be set to whatever length the input is set to? For example, if I have a <input name="firstname" size="32" maxlength="32" />, should I then set that table column to first_name->varchar(32)?

Thanks for the assistance! :thumbsup:

Kind regards,

LC.

tangoforce
10-24-2012, 01:06 PM
I'm not even sure you'll be able to read my reply as the forum seems to have developed a bug over the last 12 hours or so.. currently I can't read page two of this topic as it just takes me back to page one :eek:



Another question I've just thought of. When you create mysql table fields, should the 'length/values' column be set to whatever length the input is set to? For example, if I have a <input name="firstname" size="32" maxlength="32" />, should I then set that table column to first_name->varchar(32)?


If the column in youjr table is varchar then yes you might as well do that. Just remember to put something on your page saying that the name field has a maximum length and then check it in your processing code to be sure its not longer than it.

tangoforce
10-24-2012, 01:16 PM
Ok now I can read my post and it is apparently the first one on page two. That must mean that the delete code for the forum has been tinkered with somehow because its not deleting everything when a mod deletes a post.

Whoops!

LearningCoder
10-24-2012, 09:24 PM
If the column in your table is varchar then yes you might as well do that. Just remember to put something on your page saying that the name field has a maximum length and then check it in your processing code to be sure its not longer than it.

Is there any need to check it because setting the maxlength attribute of the form only allows users to enter that amount of characters right? When I was testing input in my first attempt at this site, I remember copying about 100 characters of text and copy and pasted it into the text field and it accepted all of the characters rather than only entering the maxlength amount. I suppose it wouldn't hurt to check that though.

Just making a brew and I will crack on with the rest of it! Looking to be somewhat ahead by the early hours!

Thanks for the reply, I will carry on with the processing, I created the table this morning and now that you have confirmed the length/value issue, I believe I have everything I need.

Regards,

LC. :thumbsup:

LearningCoder
10-25-2012, 12:15 AM
Knew I'd be back before the end of the night! :(

Just created this function:

//FUNCTION WHICH FILTERS ANY KEYS WITHOUT A VALUE. CHECKS TO SEE IF ANY POSSIBLE USER INPUT FIELDS WERE STILL EXISTENT. RETURNS A STRING OF 'FALSE'
//IF USER DIDN'T ENTER ANY DATA. IF USER ENTERED DATA, WE NEED TO GET RID OF UNNECESSARY KEYS SUCH AS 'content' AND 'submit' AS WE DO NOT NEED
//TO USE THEM IN ANY OTHER PART OF THE SCRIPT. RETURNS A STRING OF 'true' if THE USER ENTERED DATA.
function filter_keys(){

$_REQUEST = array_filter($_REQUEST);

if (!array_key_exists("firstname", $_REQUEST) && !array_key_exists("location", $_REQUEST) && !array_key_exists("age", $_REQUEST) &&
!array_key_exists("gender", $_REQUEST) && !array_key_exists("hobbies", $_REQUEST) && !array_key_exists("favgames", $_REQUEST))
{
return "false"; //if those keys do not exist, user entered no data. return false
}
else
{
//if the user wanted to update something, get rid of 'content' and 'submit' keys as they are not needed anymore.
//Because 'content' is my first form field and submit is my last, we can use these array functions.
array_pop($_REQUEST);
array_shift($_REQUEST);
return "true";//return true if keys are left within the $_REQUEST array.
}

}


As you can see I filter the $_REQUEST array which only returns the keys which have values. I then check to see if any of the user controlled input fields were filled out (checks if them certain array keys do not exist). If none of the user controlled fields exists, then they didn't enter any data into any of the form, so we return false, and do nothing, just output the default_template.htm template as usual. If any of those keys do exist, we use array_shift() to delete the first key of the array (which is 'content') and the last key of the array (which is 'submit') as we will not be needing these at any other point in the remaining script.

Just thought about a potential issue though.

What happens if the user wants to delete a field value from his existing profile? Because I return only the keys which have actual values, I will never be able to 'reset' their field because the script will not acknowledge it.

What is the first thing I should look at when processing? Should I just use array_pop() and array_shift() to get rid of the two keys which aren't needed and leave all the other keys remaining, and if any of them don't have a value, update that particular field with an empty string, so that when they view their profile after updating, it looks empty?

I was really pleased with myself as well with the function I made, looks like it may have to be deleted! :(

Kind regards,

LC.

tangoforce
10-26-2012, 08:56 PM
Sorry I'm late..



What happens if the user wants to delete a field value from his existing profile? Because I return only the keys which have actual values, I will never be able to 'reset' their field because the script will not acknowledge it.

Thats probably the very reason you shouldn't really worry about using a function to check for the fields having values. I certainly never do. The only thing I check is if the field isset. If I'm honest, while I commend you on writing that function, I think you've taken the issue of checking user input a bit too seriously and gone a bit overboard with it. It never hurts to check things strictly but if its going to break another part of your logic flow then you're better off without it.

I'd also like to mention that this looks like its to do with your custom profile system that you're working on with Fou. For that reason, I can't fully appreciate your code or comment on it with accuracy because I've not been following that thread and simply have no idea of what you're doing exactly. I've stayed out of that thread because Fou has superior knowledge and is handling it meaning that you can't really expect me to help you out with that aspect of your code.

LearningCoder
10-26-2012, 10:51 PM
Ok I'll leave this profile idea, it's far too complicated. I'll carry on with the bits I can do and then come back to that later on in the project.

Regards,

LC.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum