duanjian7617 2009-06-27 17:54
浏览 42
已采纳

初学者RegEx问题 - PHP RegEx只允许相对路径(不是URL)

Does anyone know a PHP RegEx to allow only relative paths, not absolute?

For example, I have an AJAX function that submits this value to my PHP script "some-directory/another-directory/some-file.php".

My PHP script then includes that file.... include($some-php-document);

I don't want a hacker to be able to use my AJAX function to submit something like: "http://www.malicious-website.com/malicious-script.php"

In my PHP Document I would like to do something like:

<php>
$some-php-document = $_POST["some_value_submitted_via_ajax"];

//if $some-php-document is a URL (not a relative path to a file), 
    //then $some_php_document = null

//how can I use a php regex to accomplish the above?

</php>

How can I do this?

Or, let me know if there are more secure solutions.

  • 写回答

3条回答 默认 最新

  • doucheng7234 2009-06-27 18:05
    关注

    I would use the parse_url() function rather than a regexp, something like:

    <?php
    $some_php_document = $_POST["some_value_submitted_via_ajax"];
    
    $parsed_doc = parse_url($some_php_document);
    
    //if $some-php-document is a URL (not a relative path to a file), 
        //then $some_php_document = null
    if (isset($parsed_doc['scheme']) || isset($parsed_doc['host'])) {
        $some_php_document = null;
    }
    
    ?>
    

    The file path will be in $parsed_doc['path']. It should be checked before being used, so an attacker can't say, request /etc/passwd or some similarly sensitive file.

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

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services