如何从带有文件上传的表单中获取帖子数据?

时间:2014-03-12 10:00:01

标签: php slim

如何使用slim来获取帖子数据。我有这样的函数调用

$this->app->post("/post/create", array($this, "createPost")); 我想从php html表单获取post数据。我接受了这样的请求

$request = \Slim\Slim::getInstance()->request();

并采取了这样的帖子数据

$userId = $_POST["user"];
$content = $_POST["content"];
$datetime = $_POST["date"];
$filename = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$filetmpname = $_FILES["image"]["tmp_name"];

这是正确的做法吗?

3 个答案:

答案 0 :(得分:8)

如果你使用Slim 3. *你可以这样做:

$app->post('/users', function ($request, $response) {
   $formDataArry = $request->getParsedBody();
    // do something with formDataArry 
});

答案 1 :(得分:2)

你可以这样做:

$this->app = new \Slim\Slim();

$this->app->post("/post/create", function () {

    $userId = $this->app->request->post('user');

    // or

    $allPostVars = $this->app->request->post();
    $userId = $allPostVars['user'];
    //...

});

如果您不想使用匿名函数(“在PHP 5.4.0 之前无法使用来自匿名函数的$ this”),我认为您可以这样做:

$this->app->post("/post/create", 'createPost');


function createPost() {
        $userId = $this->app->request->post('user');
        //...
}

答案 2 :(得分:2)

如果你正在使用Slim 3:

<?php
namespace Vendor\Product\Classes;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class LoginController
{
  public function loginUser(Request $request, Response $response)
  {
        $username = $request->getParam('username');
        $password = $request->getParam('password');

        // Logic to validate login ommited.
  }
}