How to show error when action= not found php - 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.

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");

OOP/Maintainble alternatives to including pages with switch statement

I have pages in my website with URLs like this:
http://example.com/index.php?page=about
http://example.com/index.php?page=portofolio
http://example.com/index.php?page=location
http://example.com/index.php?page=mission
http://example.com/index.php?page=contact
http://example.com/index.php?page=register
http://example.com/index.php?page=login
Now, the objective is to include be it a simple about.html page containing a simple text about the company, or a form processor file called register.php when ?page=register is called.
This is how I am handling the contents.
$id= isset($_GET && !empty($_GET['page'])) ? htmlspecialchars($_GET['page']) : false;
switch($id){
case 'about':
include 'about.html';
break;
case 'porofolio':
include 'portofolio.html';
break;
case 'contact':
include 'contact_form.html';
include 'contact_process.php';
break;
case 'login':
if(isset($_SESSION['user_login'])){
echo 'You are already logged in';
}else{
include 'login_form.html';
include 'login_process.php';
}
default:
die('Page not found');
break;
}
Yes, I know It is horrible. I know trust me. That is why, I need better maintainable solution to this.
Now, if you are just curious what could be inside process_login.php It looks like:
if($_POST){
if(!empty($_POST['username']) && !empty($_POST['password'])){
try{
$pdo = new PDO(...);
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND password = ?");
if($stmt->rowCount(){
$_SESSION['user_login'] = $_POST['username'];
header('location: success.php'); exit;
}
}
}
}
This is just an example I quickly wrote, so there may be some typo or another thing I've left. What I am interested to know is how to better create/emulate a practice of handling the switch statements, as it does not seem to me a good oop-oriented approach for such task. I want something maintainable, extensible approach.
If you are wandering why I have only have one page index.php, it is because I don't want to create static pages for all the pages, as they have the same layout, making the HTML improvement easier. Instead of one day, opening 7 files to change/add a single tag, it would make sense to do it only once.
second, if you wandering why I chose to include the about.html page instead of simple storing the plain text in database, is because I didn't want to create a field/table/connection just for that 10 line simple text, as I would be saving some overhead performance. (Although I am sure, you may not agree on this)
So, the general question is, how to get rid of that complexity with switch statement, which makes me end up creating files like login_process.php instead of dealing with it, in some OOP way that I am not aware of.
Sorry for the wall of text :( and thanks in advance.
The solution that you're looking for is really MVC and templating your views. Further, you're essentially creating your own router, your router is pretty simple compared to some of the complex routing schemes found in some of the major frameworks, so if you're looking to simplify further, that's going to be kinda difficult.
If you want to see how this is all done in a very OOP manner, checkout something like the Zend Framework 2, CakePHP, etc.

Magento change language by login

I'm searching now for hours. I try to switch the store language after the login.
Given is:
The id of the Store I want to switch too.
The Event Observer is also done.
This is what I worked out the last hours
My Observer:
$customerId = Mage::getModel('customer/session')->getCustomer()->getId();
// Get the Store ID we want to switch too
$connection = Mage::getSingleton('core/resource')->getConnection('distributor_read');
$mainLanguage = $connection->fetchAll('SELECT...');
$storeId = $mainLanguage[0]["store_id"];
if (!$storeId == null) {
$storeCode = Mage::app()->getStore($storeId)->getCode();
// Here I have to switch by the store code
return;
}
Would be glad if someone could help me out.
At least I need a method to switch the language or storeview, but I don't find any working MagentoAPI methods.
to Set the store id programatically
In the index.php file, (in your language specific folder), add the following:-
$store_id = 'your_store_id_here';
$mageRunCode = 'store view code';
$mageRunType = 'store';
Mage::app()->setCurrentStore($store_id);
Mage::run($mageRunCode, $mageRunType);
I am suggesting you to create some temporary session variable from login action and read in index.php to set language pack and again unset it if your work has been done
Hope someone will find this information useful :)
I will tell you guys what I did for this case. I tried to get the Mage_Core_Controller_Response_Http class, completely in vain.
So I kept going on my research and I found a solution.
I used:
header('Location: '. Mage::app()->getStore()->getBaseUrl().'/customer/account?___store='.$storeCode);
There we go, my on login observer just set the language.
edit:
To set a new header could cause some problems, because if just any piece of html is already rendered you can not set a new header.
I worked sth. else out:
$url = Mage::getUrl('*/*');
$url .= "?___store=" . $storeCode;
$response = Mage::app()->getFrontController()->getResponse();
$response->setRedirect($url);
$response->sendResponse();
exit();
There is obviously still a problem, the exit shouldn't used in good software code, but a simple return does not work, it does not end or kill the observer action.
I still working on a solution to kill the observer in a right way. As I said the observer need to get killed to redirect the url.

Controlling program flow with both forms and urls

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?

PHP Case switch (efficiency)

The code below ensures that when a user accesses control panel, they are ran through a quick verification process to validate what their entities are. For instance, if a user is level 1 they are only given access to video feed which means nothing else is available to them.
When I look at the code though, I can see video feed being called when case 1 and 3 are called. I would possibly enjoy an alternative to make the code more efficient.
I was told a possible array could make things a little easier but then again this is faster.
switch ($_SESSION['permission']) {
case 1: // Level 1: Video Feed
include ("include/panels/videofeed.index.php");
break;
case 2: // Level 2: Announcements / Courses / Teachers
include ("include/panels/announcements.index.php");
include ("include/panels/courses.index.php");
include ("include/panels/teachers.index.php");
break;
case 3: // Level 3: Announcements / Video Feed / Courses / Teachers / Accounts / Logs
include ("include/panels/announcements.index.php");
include ("include/panels/videofeed.index.php");
include ("include/panels/courses.index.php");
include ("include/panels/teachers.index.php");
include ("include/panels/accounts.index.php");
include ("include/panels/log.index.php");
break;
case 4: // Level 4: Teachers
include ("include/panels/teachers.index.php");
}
It's fine the way it is. I think you don't mean "efficiency" when you refer to the "repeated" includes. You mean you could compact your code by using the switch fall-through.
While this might make your code smaller, it has no significant impact of efficiency (the time the script takes to run) and it will actually make the code harder to read. Leave it be.
Frist you may run better if you use require_once if its possible.
The second point is to shorten the url it seems that its every include the same.
Maybe try to use it in a function for example:
$permission_id = $_SESSION['permission']
function requireModule($moduleName, $path = 'include/panels/') {
$moduleName .= '.index.php';
require_once($path . $moduleName);
}
// if you want you can add an arry for it:
$permissionModules = array(
array('videofeed'),
array('announcements', 'courses', 'teachers'),
array('announcements', 'courses', 'teachers', 'accounts', 'log', 'videofeed'),
array('teachers')
);
// now we can put it in a more effectiv way
if(array_key_exists($permission_id, $permissionModules)) {
foreach($permissionModules[$permission_id] as $includes) {
requireModule($includes);
}
}
Wrong ? Correct me!

Categories