search
HomeBackend DevelopmentPHP Tutorialphp怎么写服务端获取 客户端发来的json

我客户端是用 libcurl 库的  用http 给服务端发出请求的 不是用socket的  PHP应该怎么写才能收到请求


回复讨论(解决方案)

你先
file_put_contents('test.txt', 'get:' . print_r($_GET, 1) . 'post:' . print_r($_POST, 1));
看看 test.txt 中哪段有内容

如果使用的是HTTP协议的GET方法,数据保存在$_GET数组中.
如果使用的是HTTP协议的POST方法,数据通常保存在$_POST数组中.
注:如果post方法没有指出数据类型,提交的数据可以通过$HTTP_RAW_POST_DATA获取.

找到数据后可以通过json_decode函数处理下即可转换成数组或对象.

直接输出
print_r($_POST);ECHO "111";
pint_r($_GET);

你先
file_put_contents('test.txt', 'get:' . print_r($_GET, 1) . 'post:' . print_r($_POST, 1));
看看 test.txt 中哪段有内容

print_r($_POST, 1) 我直接打这个什么都没看到。。。 奇怪 我客户端就是发的是字符串 

你直接 print_r($_POST) 给谁看?给客户端?
那你客户端有显示回传数据的代码吗?

所以我让你 print_r($_POST, 1) 到文件,这样才好检查呀

get:Array
(
)
post:Array
(
)
我收到的是这个哈 还是什么都没有..蛋疼

你直接 print_r($_POST) 给谁看?给客户端?
那你客户端有显示回传数据的代码吗?

所以我让你 print_r($_POST, 1) 到文件,这样才好检查呀
get:Array
(
)
post:Array
(
)
我收到的是这个哈 还是什么都没有..蛋疼


file_put_contents('test.txt', file_get_contents('php://input'));
看看

进来学习的,抱歉,没帮到忙


file_put_contents('test.txt', file_get_contents('php://input'));
看看

什么都没有了..

你能确定客户端发了数据吗?

确定  是不是解码问题的 我客户端是用c++ libcurl post发的    

你能确定客户端发了数据吗? 确定  是不是解码问题的 我客户端是用c++ libcurl post发的    

你都没有收到数据,何来的解码?

有可能的话,请贴出 C++ 的代码片段

有可能的话,请贴出 C++ 的代码片段

#include "HHttp.h"
#include "json.h"
//导入curl头文件
#include "../libs/cocos2dx/platform/third_party/ios/curl/curl.h"

bool HHttp::pServer(){
    //------------------------
    CURL *curl; // 初始化 CURL 结构
CURLcode res;
    
    res = curl_global_init(CURL_GLOBAL_ALL);//初始化所有的可能的调用。
    if (res != CURLE_OK)
    {
        printf( "Failed to global init default [%d]\n", res );
        return false;
    }
    
// curl = curl_easy_init();
//    Json::FastWriter writer;
//    Json::Value root;
//    root["action"] = "device";
//      std::string json_file=writer.write(root);
if (curl)
{

         std::string cc; 
        curl_easy_setopt( curl, CURLOPT_URL, "http://127.0.0.1/ceshi/ceshi.php"); //请求的地址
        curl_easy_setopt(curl, CURLOPT_POST, true);                     //启用POST提交
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "account=zhycheng"); //发送的数据
        curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data); //处理的函数
        curl_easy_setopt( curl, CURLOPT_WRITEDATA, &cc);        //缓冲的内存
        res = curl_easy_perform(curl);// post
        if(res != CURLE_OK){
            if (CURLE_OPERATION_TIMEDOUT == res) //连接失败 超时
            {
                CCMessageBox("请重新尝试请求!", "网络连接超时");
                CCLog("网络超时:错误信息:%s\n",curl_easy_strerror(res));
                return 0;
            }
            CCMessageBox("请重新尝试请求!", "网络连接超时");
            CCLog("raw_send_recv : 启动 CURL 失败,错误信息:%s\n",curl_easy_strerror(res));
            return 0;
        }
        CCLog("~Send Data Done~~");
//清理 curl 结构,释放资源等
curl_easy_cleanup(curl);
        
} else  {
CCLog("raw_send_recv : 初始化 CURL 失败 \n");
        return 0; 
}
    return true;
}


int allLength;//总流长度
std::vector allData;//总数据

//服务器有数据返回的时候就会调用这个函数
size_t HHttp::write_data(uint8_t *dataPtr, size_t size, size_t nmemb, void *stream) {
    
    int  len  = size * nmemb;
    
    if(len!=1440){
        CCLog("收到服务器数据,返回的数据长度 : %i",allLength);
        
    }else{
        allLength+=len;
        allData.push_back(dataPtr);
    }
    size_t sizes = size * nmemb;
    return sizes;
}

你这样写对吗?
一般这么写
    // 初始化libcurl  
    CURLcode return_code;  
    return_code = curl_global_init(CURL_GLOBAL_WIN32);  
    if (CURLE_OK != return_code)  
        return 0;  
    CURL *curl_handle;  
    CURLcode res;  
    curl_handle = curl_easy_init();  
    curl_easy_setopt(curl_handle, CURLOPT_URL, url);  
   ....
你虽有
CURL *curl;
但没有
curl = curl_easy_init();
那 if (curl) 分支能进去吗?

你这样写对吗?
一般这么写
    // 初始化libcurl  
    CURLcode return_code;  
    return_code = curl_global_init(CURL_GLOBAL_WIN32);  
    if (CURLE_OK != return_code)  
        return 0;  
    CURL *curl_handle;  
    CURLcode res;  
    curl_handle = curl_easy_init();  
    curl_easy_setopt(curl_handle, CURLOPT_URL, url);  
   ....
你虽有
CURL *curl;
但没有
curl = curl_easy_init();
那 if (curl) 分支能进去吗?

代码确实运行了哈 连接成功了哈..... 我应该怎么办

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools