简体   繁体   English

使用 PHP cURL POST JSON 数据

[英]Using PHP cURL to POST JSON data

I am working on a three-tiered login system for school and am having trouble sending and receiving messages using JSON + POST.我正在为学校开发一个三层登录系统,并且无法使用 JSON + POST 发送和接收消息。 I have a front-end which accepts a username and password:我有一个接受用户名和密码的前端:

<div id = "login form" style="text-align: center">
    <input type="text" id="username" name ="username"><br>
    <input type="password" id="password" name ="password"><br>
    <button id="login"> Login</button>
<div>

and then POSTS it using AJAX to the "back of the front" - a PHP script.然后使用 AJAX 将其发布到“前面的背面” - PHP 脚本。 The PHP script on the front end simply shuttles the same message along to the middle, which shuttles it to the back-end which would query a database and return a result.前端的 PHP 脚本只是将相同的消息传送到中间,然后将其传送到后端,后端将查询数据库并返回结果。 I made the following PHP script for the front end:我为前端制作了以下 PHP 脚本:

header('Content-type: application/json');

    $middle_url = "https://myurl.edu/";
    $username = $_POST['username'];  //extract credentials
    $password = $_POST['password'];

    // load new array
    $credentials = array(
      'username' => $username, 
      'password' => $password
    );

    $ch = curl_init();  // curl handle 
    curl_setopt($ch, CURLOPT_URL, $middle_url . "test.php");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);  // load credentials to POST
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // set return type to string
    $middle_reply = curl_exec($curl);  // execute curl and store response
    curl_close($ch);

    echo $middle_reply;

My issue is that when I run my HTML file, I get an empty string as a result and I'm not sure why.我的问题是,当我运行 HTML 文件时,我得到一个空字符串,我不知道为什么。

I created a test file in which I hard-coded a return like so:我创建了一个测试文件,我在其中硬编码了一个返回值,如下所示:

<?php
    header('Content-type: application/json');

    $response = array(
      'role' => 0
    );

    echo (json_encode($response));

?>

If I connect my HTML directly to this test file, I get the array that I am expecting, but when I try to route through my front-end PHP file first, I keep getting returned an empty string.如果我将我的 HTML 直接连接到这个测试文件,我会得到我期望的数组,但是当我尝试首先通过我的前端 PHP 文件进行路由时,我一直返回一个空字符串。 Please someone help me.请有人帮助我。

EDIT: In case it's helpful, this is how I am POSTing the data from my HTML file:编辑:如果有帮助,这就是我从 HTML 文件中发布数据的方式:

<script>

        const form = {
          username: document.getElementById('username'),
          password: document.getElementById('password'),
          login: document.getElementById('login'),
        };

        form.login.addEventListener('click',validate);


        function validate() {

            var ajax = new XMLHttpRequest();

            ajax.onload = function() {
              if (this.status == 200) {
                console.log(this.responseText);
                const response = JSON.parse(this.responseText);

                if(response['role'] == 1){ 
                  location.href = 'teacher.html';
                }
                else if (response['role'] == 0)  {
                  location.href = 'student.html';
                }
              }
            };     

            const postData = `username=${form.username.value} password=${form.password.value}`;
            ajax.open('POST','login.php',true);
            console.log(postData);
            ajax.send(postData);
        }

</script>

You need to specify the format of the data you want to send in your ajax request.您需要在 ajax 请求中指定要发送的数据格式。

It seems like you are close to the form urlencoded format, so you need to add this header:看起来你接近于 urlencoded 格式,所以你需要添加这个 header:

ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.send(postData);

And your parameters must be separated by an ampersand & , not by a space:并且您的参数必须用&号分隔,而不是空格:

const postData = `username=${form.username.value}&password=${form.password.value}`;

Additionally, you may want to escape your data with encodeURIComponent() , because at the moment, if your login or your password contains an ampersand, it will break the POST data format:此外,您可能希望使用encodeURIComponent()转义您的数据,因为目前,如果您的登录名或密码包含与号,它将破坏 POST 数据格式:

const username = `${form.username.value}` ;
const password = `${form.password.value}`
const postData = 'username=' +  encodeURIComponent(username) + '&password=' +  encodeURIComponent(password);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM