Best practice for handling POST request in PHP - php

I'm working on a PHP project which has many pages calling a POST request, such as login, register, commenting and etc.
I've tried processing all POST requests in a single file named post.php, with each request containing 'formtype' parameter, like so,
$formtype = $_POST['formtype'];
if ($formtype == "register") {
register_function_here();
} else if ($formtype == 'login') {
login_function_here();
} else {
die("Error: No FORMTYPE");
}
and I've also tried having separate files for separate functions, such as login.php, register.php, comment.php and etc.
Which method is better for processing POST requests?
Are there any disadvantages for processing all POST requests in a single file, as I've done?
Thanks in advance!

I guess you mean you do not want to:
GET index.php
POST user/register.php
POST user/login.php
index.php
user/
register.php
login.php
404.php
What #ArtisticPhoenix about the MVC (model, view, controller) is actually what you tried. Well, for the Controller part i mean.
You try to create router.
You could do that. If you are new to coding and you got time i even would say: do it.
If you dont have time and need a solution then i suggest searching a framework - at least for routing.
To get started:
First i found was this: https://www.taniarascia.com/the-simplest-php-router/
If you want to go further then you SHOULD start using OOP.
A class is then a controller, a method an action.
(some got like every action is a class like zend expressive framework).
Example:
Create a routing config
// file: config/routes.php
return [
'routes' => [
[
'path' => "/login",
'class' => LoginController::class,
'method' => 'loginAction',
'allowed_methods' => ['POST'],
],
[
'path' => "/logout",
'class' => LoginController::class,
'method' => 'logoutAction',
'allowed_methods' => ['GET', 'POST'],
],
// ...
],
];
Create Controllers
// file: Controller/LoginController.php
namespace Controller;
class LoginController
{
public function loginAction()
{
// ...
}
public function logoutAction()
{
// ...
}
}
Now use the requested path and route it to the controller.
If no route found then return a HTTP 404 "Not Found" response .
// file: index.php
// load routing config
$routes = require 'config/routes.php';
// ...
// ... this now is up to you.
// you should search in the config if the requested path exists
// and if the request is in the allowed_methods
// and then create a new controller and call the method.

I strongly recommend Object Oriented Programming, using classes, one source file per class.

Related

execute global function automatically on running controller in yii2

We have web pages, where user will be redirected to $this->goHome(), if the session timeouts or user logouts. We have to destroy the all the session so, we have to add a function with destroying session. This function should be executed before running any action/controller in Yii2 i.e. similar to hooks in codeigniter. We have tried a helper function with destroying session and we have called the function as HomeHelper::getHelpDocUrlForCurrentPage(); in main.php layout, but the layout will be executed after running action in controller, it should work on running any controller as we have 100+ controllers. How this can be achieved, please suggest us in right way. Thanks in advance.
in
config/main.php
you could try using 'on beforeAction'
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'bootstrap' => [
'log',
....
],
'on beforeAction' => function($event){
// your code ..
} ,
'modules' => [
....
],
...
];
While #ScaisEdge solution would work I believe application config is not proper place to hold application logic.
You should use filters to achieve result you want.
First you need to implement filter with your logic. For example like this:
namespace app\components\filters;
class MyFilter extends yii\base\ActionFilter
{
public function beforeAction() {
// ... your logic ...
// beforeAction method should return bool value.
// If returned value is false the action is not run
return true;
}
}
Then you want to attach this filter as any other behavior to any controller you want to apply this filter on. Or you can attach the filter to application if you want to apply it for each action/controller. You can do that in application config:
return [
'as myFilter1' => \app\components\filters\MyFilter::class,
// ... other configurations ...
];
You might also take a look at existing core filters if some of them can help you.

Basic structure for developing with jQuery and Ajax in MVC (PHP)

