【问题标题】:Sending data using POST in Python to PHP在 Python 中使用 POST 将数据发送到 PHP
【发布时间】:2023-04-01 06:13:01
【问题描述】:

PHP 代码:

<?php
$data=$_POST['data'];
echo $data;
?>

当我这样做时,Python 打印的 HTML 页面会通知我 PHP 在$data 中没有收到任何值,即:

$name 中的错误;未定义索引

但是,当我将数据作为 GET (http://localhost/mine.php?data=data) 发送并将 PHP 方法从 POST 更改为 GET ($data=$_GET['data']) 时,会获取并处理该值。

我的主要问题是数据中的值似乎没有传递给 PHP,因为我本来想使用 POST。有什么问题?

【问题讨论】:

  • 鉴于我们大多数人都不是千里眼,发布您的代码可能是个好主意。

标签: php python urllib2


【解决方案1】:
import urllib
import urllib2

params = urllib.urlencode(parameters) # parameters is dicitonar
req = urllib2.Request(PP_URL, params) # PP_URL is the destionation URL
req.add_header("Content-type", "application/x-www-form-urlencoded")
response = urllib2.urlopen(req)

【讨论】:

    【解决方案2】:

    看看这条蟒蛇:

    import urllib2, urllib
    mydata=[('one','1'),('two','2')]    #The first is the var name the second is the value
    mydata=urllib.urlencode(mydata)
    path='http://localhost/new.php'    #the url you want to POST to
    req=urllib2.Request(path, mydata)
    req.add_header("Content-type", "application/x-www-form-urlencoded")
    page=urllib2.urlopen(req).read()
    print page
    

    几乎所有东西都在那里看第 2 行

    这是 PHP:

    <?php
    echo $_POST['one'];
    echo $_POST['two'];
    ?>
    

    这应该给你

    1
    2
    

    祝你好运,我希望这对其他人有所帮助

    【讨论】:

      【解决方案3】:

      有很多文章建议使用 requests 而不是 Urlliburllib2。 (阅读参考资料以获取更多信息,解决方案优先)

      您的 Python 文件 (test.php):

      import requests
      userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
      resp = requests.post('http://yourserver.de/test.php', params=userdata)
      

      您的 PHP 文件:

      $firstname = htmlspecialchars($_GET["firstname"]);
      $lastname = htmlspecialchars($_GET["lastname"]);
      $password = htmlspecialchars($_GET["password"]);
      echo "firstname: $firstname lastname: $lastname password: $password";
      

      名字:John 姓氏:Doe 密码:jdoe123

      参考资料:

      1) Good Article, why you should use requests

      2) What are the differences between the urllib, urllib2, and requests module?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-28
        • 2016-07-31
        • 2017-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多