duanmin0941 2015-07-19 12:54
浏览 25

PHP:PDO(SQLite)用户输入 - 安全性?

I'm writing a litle Q&A webapp which will allow Internet users to submit answers to questions (only answers can be submitted, not questions).

I'd like your thoughts on my method that receives the user input and inserts it into the database, mainly from a security point of view. I've actively tried to address the weight of the payload (strlen()), XSS (htmlspecialchars()), SQL injection (prepare()), and that the user is submitting an answer to a question that actually exists (by executing a SELECT query "behind the scenes").

public function submitAnswer($qid, $payload) {
    // escape/sanitize input
    $answer = htmlspecialchars($payload, ENT_QUOTES);
    $unix_time = time();
    $qid = preg_replace('/\D/', '', $qid);

    // get length of question from db
    $this->sth = $this->dbh->prepare("SELECT question, LENGTH(question) as length FROM questions where id = :id");
    $this->sth->execute(array(':id' => $qid));
    $this->sth->bindColumn('length', $q_length);
    $result = $this->sth->fetch(PDO::FETCH_BOUND);

    // make sure question exists and check the combined length of q & a
    if ($result && ($q_length + strlen($answer) < 130)) {
        try {
            $this->hsth = $this->dbh->prepare("INSERT INTO answers (unix_time, qid, answer) values ($unix_time, :qid, :answer)");
            $this->sth->execute(array(
                ':qid' => $qid,
                ':answer' => $answer
            ));
            return array('status' => '0', 'unix_time' => $unix_time, 'qid' => $qid, 'length' => strlen($answer));
        } catch (PDOException $e) {
            return array('status' => '1', 'unix_time' => time(), 'message' => 'db error');
        }
    } else {
        return array('status' => '1', 'unix_time' => time(), 'message' => 'invalid input');
    }
}

To be more precise, do the functions (htmlspecialchars() and prepare()) offer sufficient protection against XSS and SQL injection?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 个人网站被恶意大量访问,怎么办
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM
    • ¥15 划分vlan后不通了
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)