draw62188 2010-09-08 17:38
浏览 116
已采纳

在登录表单/控制器中存储返回URL的位置

I am wondering how to best deal with a return url in a login form. I think a good way is probably how it is done here. That is to urlencode the current url and send it as a get parameter to the login controller.

This can then be urldecoded in the login controller. But what then? I looked at the StackOverflow login page, and I couldn't find that url anywhere. Where is it stored? How does it know where to go when the login is done? Is it stored in a cookie? Session variable? Or something else?

I guess things can be done a bit differently than in PHP, but anyways. What is a good way to do this?

  • 写回答

2条回答 默认 最新

  • doulu5109 2010-09-08 17:43
    关注

    If it's a static URL, then you can include it on the form as a hidden field and then redirect to it in your code, i.e.

    <input type='hidden' name='return' value='/thankyou.html' />
    

    Then in your submit function ...

    header("Location: $_POST['return']");
    

    In production, you'll obviously want to encrypt the URL in the hidden field, and then decrypt it and validate it as a good URL before invoking the header() function, but that should give you the idea.

    Some folks use cookies, others have a lookup table in the DB. Doesn't really matter where you store the URL, it's just important that you scrub it before you header() it.

    EDIT: Scrubbing

    function isValidURL($url) {
       return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
    }
    
    if ( isValidURL($_POST['return']) )
        header("Location: {$_POST['return']}");
    

    As I said earlier, if you want to be even more careful, you can encrypt/decrypt the actual URL prior to showing on the form and prior to validation. There's a ton of good encrypt/decrypt libraries out there.

    The take home lesson is to never actually "do anything" (such as insert values in a database, run a shell command, redirect to a URL, etc) with data that comes in via form. Someone could manipulate that hidden field and inject code into your app or db by being tricky. There's thousands of posts an examples of things that people will do through form injection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?