dougou8639 2014-12-03 17:40
浏览 57
已采纳

使用Heroku创建注册页面 - NotFoundException错误

I am trying to make a basic account registration page for a website using Heroku. I have installed PostGRESQL and created a table called users with all the proper columns. (I haven't used encryption yet since I'm just trying to get this working first.) Here is my PHP for the page:

<?php
require('../vendor/autoload.php');
require('../includes/config.php');
$app = new Silex\Application();
$app['debug'] = true;
// Register the monolog logging service
$app->register(new Silex\Provider\MonologServiceProvider(), array(
'monolog.logfile' => 'php://stderr',
));
// Register the Twig templating engine
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/../views',
));

/*checking database*/
    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
         /**/
        //check that all three fields have been filled out
        if (empty($_POST["username"])||empty($_POST["password"])||empty($_POST["confirmation"]))         
        {     
             apologize("You need to complete the username, password, and confirmation fields.");
             exit;
        }       
        //check that password and confirmation are the same
        if ($_POST["password"] != $_POST["confirmation"])
        {
             apologize("Password and confirmation must match.");
             exit;
        }

        if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) )
        {
             apologize("Email address not valid. Try again.");        
             exit ; 
        }    


// Register the Postgres database add-on
$dbopts = parse_url(getenv('DATABASE_URL'));
$app->register(new Herrera\Pdo\PdoServiceProvider(),
array   (
    'pdo.dsn' => 'pgsql:dbname='.ltrim($dbopts["path"],'/').';host='.$dbopts["host"],
    'pdo.port' => $dbopts["port"],
    'pdo.username' => $dbopts["user"],
    'pdo.password' => $dbopts["pass"]
    )
          );

$st = $app['pdo']->prepare('INSERT INTO users (username, email, hash) VALUES ('. $_POST["username"] . ', ' . $_POST["email"]. ', '. $_POST["password"]. ')');
$st->execute();     

$app->get('/db/', function() use($app) {

$st = $app['pdo']->prepare('SELECT username FROM users');
$st->execute();
$names = array();
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$app['monolog']->addDebug('Row ' . $row['name']);
$names[] = $row;
}
return $app['twig']->render('database.twig', array(
'names' => $names
));
});
$app->get('/twig/{name}', function($name) use($app) {
return $app['twig']->render('index.twig', array(
'name' => $name,
));
});
$app->run();
         //if the registration worked, log the user in
       if ($result !== false)
       {
            //if registration worked, remember that session ID
            $rows = query("SELECT LAST_INSERT_ID() AS id");
            $id = $rows[0]["id"];

            $_SESSION["id"] = $id; 
            redirect("../index.php");
       }
    }
    else
    {
        // else render form
        render("register_form.php", ["title" => "Register"]);
    }

?>

I am getting the following errors when I submit the page:

Sorry, the page you are looking for could not be found. 2/2 NotFoundHttpException in RouterListener.php line 145: No route found for "POST /" (from "http://secret-ridge-6332.herokuapp.com/register.php")

in RouterListener.php line 145
at RouterListener->onKernelRequest(object(GetResponseEvent), 'kernel.request', object(EventDispatcher))
at call_user_func(array(object(RouterListener), 'onKernelRequest'), object(GetResponseEvent), 'kernel.request', object(EventDispatcher)) in EventDispatcher.php line 164
at EventDispatcher->doDispatch(array(array(object(RouterListener), 'onKernelRequest'), array(object(LocaleListener), 'onKernelRequest'), array(object(LogListener), 'onKernelRequest'), array(object(MiddlewareListener), 'onKernelRequest')), 'kernel.request', object(GetResponseEvent)) in EventDispatcher.php line 53
at EventDispatcher->dispatch('kernel.request', object(GetResponseEvent)) in HttpKernel.php line 126
at HttpKernel->handleRaw(object(Request), '1') in HttpKernel.php line 66
at HttpKernel->handle(object(Request), '1', true) in Application.php line 538
at Application->handle(object(Request)) in Application.php line 515
at Application->run() in register.php line 72

1/2 ResourceNotFoundException in UrlMatcher.php line 96:

