如何在SLIM 2框架中显示HTTP POST数据

时间:2016-01-20 16:44:58

标签: php slim

在SLIM 2中,我有一个小表单来显示用户名。

我的index.php

$app = New \SlimController\Slim()

//Define routes
$app->addRoutes(array('/' => array('get' => 'Home:indexGet','post' => 'Home:indexPost'),
   ));

在postpage.php中:

<form action="" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit">
</form>

这是我的控制器功能:

public function indexPostAction()
{
    $this->render('postpage');
}

这是我的postpage.html

var_dump($app->request->post("username"));

我收到此错误:

  

异常'ErrorException',消息'Undefined variable:app'

我也尝试了var_dump($this->app->request->post("username")); 我得到了

  

异常'ErrorException',消息'Undefined variable:this'

2 个答案:

答案 0 :(得分:1)

Slim(v 2.x)View类不存储应用程序引用。 &#34;最短&#34;从内部视图获取应用程序(然后是请求对象)的方法(使用静态Slim:getInstance方法除外)是

$this->data->get('flash')->getApplication()->request()->post();

但这只是一种解决方法而不是官方方式。

如果您的视图需要数据,则应通过render方法获取数据:

$app->render('template', array('postdata' => $app->request()->post()));

如果这还不够,请创建一个View子类,该子类保存对应用的引用并将其设置为默认视图。

答案 1 :(得分:0)

 //First of all you did not set the action="" of your form in postpage.php so make it correct give the full route path like action="http://localhost/slim/index.php/showpostdata" (like if you are using wamp server and you have index.php in slim folder and showpostdata is your post route identifier) now try the following code or copy it and try it..

    //In postpage.php 
    <form action="http://localhost/slim/index.php/showpostdata" method="post">
        <input type="text" name="username">
        <input type="text" name="password">
        <input type="submit">
    </form>

    //In index.php which you will save in your slim folder

    <?php
      require 'vendor/autoload.php';
      $app = new\Slim\Slim();
    $app->post('/showpostdata', function () use ($app){
      $us=json_decode($app->request()->getBody(), true);
    //or
      $us=$_POST;

    //use one out of these above three or try all which gives you output..so In $us you will get an array of post data soo.. 
    $unm=$us["username"];
    $pwd=$us["password"];
    //now you have your post form data user name and password in variable $unm and $pwd now echo it...
    echo $unm."<br>";
    echo $pwd;
    });
     $app->run();
    ?>