PHP: PDO (SQLite) user input
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?
上一篇: 清理用于输入电子邮件的用户输入
下一篇: PHP:PDO(SQLite)用户输入