I am using the HTML form below to pass a file to PHP for handling. But PHP says that the index is undefined.
Also, similarly, a variable I defined in config.php is showing as undefined.
What am I missing here?
classes.php
<?php
require('config.php');
error_reporting(E_ALL);
/*
* Classes required by the script
*
*/
class database extends PDO
{
public $conURL;
public function __construct($config) {
$conURL = "mysql:host=" . $config['host'] . ";dbname=" . $config['db'];
try {
parent::__construct($conURL, $config['user'], $config['pass']);
} catch (PDOException $e) {
$e->getMessage();
}
}
}
class upload
{
public $_FILES;
public function uploadFile() {
if ($_FILES['file']['size'] >= 2000000) {
echo "File is too large!";
}
elseif (isset($_FILES['file'])) {
$stmt = $this->prepare("INSERT INTO upload (name, type, size, content) VALUES (?, ?, ?, ?)");
$stmt->execute(array($_FILES['file']['name'], $_FILES['file']['type'], $_FILES['file']['size'], $_FILES['file']['file']));
}
}
}
config.php
<?php
$config = array(
'host' => 'localhost', // db host
'user' => 'root', // db user
'pass' => 'mypassword', //db pass
'db' => 'files' // db name
);
upload.php
<?php
error_reporting(E_ALL);
require('config.php');
require('classes.php');
$dbh = new database($config);
$upload = new upload();
$upload->uploadFile();
HTML form
<form name="uploaddb" action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input type="file" name="file" />
<br/>
<input type="submit" name="submit" value="Upload!" />
</form>
And for reference, here are the errors:
Notice: Undefined variable: config in
/Applications/MAMP/htdocs/files/classes.php on line 28Notice: Undefined index: file in
/Applications/MAMP/htdocs/files/classes.php on line 34
I didn’t test it, but here is what I think is wrong:
config.phpon the class files. You are already passing$configto thedatabaseconstructor.$_FILESon your classes, it’s a superglobal available everywhere.I’d also recommend you capitalize your class names.
UPDATE
Sorry that I can’t put it all together right now. Here is a couple more problems I see:
filekey on$_FILES['file']. Not sure which key you’re looking for.uploadas it is now. Isn’t$this->preparecausing an error? That class does not extendPDO. Maybe you should have the upload method inside the db class.