Controlling program flow with both forms and urls - php

Sorry for a noob question. I have my php script organized like this:
switch(true)
{
case (isset($_POST['login'])):
// ...some code to check a login
break;
case (isset($_POST['register'])):
// ... some script to register a new user
etc.
Access to each section of code is controlled by using the name of the submit buttons in forms. I borrowed a menu system that uses URL's with command parameters instead of submit buttons. An example URL looks like this:
http://MYIPADDRESS/gradebook/login.php?guid=51913a6e37e1b&command=newclass
So, to get the same control of the program flow using URL's I tried adding this at the beginning of the file:
if (isset($_GET['command']))
{
switch ($_GET['command'])
{
case 'newclass':
$_POST['basicsettings']='basicsettings';
$guid=$_GET['guid'];
break;
case 'logout':
$_POST['logout']='logout';
break;
case 'continue':
$guid=$_GET['guid'];
$_POST['continue']='continue';
break;
}
}
This doesn't work because the $_GET global array is only reset if the next operation issues a new URL, and in most cases the user would use a submit button on a form and not select another menu item. You can't use unset on $_GET within a php script because it only affects the local copy. I tried setting up a $_SESSION command variable instead and refreshing the page using header("Location:login.php") to reset the $_GET global array but this also didn't work. Here is the modified code:
session_start();
if (isset($_GET['command'])) // if program flow control came from a URL
{
switch ($_GET['command']) // check which script section to use
{
case 'newclass':
$_POST['basicsettings']='basicsettings';
$guid=$_GET['guid'];
$_SESSION['command']='basicsettings';
$_SESSION['guid']=$guid;
header("Location:login.php");
break;
case 'logout':
$_POST['logout']='logout';
$_SESSION['command']='logout';
header("Location:login.php");
break;
case 'continueteacher':
$guid=$_GET['guid'];
$_POST['continueteacher']='continueteacher';
$_SESSION['command']='continueteacher';
$_SESSION['guid']=$guid;
header("Location:login.php");
break;
}
}
if (isset($_SESSION['command']))
{
$var=$_SESSION['command'];
$_POST[$var]=$_SESSION['command'];
$guid=$_SESSION['guid'];
$_REQUEST['guid']=$_SESSION['guid'];
unset($_SESSION['command']);
}
switch(true)
{ .. ...etc.
I realize that one way to fix this is to change the menu system to use submit buttons instead of URL's, but that has some downsides as well. Is there any way to make this work? Assuming you can see what I'm trying to do and it makes sense?

Related

Print HTML files within eachother with PHP

I am currently working on a project and I would like to print different HTML pages depending on the selection of the user.
Since all pages share the same sidebar and navigation bar I thought I could export them into a different file and always read/show them while also reading the different subsites and showing them.
Here is a little example of the code:
$decision = (isset($_GET["site"])?$_GET["site"]:"default");
switch ($decision) {
case "login":
readfile("login.html");
break;
case "register":
if($isAdmin){
readfile("register.html");
}
break;
default: // Prints the dashboard by default
/* #region To be removed (exists for testing only) */
//readfile("register.html");
/* #endregion */
readfile("dashboard.html");
break;
And since I don't know how I would succeed in showing to pages at the same time which are interconnected I am asking you and I was also wondering if I could send the page information by post and not only by get.
Thanks in advance!
The solution to my problem was to split my content into several different files and just arrange it in the correct order (suggested by #Adyson)
include_once("header.html");
switch ($decision) {
case default:
include_once("login.html");
break;
}
include_once("footer.html");

How to show error when action= not found php

Hii everyone i am new here, and i am also new in coding world too 😁
But i what i have learned so far from php by myself it feels nice using php.
But i have a queation
I have a file name (home.php)
I used
$action = $_GET("action")
In this page and i have multiple actions available fr the page it goes like
home.php?action=main
home.php?action=new
But when someone tries puting new action there that i dont have in the file
Like
home.php?action=boom
Page comes blank
Any one give me any idea to set a action that will come when an actio not found in the file
Thank you very much
I know ifs a lot to ask
But its stack overflow 😍
A very simple solution can be :
$action = $_GET["action"];
switch ($action) {
case "main":
// do your main stuff here
break;
case "new":
// do your new stuff here
break;
default:
// the action is unknown, do what you have to do in that case here
}
But that makes you add each new action manually, probably not the best way to do it.
Still, it is a simple way to answer your question.
You can also try this :
$action = $_GET("action");
if($action=='main'){
// do your main stuff here
}else if($action=='new'){
// do your main stuff here
}else{
// do your main stuff here
}
if action does not match in any condition then by default it will go on else case.

PHP session variable to be added to URL (and Vice Versa)

When users enter my site for the first time they are asked to select a location, this determines their currency. When selected, the country code is stored in $_SESSION['countryCode']and displayed onscreen.
However I'd also like to have this reflect in the URL, for instance if the user selected Germany the url would redirect to http://test.com/de/. Additionally I'd also like it if the user typed the above URL then when the page loads for it to set the session as 'de'.
I'm not sure where to start with this I presume we'd have to do a url rewrite within the htaccess file but I don't know how this would interact with the php session, so any help would be thoroughly appreciated.
All the best,
Matt
You would want to store your country session globally and then reference it in your header/bootstrap file.
I would personally run a switch statement to determine how URLs are structured with a default to GB.
session_start();
// Assuming your country has come in from a validated form post.
$urlBit = $_POST['country'];
switch($urlBit) {
case 'de':
$country = $urlBit;
break;
case 'es':
$country = $urlBit;
break;
default:
$country = 'gb';
break;
}
$_SESSION['country'] = $country;
Regarding the vice-versa, you could write some code to put the URL into a string and look for '/de/', '/gb/' within the string.
Again, I would revert back to a switch statement to handle that and once you know your result. Then, store it all using $_SESSION['country'].
session_start();
// Assumed URL structure.
$url = 'http://www.website.com/de/';
// The switcheroo.
$urlParts = explode('/', $url);
$urlBit = $urlParts[3]; // Returns 'de'
// The same switch as above. Stick it in a function or class/method, maybe.
switch($urlBit) {
case 'de':
$country = $urlBit;
break;
case 'es':
$country = $urlBit;
break;
default:
$country = 'gb';
break;
}
$_SESSION['country'] = $country;
This is the best answer I can offer without seeing code first, but this simple logic would solve your issue, assuming you knew how to implement the above.
You could easily do this without htaccess but it's hard to say without seeing your code.
You can do this without .htaccess.
Create a lang file that you include in all your script. That lang file will have a variable generated from your session variable that will be appended to all your links and it will have the carrying the currency code
initially at a login then cuntry is located by gps. then depending on the cuntry u write the php code like as.initially u defind the cuntry currency values..
use case or if condition
for select currency cuntry
like as
switch($cuntry_name)
{case(germany):
$_SESSION['countryCode'] = 'de';
break;
case(...):
$_SESSION['countryCode'] = '..';
break;
}

Does storing a MySQL fetch array in a variable only use it once?

I have a forum system and I use $users->permissions() a lot in my thread.php page. What I want to know is if I do something like $rights = $users->permissions() will it only make the call do the database to get the rights of that person one time as opposed to doing something like:
if($users->permissions() ==1) { show some mod panel }
elseif($users->permissions == 2) { show some admin panel }
SELECT `users`.`rights` FROM `users` LEFT JOIN `sessions` ON `sessions`.`user_id` = `users`.`id` WHERE `sessions`.`session_hash` ='".$this->con->real_escape_string($_COOKIE['session_hash'])."'
You are right. If you store the result of the call $users->permissions() into a variable (e.g. $rights) and then use that to check then it will only perform the call to the database once (and speed up the script as it's checking local data at that point rather than firing off a request to a server elsewhere).
However, if you use the code that you have shown in your initial question then it will perform a call to the database each time you check the value.
Personally, I would use a switch structure:
$rights=$users->permissions();
switch ($rights)
{
case 1:
//Show some form
break;
case 2:
//Show something else
break;
default:
//Do something just in case it's not 1 or 2
break;
}
If you want to stick with if...else statements, still store the result of $users->permissions() into a variable and then wherever you say $users->permissions() in the if structure, replace it with $rights
You are confusing functions and variables.
Unlike functions that runs every time they called, Variables do not run anything. they only contain some value. This is like putting money in the pocket. Once you got your change from a shopkeeper and put it in the pocket, the money stays there in the pocket, require no shopkeeper every time you put your hand in the pocket.

How to make Drupal redirect to pages after user registration

I have a Drupal website and I want to show different welcome pages, depending on what my users enter as profile fields. I can't use the global $user variable, because users are not automatically logged in (They have to very their email address before they can log in).
Where can I add code to set the redirect?
I've tried with $form['#redirect'] and $form_state['redirect'] in the form validator, but that didn't work.
You can use logintobogan for inspiration:
#implementation of hook_user
mymodule_user($op) {
if ($op == 'login') {
$_REQUEST['destination'] = '/user/will/be/redirected/here'
}
}
The important part is to make sure, that by the time the final drupal_goto() is called in user.module, you have set your $_REQUEST['destination'].
A few things to note:
Logintoboggan has a lot of code to deal with all sorts of edge-cases, such as redirecting out/to https. You can ignore these, if your case is simple.
Your module must be called after user.module and probably after other modules implementing hook_user, for they might change this global too. Very ugly, but the way this works in Drupal.
Do not -ever- issue drupal_goto() in any hook. Especially not hook_user, or hook_form_alter. drupal_goto will prohibit other hooks from being called; breaking functionality at the least, but often corrupting your database.
Do not issue drupal_goto() in form_alter callbacks such as "_submit", this might break many other modules and might even corrupt your database.
Similar to Berke's answer, but it seems like you just want this to be a one time thing. For that, you can check for the $account->access property to check their last login. If it is 0, then they are logging in for the first time.
This should work fine for email or no email validation.
<?php
/**
* Implements hook_user().
*/
function mymodule_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
// execute this if they have never accessed the site before
if ($account->access == 0) {
// run conditional logic based on profile fields
// to set destination here
$_REQUEST['destination'] = 'path/to/welcome-page';
}
break;
}
}
?>
I suggest you use the Login Destionation module or you can use the Rules module redirect action which is maybe to robust for your purpose.
Just in case you don't want to write your own custom module :-)

Categories