dqde43215 2017-06-07 19:10
浏览 68
已采纳

保护PHP和AJAX之间的POST请求 - 无用户输入

I have a simple component on a website that is performing a query of all the prod ids from a cluster of products on the page and storing them into an array in jquery. I then send that array to PHP via AJAX as a POST which will ultimately perform a db query on all the ids.

My question is, how can I protect the array coming from the AJAX/JS file into the PHP file in the POST, against user manipulation... meaning I can find the ids in the source code and change them to some random value or even something malicious.

Normally in a user input scenario, you could do a real escape string or similar functionality in the PHP to cover the incoming data. Since I'm sending over an array of numeric values, what would be the best to way to secure that POST request?

Thank you,

-S

  • 写回答

1条回答 默认 最新

  • dsuoedtom207012191 2017-06-08 10:26
    关注

    Let's assume, that you want to receive array of integer values from a client.

    If you write on a raw PHP, then your code can look like this:

    if (isset($_POST['ids']) && is_array($_POST['ids'])) {
        $ids = array_map('intval', $_POST['ids']);
        $ids = array_unique($ids); // Optional.
        print(implode(', ', $ids)); // Print values.
    }
    

    Sample of user input:

    ids[]=1&ids[]=2&ids[]=3&ids[]=malicious_input&ids[]=1
    

    Output:

    1, 2, 3, 0
    

    intval takes argument and returns it's integer representation. malicious_input becomes 0 and it's safe for using it in SQL queries.

    Some related links:

    1. PHP Prepared Statements.
    2. I have an array of integers, how do I use each one in a mysql query (in php)?
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?