用php解析formdata

用php解析formdata,php,angularjs,ajax,form-submit,Php,Angularjs,Ajax,Form Submit,我有一个来自AngularJS的AJAXPOST请求,一个JSON模型,带有一些字段和文件: ------WebKitFormBoundarywlEiXuTa9EkwFUWz Content-Disposition: form-data; name="model" {"fname":"and","lname":"and","email":"asd@asd.com","phone":"+3912345","position":"Marketing","startdate":"10/10/2017

我有一个来自
AngularJS
AJAX
POST
请求,一个
JSON
模型,带有一些字段和文件:

------WebKitFormBoundarywlEiXuTa9EkwFUWz
Content-Disposition: form-data; name="model"

{"fname":"and","lname":"and","email":"asd@asd.com","phone":"+3912345","position":"Marketing","startdate":"10/10/2017"}

------WebKitFormBoundarywlEiXuTa9EkwFUWz

Content-Disposition: form-data; name="file"; filename="InterviewPreparation.pdf"
Content-Type: application/pdf

------WebKitFormBoundarywlEiXuTa9EkwFUWz--
我是一个php虚拟开发人员。如何使用PHP解析请求?此代码不起作用:

<?php
// mail.php

$errors = array();  // array to hold validation errors
$data = array();        // array to pass back data

// validate the variables ========
if (empty($_POST['model.fname']))
  $errors['First name'] = 'Required.';
if (empty($_POST['model.lname']))
  $errors['Last Name'] = 'Required.';
if (empty($_POST['model.email']))
  $errors['Email'] = 'Required.';
if (empty($_POST['model.phone']))
  $errors['Phone'] = 'Required.';
if (empty($_POST['model.position']))
  $errors['Position'] = 'Required.';
if (empty($_POST['model.startdate']))
  $errors['Start Date'] = 'Required.';

// return a response ==============
$file = $_POST['file'];
if (! empty($file))
  echo 'Uploaded file: ' + $file.name;

// response if there are errors
if (! empty($errors)) {
  // if there are items in our errors array, return those errors
  $data['success'] = false;
  $data['errors']  = $errors;
} else {
  // if there are no errors, return a message
  $data['success'] = true;
  $data['message'] = 'Mail sent, good luck!';
}
// return all our data to an AJAX call
echo json_encode($data);
?>

第一个表单数据字段的名称是“model”,它包含一个JSON对象,在PHP中被视为字符串,除非先对其进行JSON解码

因此,我建议采取如下措施:

$model = filter_input(INPUT_POST, 'model'); // better to not use $_POST directly
$decoded = json_decode($model);
if(!$decoded)
    // not valid json
if(empty($decoded->fname))
    $errors['First name'] = 'Required.';
// etc...
该文件应位于$\u FILES数组中

$file = $_FILES['file'];

谢谢Brense,我正在努力处理这段代码。在您的代码中,如果我回显$model,则返回null。这意味着我无法从请求中获取参数“model”。我应该如何用PHP读回这篇文章的原始数据?作为一条小溪还是什么?这是一篇内容类型为“multipart/formdata”的文章。$stream=fopen('php://input","rb",$字符串=流\获取\内容($stream);变量转储($string)//这个转储给我字符串(0)”,如果执行
var\u转储($\u POST),结果是什么?表单数据不应在输入流中。PHP自动将表单数据字段添加到$_postarray.Content-type:multipart/formdata,并具有两个属性:“model”是JSON,“file”是文件