PHP 500内部错误没有得到现场

时间:2017-08-28 08:08:11

标签: php json http

我已经完成了这段代码很多次都无法发现单个错误,任何正文看到这个脚本有什么问题。 它给了我以下错误: localhost目前无法处理此请求。 HTTP ERROR 500

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<?php
session_start();

ob_start();

header("Content-type: application/json");

date_default_timezone_set('UTC');



$db = mysqli_connect('localhost', 'root', 'root', 'chat');

if(mysqli_connect_errno()) { 

    echo '<p>Error:Could not connect to database.<br>
    Please try again later.</p>'; 
    exit; 
} 

try { 
    $currentTime = time(); 

    $session_id = session_id(); 

    $lastPoll = isset($_SESSION['last_poll']) ? 
        $_SESSION['last_poll'] : $currentTime; 

    $action = isset($_SERVER['REQUEST_METHOD']) && 
        ($_SERVER['REQUEST_METHOD'] == 'POST') ? 
        'send' : 'poll'; 

    switch($action){ 
        case 'poll': 

            $query = "SELECT * FROM chatlog WHERE
            date_created >= ?"; 

         $stmt = $db->prepare($query); 
            $stmt->bind_param('s', $lastPoll); 
            $stmt->execute(); 
            $stmt->bind_result($id, $message, $session_id, $date_created);
            $result = $stmt->get_result(); 

            $newChats = []; 

            while($chat = $result->fetch_assoc()){ 

                if($session_id == $chat['sent_by']){ 
                    $chat['sent_by'] = 'self'; 
                }else{ //good
                    $chat['sent_by'] = 'other'; 
                } 
                $newChats[] = $chat; 
            } 

            $_SESSION['last_poll'] = $currentTime; 

            print json_encode([ 
                'success' => true, 
                'messages' => $newChats
            ]); 
            exit; 

        case 'send': 

            $message = isset($_POST['message']) ? $_POST['message'] : '';

            $message = strip_tags($message);

            $query = "INSERT INTO chatlog(message, sent_by, date_created)
            VALUES(?, ?, ?)"; 

            $stmt = $db->prepare($query); 
            $stmt->bind_param('ssi', $message, $session_id, $currentTime);
            $stmt->execute(); 

            print json_encode(['success' => true]); 
            exit; 
    } 
}catch(\Exception $e) { 
        print json_encode([ 
            'success' => false,
            'error' => $e->getMessage();
        ]);
    }

我有javascript文件和HTML文件javascript文件用于处理ajax请求,我使用jquery来处理所有ajax的东西。我不知道是否可以将错误传递给PHP文件?

1 个答案:

答案 0 :(得分:1)

尝试删除分号

'error' => $e->getMessage();

'error' => $e->getMessage()

在你的最后一行中。

请使用带有PHP语法检查的编辑器来避免这些问题。