doujing6436 2016-04-13 16:10
浏览 23
已采纳

如何避免“+”符号引起的错误GET请求?

My URL path:

https://mypage/main.php?dir=farm/1234_animal_fred+sam_cats

I am requesting the data with the GET method:

$dir = $_GET['dir'];
echo $dir;

But my result is

farm/1234_animal_fred sam_cats
  • 写回答

3条回答 默认 最新

  • doudizhi947129 2016-04-13 17:01
    关注

    Even though Unex's answer is right in this particular case, I am unsure if he would be missing other characters that may be in your DB that could cause something to fail, or worse yet, open you up to an XSS vulnerability. So instead of making it work in this one single case by doing:

    $url = str_replace('+', '%2B', $url);
    

    You want to instead make it work for all cases. So assuming you have the following from your database:

    $file_path = 'farm/1234_animal_fred+sam_cats';
    

    To make this work correctly as part of a URL you need to do urlencode(), however from this answer you will notice that it's not enough to protect you from XSS attacks. You therefore also need to use htmlspecialchars() on the string:

    $url = 'https://mypage/main.php?dir=';
    $file_path = 'farm/1234_animal_fred+sam_cats';
    $url .= htmlspecialchars(urlencode($file_path));
    
    echo $url; // https://mypage/main.php?dir=farm%2F1234_animal_fred%2Bsam_cats
    

    And when going to this URL you can see that PHP gets the correct value:

    print_r($_GET) output:
    Array
    (
        [dir] => farm/1234_animal_fred+sam_cats
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line