Home > Software design >  PHP MVC User Management
PHP MVC User Management

Time:01-07

I'm creating my own PHP MVC Framework and want to manage users, for this I have a dynamic url that is created with a form action like the following:

<form action="users/delete/<?=$user->id?>" method="post">
     <input type="hidden" name="_method" value="delete-submit" name="delete-submit">
     <button type="submit" >Delete</button>
</form>

I don't know if this is the right way to do it, so I'm asking. This redirects to /users/delete/$id but do I need to handle the form requests like this:

    if(!empty($_POST['delete-submit'])) {
            $user = $this->model("user");
            $user->deleteUser($value);
            header("Location:".ROUTE."home/users");
        }

or can I just work with the url and ignore the POST request.

CodePudding user response:

I wouldn't count on $_POST['delete-submit'] variable, cause for example if you use tool like Postman, you can create such request manually and delete any user, considering you are just checking if $_POST['delete-submit'] is set or not.

So if you are deleting user, there should be some authorization mechanism.

  1. users/delete route for deleting users -> That's Correct
  2. Then you check via $_SESSION['UserId'], which user is making such request and if he is authorized / has such permission, you delete the user..

Like...

function deleteUser($userId) {
    if(user::hasDeletePermission($_SESSION['UserId']) {
         'delete the user';
    }
}

If you already have such authorization based mechanism and just need additional check, user really submitted / clicked on that button or not, for CSRF attacks for example, then I would create Token (some random string with numbers and characters) and save into user's session, which would be embedded into form as a hidden input element's value.

Like:

<form method="POST" action="users/delete">
    <input type="hidden" name="csrfToken" value="token"/>
</form>

 function deleteUser($userId) {
    if($_POST['csrfToken'] === $_SESSION['csrfToken'] && user::hasDeletePermission($_SESSION['UserId']) {
         'delete the user';
    }
}
  • Related