I have a little problem with my browser application, which is hosted on a local server with XAMPP.
I have a form in which there is inputs
text and one file.
When uploading the file/image, from my computer, it uploads correctly and when I do it with my android device, searching and selecting an image from the gallery, it also uploads. But it turns out that if instead of choosing the file in the gallery I take a photo directly, it does not upload correctly.
I put the code below:
<?php
require_once 'conexion.php';
$result;
$connn = dbConnect();
// Create the query
$user ="";
$sqll = 'SELECT * FROM ******* ORDER BY id DESC LIMIT 1';
$result = $connn->query($sqll);
$rows = $result->fetchAll();
foreach ($rows as $row) {
$idImg = $row['id'];
}
$target_path = "img/";
$tipo_archivo = $_FILES['uploadedfile']['type'];
$tipo_archivo = explode("/", $tipo_archivo);
$tipo_archivo= '.'.$tipo_archivo[1];
$nombre_archivo= $idImg.$tipo_archivo;
$target_path = $target_path.$nombre_archivo;
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<script type='text/javascript'>
window.location='index.php';
</script>";
}
else{
echo $target_path;
}
?>
Here theinput
<form method="post" action="insertar.php" id="carga_archivo" name="carga_archivo" enctype="multipart/form-data" >
<!--inputs...-->
<p><span>Imagen: </span><input type="file" id="file-input" name="uploadedfile"></p>
<input type="submit" value="Crear" class="pill orange" style="border:none;width: 100%;">
</form>
In your code I see mainly two problems that can be the origin of the file not being saved correctly. The first is related to the lack of upload status checking and the second is related to the way you get the file extension.
Checking the rise
Before working with the uploaded file you should check if there was any kind of error during the upload. All error messages are on this PHP man page .
Here I show you a way to manage any eventuality during the upload process:
In case the problem is that you are sending a larger file (
UPLOAD_ERR_INI_SIZE
) than the default value or set toupload_max_filesize
, you can change its value inphp.ini
to, for example, 32 MiB:Get the file extension
Another problem you may experience is that the browser is not sending the index
type
with the expected or correct value.You should correct your code to detect the file extension in alternative ways in case the index is empty:
You could also make use of
finfo_file()
to get the actual content of the file, regardless of what information the browser gives us:Or using the OOP interface: