Do not use $_FILES['ebook']['type'] == "application/pdf"
for the following two reasons:
It is up to the browser to send or not the correct type (maybe send another generic as application/octet-stream
).
Being provided from the client's browser (and not detected on the server, where you have control of how the check is done) can easily be altered by a user for malicious purposes.
Instead you should use mime_content_type()
and allow your server to detect the type by analyzing the contents of the uploaded file. use of magic numbers ( magic.mime
) of your server.
Example with mime_content_type()
:
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"
class="regisform" enctype="multipart/form-data">
<label>
Subir el ebook (máximo <?=
htmlspecialchars(ini_get('upload_max_filesize'))
?>)
</label>
<input type="file" name="ebook" />
<input type="submit" name="enviar" value="Upload" />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
extract($_POST);
$ebook = $_FILES['ebook']['tmp_name'];
if ($_FILES['ebook']['error'] !== 0) {
echo 'Error al subir el archivo (¿demasiado grande?)';
} else {
if (
mime_content_type($_FILES['ebook']['tmp_name']) == 'application/pdf'
) {
$ruta_ebook = 'ebook/' . $nombre_ebook . '.pdf';
if (move_uploaded_file($ebook, $ruta_ebook)) {
echo "Entra aqui";
} else {
echo "No entro";
}
}
}
}
Example with finfo::file()
:
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"
class="regisform" enctype="multipart/form-data">
<label>
Subir el ebook (máximo <?=
htmlspecialchars(ini_get('upload_max_filesize'))
?>)
</label>
<input type="file" name="ebook" />
<input type="submit" name="enviar" value="Upload" />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
extract($_POST);
$ebook = $_FILES['ebook']['tmp_name'];
if ($_FILES['ebook']['error'] !== 0) {
echo 'Error al subir el archivo (¿demasiado grande?)';
} else {
$finfo = new finfo(FILEINFO_MIME);
if (
strpos($finfo->file($_FILES['ebook']['tmp_name']),
'application/pdf') === 0
) {
$ruta_ebook = 'ebook/' . $nombre_ebook . '.pdf';
if (move_uploaded_file($ebook, $ruta_ebook)) {
echo "Entra aqui";
} else {
echo "No entro";
}
}
}
}
Increasing the size of received files
Ideally, modify the file php.ini
and set upload_max_filesize
and post_max_size
with a higher value.
For example, to configure 32 MiB using notation shorthand
, we will have to put:
upload_max_filesize = 32M
post_max_size = 32M
Another alternative option is to create a file .htaccess
(if you use apache and its use is enabled) with the following content:
php_value upload_max_filesize 32M
php_value post_max_size 32M