Search code examples
htmlmodel-view-controllereditmodels

How should I edit a model entry in mvc?


I am working on a small app using phalcon for php framework. I have implemented multiple controllers and models, but so far when I want to edit a user for example, i use a link that links to

localhost/myappname/User/edit/11 "user's id"

I was told this is not the best way to do this, and I am trying to do this without passing the id through the url, like using post method like in forms but without success so far. Is this the only correct way to edit or delete an entry or it there something better? I tried to search for the problem but couldn't figure how to name this question so I am yet to find an answered question.


Solution

  • If you don't want to let everyone access to edit page you can do this in a few ways.

    Solution #1

    You can use Phalcon ACL to block user's who has no permission to edit this page so only allowed people like managers can edit user or whatever.

    See Access Control Lists ACL

    Solution #2

    You can crypt/decrypt user id so in URL it will not be readable by humans and then in edit method try to dectypt that id and if it is not a valid echo error.

    <?php
    
        use Phalcon\Crypt;
    
        // Create an instance
        $crypt   = new Crypt();
    
        $key     = 'le password';
        $user_id = 5;
    
        $encrypt = $crypt->encryptBase64($user_id, $key);
        // Use $encrypt for URL like <a href="/User/edit/{{encrypt}}">Edit</a>
    
        // Use decrypt to get the real id of a user
        $crypt->decryptBase64($encrypt, $key);
    
    ?>
    

    In this way users will see URL something like

    localhost/myappname/User/edit/nomGPPXd+gAEazAP8ERF2umTrfl9GhDw1lxVvf39sGKF34AFNzok31VdaT/OwADPPJ4XgaUNClQKrlc/2MfaXQ==

    For more info see Encryption/Decryption

    But my personal opinion is that it is better to go with ACL. After all ACL was made for that kind of things.

    Note! If you want to use Encrypt/Decript remember to wrap decryption in edit method in try/catch block and catch exception so you don't get Error if someone tries to guess sone id.

    Solution #3

    If you still want to do that using POST then don't use <a href="...">Edit</a> instead you can try something like:

    <form method="POST">
        <input type="hidden" name="uid" value="{{ user_id }}"/>
        <button type="submit">Edit</button>
    </form>
    

    And then in edit method catch that id like:

    <?php
        $user_id = $this->request->getPost("uid");
    ?>
    

    NOTE! In this way your URL will not contain user id but someone still can POST another uid so you can try to hide that real user id even from input type hidden. You can use again crypt/decrypt so input hidden uid can be crypted and then decrypt post data in method.