I was hoping someone could share some advice on the file structure a mobile app with jQuery Mobile, Ajax and PHP.
I am pretty new to Ajax and I am struggling to integrate it into my MVC framework.
I have my Models, Views and Controller files and normally I would simply use my Controllers to feed my Views with the data from the Models.
However, when using Ajax, I understand that you can not POST (or GET) data to a specific function in a Controller directly. (Please correct me if I am wrong)
What is the best practice here?
Create a specific Ajax Controller with no functions?
Have a separate "connecting" php-file and post the Ajax call to that file which then calls the Controller files and retrieves the data.
Any ideas and maybe even some sample code would be greatly appreciated.
Here is an example how you do it with Yii framework.
This is your ajax class 'AjaxController.php':
class UserController extends Controller
{
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
*
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow',
'actions' => array('foo', 'bar'),
'users' => array('?'),
),
array('allow',
'actions' => array('foo', 'bar'),
'users' => array('*'),
),
array('allow',
'actions' => array('foo', 'bar','regform'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
// [...] all the common Yii Controller functions
public function actionRegform()
{
//get some data from database
$data = Yii::app()->db->createCommand('some sql')->queryRow();
//or render a view
$this->render('regform', array('mydata' => $dataFromDb));
//push out everything you want
echo 'my function was called!';
}
}
In your javascript you just call the url /ajax/regform and your MVC will know that ajax is the controller and actionRegform the function you are calling.
Do not forget to implement your function to the access rules of this controller.
The fact that You are using AJAX doesn't change much, the simplest way to use AJAX on your site is to put an extra POST (try not to use GET) parameter with will help You to determine if this is AJAX request. It can be just ajax=1. Then You can make a seperate view to show only those things that should be shown by ajax. this can be done on every components separately, or just in Your main index.php (or whatever your mine view file is called). In this file give some code like this:
if( ( isset($_POST['ajax']) ) and ( $_POST['ajax'] == 1 ) ){
echo just_main_content();// or $component->content - whatever You use
}else{
//normal page code
}
I believe that this is the easiest way

phalcon router not working

I try to use a router with phalcon. This is how it is included in index.php right after registering the 'events manager':
$di->set('router', function(){
require __DIR__.'/../app/config/routes.php';
return $router;
});
and this is how the routes.php looks like:
<?php
$router = new Phalcon\Mvc\Router(false);
$router->add("/", array(
'controller' => 'index',
'action' => 'index'
));
$router->add("/topics", array(
'controller' => 'wurst',
'action' => 'index'
));
$router->handle();
return $router;
The website reacts as if the router was not existent. /topics and topics say this:
TopicsController handler class cannot be loaded
and I also cannot use a die("test"); function inside routes.php . nothing happens.
I also tried to activate it without a separate file, but the result was the same :(
(The sample web-application INVO was used as starting point for my site )
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); will use default $_SERVER['REQUEST_URI']
If your index/index action is working when you access domain.com/index.php, check that you are using proper uri source, if using nginx or php built-in server you might have some problems with routing and $_GET['_uri'] which phalcon use for handling uris.
can find more about it on phalcon router documentation about uri sources -> http://docs.phalconphp.com/en/latest/reference/routing.html#uri-sources
now it seems to work:
Action 'route404' was not found on handler 'index'
the problem was , that I put the function to set the router in index.php within "set dispatcher function". ..did not see the closing braces.

Yii actionError not handling request when error occurs

I have made my custom controller and set it as default in my main config file.
All the other actions are working fine. But when there is any error i have made :
public function actionError() {
echo 'Error'; die;
}
and then i made a not found request. It did not did the action written by me, but did default action.
Please suggest!!
If you want to use your custom error action, you have to configure the errorAction in the errorHandler application component. You can do so in your main.php. If your controller is CustomController you'd configure:
'components' => array(
// ...
'errorHandler' => array(
'errorAction' => 'custom/error',
),
// ...
You dont have to echo inside the controller.Create a view file inside your views folder and render it like so public function actionError(){ $this->render('viewName') }

Zend Framework 2.1, output from one controller action to another controller

I am using zend framework 2.1. I am trying to load the output of my indexAction from my login controller inside of my index controller. The end result I am trying accomplish is to just have my login form loaded on the index page as if it is part of that view.
I have searched for a few hours with no avail. I have attempted to use $this->view->action, which i've seen in earlier versions of zf2 but that has not worked either.
Any information would be helpful.
Taken from this blog, which explains in depth why $this->view->action() has been removed from ZF2, an example how to use the forward() (ZF2 documentation) controller plugin:
You can forward all necessary data to another controller inside your index controller action using the forward() controller plugin like this:
public function indexAction() {
$view = new ViewModel();
$login_param = $this->params('login_param');
$login = $this->forward()->dispatch('App\Controller\LoginController', array(
'action' => 'display',
'login_param' => $login_param
));
$view->addChild($login, 'login');
return $view;
}
In your view, all you need to do is:
<?php echo $this->login; ?>
Please note that the forward() plugin might return a Zend\Http\PhpEnvironment\Response instead. This happens if you use a redirect() in your login controller / action.
Also, if the Servicemanager claims to not find App\Controller\LoginController, have a look in your module.config.php. Look for a section called controllers.
Example:
[...]
'controllers' => array(
'invokables' => array(
'LoginCon' => 'App\Controller\LoginController',
'IndexCon' => 'App\Controller\IndexController',
'DataCon' => 'App\Controller\DataController',
)
),
[...]
Here, there is an alias for your login controller called LoginCon, you should use this name as controller name in the dispatch() method instead.

Categories