【问题标题】:Convert Linux Curl to PHP将 Linux Curl 转换为 PHP
【发布时间】:2017-02-19 16:15:44
【问题描述】:

我整个星期都在尝试使用 PHP curl 启用与我的 Web 服务的连接,但是,我无法让它工作,所以我尝试使用命令行 curl 并且令我惊讶的是......它成功了。

这是我使用 linux curl 使用的命令:

curl -k -i -H "Content-type: application/x-www-form-urlencoded" -c cookies.txt -X POST https://<host>/appserver/j_spring_security_check -d "j_username=admin&j_password=demoserver"

如何将其转换为 PHP 代码?

PS。我是新手,刚接触PHP不到一个月的exp,见谅! :D

【问题讨论】:

标签: php linux rest curl spring-security


【解决方案1】:

您询问以下 linux 终端 curl 命令如何与 PHP curl 的选项相关:

curl -k -i -H "Content-type: application/x-www-form-urlencoded" -c cookies.txt -X POST https://192.168.100.100:444/appserver/j_spring_security_chec‌​k -d "j_username=admin&j_password=demoserver"

以下是上述选项/标志的列表:

  • -k = CURLOPT_SSL_VERIFYPEER:假
  • -i = CURLOPT_HEADER: 真
  • -H = CURLOPT_HTTPHEADER
  • -c = CURLOPT_COOKIEJAR + CURLOPT_COOKIEFILE
  • -X POST = CURLOPT_POST: 真
  • -d = CURLOPT_POSTFIELDS

这将导致以下结果:

<?php
    $ch = curl_init();
    $url  = "https://192.168.100.100:444/appserver/j_spring_security_chec‌​k";
    $postData = 'j_username=admin&j_password=demoserver';
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, 1); // -X
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postData); // -d
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'application/x-www-form-urlencoded'
    )); // -H
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); // -c
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); // -c
    curl_setopt($ch, CURLOPT_HEADER, true); // -i
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // -k
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // see comment
    echo curl_exec ($ch);
    curl_close ($ch);

希望对你有帮助。

【讨论】:

  • 感谢@mevdshchee,您提供了大量帮助!我快到了.. 你知道为什么 PHP curl 不像 linux curl 那样推进吗?这是我执行 linux curl 时的结果。 HTTP/1.1 302 Found Date: Thu, 16 Feb 2017 19:12:22 GMT Server: Apache/2.2.26 (Unix) mod_ssl/2.2.25 OpenSSL/1.0.1e mod_jk/1.2.37 Set-Cookie: JSESSIONID=9D1761E49919B0FCE8E077E70E250749; Path=/appserver/; HttpOnly Location: https://192.168.100.100:444/appserver/portal/welcome;jsessionid=9D1761E49919B0FCE8E077E70E250749 Content-Length: 0 Access-Control-Allow-Origin: * Content-Type: text/plain
  • 您可能需要添加“CURLOPT_FOLLOWLOCATION”选项来跟踪重定向。我将此添加到代码中。
猜你喜欢
  • 1970-01-01
  • 2017-06-05
  • 2017-08-03
  • 2019-06-04
  • 2017-12-03
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
相关资源
最近更新 更多