in UrlMatcher.php line 96
at UrlMatcher->match('/') in RedirectableUrlMatcher.php line 30
at RedirectableUrlMatcher->match('/') in LazyUrlMatcher.php line 51
at LazyUrlMatcher->match('/') in RouterListener.php line 127
at RouterListener->onKernelRequest(object(GetResponseEvent), 'kernel.request', object(EventDispatcher))
at call_user_func(array(object(RouterListener), 'onKernelRequest'), object(GetResponseEvent), 'kernel.request', object(EventDispatcher)) in EventDispatcher.php line 164
at EventDispatcher->doDispatch(array(array(object(RouterListener), 'onKernelRequest'), array(object(LocaleListener), 'onKernelRequest'), array(object(LogListener), 'onKernelRequest'), array(object(MiddlewareListener), 'onKernelRequest')), 'kernel.request', object(GetResponseEvent)) in EventDispatcher.php line 53
at EventDispatcher->dispatch('kernel.request', object(GetResponseEvent)) in HttpKernel.php line 126
at HttpKernel->handleRaw(object(Request), '1') in HttpKernel.php line 66
at HttpKernel->handle(object(Request), '1', true) in Application.php line 538
at Application->handle(object(Request)) in Application.php line 515
at Application->run() in register.php line 72

Any ideas what I could be doing wrong? Thank you!

  • 写回答

1条回答 默认 最新

  • dpwfh874876 2014-12-05 14:22
    关注

    Yeah you're mixing your old way of programming with using Silex.

    In general, you do $app->get('/someroute', function(Request $request) { ... }); to respond to GET requests, with your code for that route "/someroute" inside the function, and $app->post() for POST requests. You do NOT use the $_GET, $_POST etc superglobals in any way but instead use the request object passed to these controller functions to access request data.

    Please read some of the Silex tutorials out there and the main Silex manual to learn more.

    I tried to clean up your app a little bit as an example, and gave it an index page, a login form route and POST handler, and a registration form route and POST handler. Please use prepared statements with bound parameters to protect yourself against SQL injection, and please do not store passwords in plain text in the database but crypt() them properly using BCrypt.

    <?php
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    require __DIR__.'/../vendor/autoload.php';
    
    $app = new Silex\Application();
    
    $app->register(new Silex\Provider\MonologServiceProvider(), [
        'monolog.logfile' => 'php://stderr',
    ]);
    $app->register(new Silex\Provider\TwigServiceProvider(), array(
        'twig.path' => __DIR__.'/../views',
    ));
    $dbopts = parse_url(getenv('DATABASE_URL'));
    $app->register(new Herrera\Pdo\PdoServiceProvider(), array(
        'pdo.dsn' => sprintf('pgsql:dbname=%s;host=%s;port=%s', ltrim($dbopts["path"],'/'), $dbopts["host"], $dbopts["port"]);
        'pdo.username' => $dbopts["user"],
        'pdo.password' => $dbopts["pass"],
        'pdo.options' => array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION),
    ));
    
    $app->get('/', function(Request $request) use($app) {
        // your index code goes here, maybe render index.html.twig:
        return $app['twig']->render('index.html.twig');
    });
    
    $app->get('/login', function(Request $request) use($app) {
        // render login form here
        return $app['twig']->render('login.html.twig');
    });
    
    $app->post('/login', function(Request $request) use($app) {
        $email = $request->request->get('email');
        $password = $request->request->get('password');
        // try to log in here
        $s = $app['pdo']->prepare('SELECT * FROM users WHERE email = :email');
        if($s->execute(array(':email' => $email))) {
            $u = $s->fetch();
            // compare crypted password to stored hash, constant time and all
            // the hash acts as the salt at the same time, clever stuff
            if(!password_verify($password, $u['password'])) {
                // password wrong
            } else {
                // login okay
            }
        } else {
            // no such user
        }
    });
    
    $app->get('/register', function(Request $request) use($app) {
        // render registration form here
        return $app['twig']->render('register.html.twig');
    });
    
    $app->post('/register', function(Request $request) use($app) {
        $email = $request->request->get('email');
        // hash password using bcrypt (safe "2y" algorithm, cost factor 10, random salt)
        $password = password_hash($request->request->get('password'), PASSWORD_BCRYPT);
        $s = $app['pdo']->prepare('INSERT INTO users (email, password) VALUES(:email, :password)');
        $s->execute(array(':email' => $email, ':password' => $password));
        // success page unless there is an exception
    });
    

    I didn't test this, but you should get the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程