You are not logged in.
- Topics: Active | Unanswered
#1 2010-01-04 12:35:50
- frozen_space
- Member

- From: Wuxi, China
- Registered: 2008-05-12
- Posts: 107
- Website
Can you find 3 most severe defects in this code?
I have been asked with this question, not sure if i get the right answer
<?php
class Document {
public $user;
public $name;
public function init($name, User $user) {
assert(strlen($name) > 5);
$this->user = $user;
$this->name = $name;
}
public function getTitle() {
$db = Database::getInstance();
$row = $db->query('SELECT * FROM document WHERE name = "' .
$this->name . '" LIMIT 1');
return $row[3]; // third column in a row
}
public function getContent() {
$db = Database::getInstance();
$row = $db->query('SELECT * FROM document WHERE name = "' .
$this->name . '" LIMIT 1');
return $row[6]; // sixth column in a row
}
public static function getAllDocuments() {
// to be implemented later
}
}
class User {
public function makeNewDocument($name) {
$doc = new Document();
$doc->init($name, $this);
return $doc;
}
public function getMyDocuments() {
$list = array();
foreach (Document::getAllDocuments() as $doc) {
if ($doc->user == $this)
$list[] = $doc;
}
return $list;
}
}
?>1. Possible SQL injection
2. No constructor defined
3. Should not use assert in the production env ????
Last edited by frozen_space (2010-01-05 03:57:49)
Today is the tomorrow you worried about yesterday, and all is well. ![]()
FluxBB in Chinese.
Offline
#2 2010-01-06 01:36:27
- Daniel03155
- Member
- Registered: 2010-01-05
- Posts: 1
Re: Can you find 3 most severe defects in this code?
Hey,
I wouldn't say that having no constructor makes it a severe mistake. Constructors are optional, but you can surely benefit from having them. One severe defect would be not sanitizing the variables before confronting them with the database.
Another one would be
return $row[6]; // sixth column in a row
mysql_query returns a resource, it seems like you forgot to to add mysql_fetch_row() to get a result row array, then display the column you wish. (The same goes with the others).
Lookup mysql_query().
Do you really need all these methods to be public?
Offline
#3 2010-01-06 02:30:17
- frozen_space
- Member

- From: Wuxi, China
- Registered: 2008-05-12
- Posts: 107
- Website
Re: Can you find 3 most severe defects in this code?
Thanks, Daniel,
I found another one, we should not write like this foreach (Document::getAllDocuments() as $doc) , the getAllDocuments() should not be in the loop
Today is the tomorrow you worried about yesterday, and all is well. ![]()
FluxBB in Chinese.
Offline
