Home > Article > Backend Development > PHP method sample code for receiving file stream sent by App
This article mainly introduces the method of PHP receiving App side to send file stream, involving PHP curl-based file transfer operation related skills, friends in need can refer to it
The example of this article tells the PHP receiving App side Method for sending a file stream. Share it with everyone for your reference, the details are as follows:
Solution ideas:
1. The client uploads multiple pictures in a loop, with parameters and combinations using certain rules Produce data stream (picture data is placed at the end)
2. Use data stream for transmission, and the php server uses file_get_content('php://input') to receive
3. After the transmission is completed, the data stream will be processed according to the rules Split, take out the last picture data, and write it into the picture file
Sample code:
The following code is to send a single picture and parameter PHP file. Multiple pictures can be Loop call.
<?php /* curl_post.php */ // 设置请求的POST地址,必须是包含网址的域名,不能是相对路径 $url = 'http://www.xxx.com/post.php'; $pic_data = file_get_contents('./me.jpg'); $data = [ 'username=chafang_'.rand(100, 999), 'password='.md5('123456'), 'pic=' => $pic_data, // 这里存放图片数据 ]; // 使用 '#####' 进行分割数组 $strData = implode('#####', $data); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); //设置头文件的信息作为数据流输出 curl_setopt($curl, CURLOPT_HEADER, 0); //设置获取的信息以文件流的形式返回,而不是直接输出。 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设置post方式提交 curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $strData); $data = curl_exec($curl); curl_close($curl); // 显示post的返回值 echo ($data);
Receive the PHP file requested by curl and return the json format
<?php /* post.php */ $content = file_get_contents("php://input"); $domain = 'http://www.xxx.com/'; // 注意这里需要有写权限 $filename = 'update/'.time().'_'.rand(100000, 999999).'.jpg'; $data = explode('#####', $content, 3); $count = count($data); $result = []; // 如果文件写入成功 if (file_put_contents($filename, $data[$count - 1])) { // 删除数据中最后一个元素(就是图片) unset($data[$count - 1]); foreach ($data as $val) { // 返回参数,且参数值不能存在 '=' 号 $tmp = explode('=', $val, 2); $result[$tmp[0]] = $tmp[1]; } // 组合图片访问地址 $result['pic'] = $domain.$filename; } echo json_encode($result);
The above is the detailed content of PHP method sample code for receiving file stream sent by App. For more information, please follow other related articles on the PHP Chinese website!