Need to upload img to my directory

I have this code, which creates a folder in the specified directory if it does not exist and moves the images submitted by the user to that folder, my problem is that on my localhost it works perfectly, but once I uploaded the website to the hostinger host The image is no longer copied to the specified path, I have already changed the path as the hosting support informs me but it does not work, I have already modified the code thousands of times and nothing for two days I am trying to fix it but to no avail, I also changed the permissions of the folders in my directory and it didn’t work either. this is my code

 // Procesar las imágenes
    $imagenes = $_FILES['imagen']['name'];
    $imagenes_temp = $_FILES['imagen']['tmp_name'];
    $carpeta_destino = "carpeta_destino/".$nombre;

    if (!file_exists($carpeta_destino)) {
        mkdir($carpeta_destino, 0777, true);
    }

    $rutas_imagenes = array();
    for ($i = 0; $i < count($imagenes); $i++) {
        if (!empty($imagenes[$i])) {
            $imagen = $imagenes[$i];
            $imagen_temp = $imagenes_temp[$i];
            $ruta_imagen = "carpeta_destino/".$nombre."/".$imagen;
            move_uploaded_file($imagen_temp, $ruta_imagen);
            $rutas_imagenes[] = $ruta_imagen;
        }
    }

    $ruta_imagenes_string = implode(',', $rutas_imagenes);

You need to find what’s causing a problem in order to be able to fix the problem. What does php’s error reporting show? Add the following two lines of code near the top of your php code to get php to report and display all the errors it detects -

ini_set('display_errors', '1');
error_reporting(-1);

show no error, i put the code after the session star and include conexion
as i say the code is perfect working in localhost, but in the hosting dont transfere the img to the directory

Unless your web host has disabled those settings, no php errors would indicate that it is likely that your upload form processing code is not being executed at all.

What does adding echo '<pre>'; print_r($_FILES); echo '</pre>'; right before the start of your form processing code show?

Lastly, it will be quicker if you just post all of the form processing code.

this is my code for processing my form

<?php
session_start();
$url = $_SESSION['redirect_url'];
include('config/config.php');

ini_set('display_errors', '1');
error_reporting(-1);

if (isset($_POST['id'])) {

    $id = $_POST['id'];
    $email = $_POST['email'];
    $categoria = $_POST['categoria'];
 
if($categoria == ''){
    echo 'no se puede guardar a favorito';
}else{
    $favorito = "SELECT * FROM favorito where email = '$email' and id_item = '$id' AND categoria = '$categoria'";
$fav = $conexion->query($favorito);
$id_item = '';
while($row_fav = $fav->fetch_assoc()) {
  $id_item = $row_fav["id_item"];
}

if($id == $id_item){
   $eliminar = "DELETE FROM favorito WHERE email = '$email' and id_item = '$id_item' AND categoria = '$categoria'";
   $delete = mysqli_query($conexion, $eliminar);
   if ($eliminar) {
   // header("Location: $url");
    exit();
} 
}else{
    $insert = "INSERT INTO favorito(id_item, email, categoria) VALUES ('$id','$email','$categoria')";
    $insertar = mysqli_query($conexion, $insert);

    if ($insertar) {
        header("Location: $url");
        exit();
    } 
}
}
}
if (isset($_POST["arrendar"] )) {
    $id = isset($_SESSION["email"]) ? $_SESSION["email"] : "-";
    $nombre = isset($_POST['nombre']) ? $_POST['nombre'] : "-";
    $post = isset($_POST['post']) ? $_POST['post'] : "-";
    $telefono = isset($_POST['telefono']) ? $_POST['telefono'] : "-";
    $whatsapp = isset($_POST['whatsapp']) ? $_POST['whatsapp'] : "-";
    $fijo = isset($_POST['fijo']) ? $_POST['fijo'] : "-";
    $latitud = isset($_POST['latitud']) ? $_POST['latitud'] : "-";
    $longitud = isset($_POST['longitud']) ? $_POST['longitud'] : "-";
    $descripcion = isset($_POST['descripcion']) ? $_POST['descripcion'] : "-";
    $categoria = isset($_POST['categoria']) ? $_POST['categoria'] : "-";
    $habitacion = isset($_POST['habitaciones']) ? $_POST['habitaciones'] : "-";
    $periodo = isset($_POST['periodo']) ? $_POST['periodo'] : "-";
    $precio = isset($_POST['precio']) ? $_POST['precio'] : "-";
    

    // Procesar las imágenes
    $imagenes = $_FILES['imagen']['name'];
    $imagenes_temp = $_FILES['imagen']['tmp_name'];
    $carpeta_destino = "carpeta_destino/".$nombre;

    if (!file_exists($carpeta_destino)) {
        mkdir($carpeta_destino, 0777, true);
    }

    $rutas_imagenes = array();
    for ($i = 0; $i < count($imagenes); $i++) {
        if (!empty($imagenes[$i])) {
            $imagen = $imagenes[$i];
            $imagen_temp = $imagenes_temp[$i];
            $ruta_imagen = "carpeta_destino/".$nombre."/".$imagen;
            move_uploaded_file($imagen_temp, $ruta_imagen);
            $rutas_imagenes[] = $ruta_imagen;
        }
    }

    $ruta_imagenes_string = implode(',', $rutas_imagenes);

   $sql = "INSERT INTO arrendar (id_user, nombre, telefono, post, whatsapp, fijo, latitud, longitud, descripcion, precio, categoria, habitaciones, periodo, img) VALUES ('$id', '$nombre', '$telefono', '$post', '$whatsapp', '$fijo', '$latitud', '$longitud', '$descripcion', '$precio', '$categoria', '$habitacion', '$periodo', '$ruta_imagenes_string')";

    if ($conexion->query($sql) === TRUE) {
    //    header('Location: nuevo_post.php');
    } else {
        echo "Error al guardar el lugar: " . $conexion->error;
    }
}
/////////////////////////////////////////////////////////

if (isset($_POST["vender"] )) {
    $id = isset($_SESSION["email"]) ? $_SESSION["email"] : "-";
$nombre = isset($_POST['nombre']) ? $_POST['nombre'] : "-";
$post = isset($_POST['post']) ? $_POST['post'] : "-";
$telefono = isset($_POST['telefono']) ? $_POST['telefono'] : "-";
$whatsapp = isset($_POST['whatsapp']) ? $_POST['whatsapp'] : "-";
$fijo = isset($_POST['fijo']) ? $_POST['fijo'] : "-";
$latitud = isset($_POST['latitud']) ? $_POST['latitud'] : "-";
$longitud = isset($_POST['longitud']) ? $_POST['longitud'] : "-";
$descripcion = isset($_POST['descripcion']) ? $_POST['descripcion'] : "-";
$categoria = isset($_POST['categoria']) ? $_POST['categoria'] : "-";
$habitacion = isset($_POST['habitaciones']) ? $_POST['habitaciones'] : "-";
$precio = isset($_POST['precio']) ? $_POST['precio'] : "-";


    // Procesar las imágenes
    $imagenes = $_FILES['imagen']['name'];
    $imagenes_temp = $_FILES['imagen']['tmp_name'];
    $carpeta_destino = "carpeta_destino/".$nombre;

    if (!file_exists($carpeta_destino)) {
        mkdir($carpeta_destino, 0777, true);
    }

    $rutas_imagenes = array();
    for ($i = 0; $i < count($imagenes); $i++) {
        if (!empty($imagenes[$i])) {
            $imagen = $imagenes[$i];
            $imagen_temp = $imagenes_temp[$i];
            $ruta_imagen = "carpeta_destino/".$nombre."/".$imagen;
            move_uploaded_file($imagen_temp, $ruta_imagen);
            $rutas_imagenes[] = $ruta_imagen;
        }
    }

    $ruta_imagenes_string = implode(',', $rutas_imagenes);

    $sql = "INSERT INTO tienda (id_user, nombre, telefono, post, whatsapp, fijo, latitud, longitud, descripcion, categoria, habitaciones, precio, img) VALUES ('$id', '$nombre', '$telefono', '$post', '$whatsapp', '$fijo', '$latitud', '$longitud', '$descripcion', '$categoria', '$habitacion', '$precio', '$ruta_imagenes_string')";

    if ($conexion->query($sql) === TRUE) {
    //    header('Location: nuevo_post.php');
    } else {
        echo "Error al guardar el lugar: " . $conexion->error;
    }
}

//////////////////////////////////////////////////////////
if (isset($_POST["trabajo"] )) {
    $id = isset($_SESSION["email"]) ? $_SESSION["email"] : "-";
    $nombre = isset($_POST['nombre']) ? $_POST['nombre'] : "-";
    $post = isset($_POST['post']) ? $_POST['post'] : "-";
    $telefono = isset($_POST['telefono']) ? $_POST['telefono'] : "-";
    $whatsapp = isset($_POST['whatsapp']) ? $_POST['whatsapp'] : "-";
    $fijo = isset($_POST['fijo']) ? $_POST['fijo'] : "-";
    $latitud = isset($_POST['latitud']) ? $_POST['latitud'] : "-";
    $longitud = isset($_POST['longitud']) ? $_POST['longitud'] : "-";
    $descripcion = isset($_POST['descripcion']) ? $_POST['descripcion'] : "-";
    $pago = isset($_POST['pago']) ? $_POST['pago'] : "-";
    $tiempo = isset($_POST['horas']) ? $_POST['horas'].' horas' : "-";
    $salario = isset($_POST['salario']) ? $_POST['salario'] : "-";

    // Procesar las imágenes
    $imagenes = $_FILES['imagen']['name'];
    $imagenes_temp = $_FILES['imagen']['tmp_name'];
    $carpeta_destino = "carpeta_destino/".$nombre;

    if (!file_exists($carpeta_destino)) {
        mkdir($carpeta_destino, 0777, true);
    }

    $rutas_imagenes = array();
    for ($i = 0; $i < count($imagenes); $i++) {
        if (!empty($imagenes[$i])) {
            $imagen = $imagenes[$i];
            $imagen_temp = $imagenes_temp[$i];
            $ruta_imagen = "carpeta_destino/".$nombre."/".$imagen;
            move_uploaded_file($imagen_temp, $ruta_imagen);
            $rutas_imagenes[] = $ruta_imagen;
        }
    }

    $ruta_imagenes_string = implode(',', $rutas_imagenes);

    $sql = "INSERT INTO trabajo (id_user, nombre, telefono, post, whatsapp, fijo, longitud, latitud, descripcion, pago, tiempo, salario, img) 
                    VALUES 
                            ('$id', '$nombre', '$telefono', '$post', '$whatsapp', '$fijo', '$longitud', '$latitud', '$descripcion', '$pago', '$tiempo', '$salario', '$ruta_imagenes_string')";

    if ($conexion->query($sql) === TRUE) {
    //    header('Location: nuevo_post.php');
    } else {
        echo "Error al guardar el lugar: " . $conexion->error;
    }
}
///////////////////////////////////////////////////////////
if (isset($_POST["servicio"] )) {
    $id = isset($_SESSION["email"]) ? $_SESSION["email"] : "-";
$nombre = isset($_POST['nombre']) ? $_POST['nombre'] : "-";
$post = isset($_POST['post']) ? $_POST['post'] : "-";
$telefono = isset($_POST['telefono']) ? $_POST['telefono'] : "-";
$whatsapp = isset($_POST['whatsapp']) ? $_POST['whatsapp'] : "-";
$fijo = isset($_POST['fijo']) ? $_POST['fijo'] : "-";
$latitud = isset($_POST['latitud']) ? $_POST['latitud'] : "-";
$longitud = isset($_POST['longitud']) ? $_POST['longitud'] : "-";
$descripcion = isset($_POST['descripcion']) ? $_POST['descripcion'] : "-";
$categoria = isset($_POST['categoria']) ? $_POST['categoria'] : "-";
$precio = isset($_POST['precio']) ? $_POST['precio'] : "-";

    // Procesar las imágenes
    $imagenes = $_FILES['imagen']['name'];
    $imagenes_temp = $_FILES['imagen']['tmp_name'];
    $carpeta_destino = "carpeta_destino/".$nombre;

    if (!file_exists($carpeta_destino)) {
        mkdir($carpeta_destino, 0777, true);
    }

    $rutas_imagenes = array();
    for ($i = 0; $i < count($imagenes); $i++) {
        if (!empty($imagenes[$i])) {
            $imagen = $imagenes[$i];
            $imagen_temp = $imagenes_temp[$i];
            $ruta_imagen = "carpeta_destino/".$nombre."/".$imagen;
            move_uploaded_file($imagen_temp, $ruta_imagen);
            $rutas_imagenes[] = $ruta_imagen;
        }
    }

    $ruta_imagenes_string = implode(',', $rutas_imagenes);

    $sql = "INSERT INTO servicio (id_user, nombre, telefono, post, whatsapp, fijo, latitud, longitud, descripcion, categoria, precio, img) 
                    VALUES 
                            ('$id', '$nombre', '$telefono', '$post', '$whatsapp', '$fijo', '$latitud', '$longitud', '$descripcion', '$categoria', '$precio', '$ruta_imagenes_string')";

    if ($conexion->query($sql) === TRUE) {
    //    header('Location: nuevo_post.php');
    } else {
        echo "Error al guardar el lugar: " . $conexion->error;
    }
}
$conexion->close();
?>

I ask support and they tell me that everything is fine, the error is mine but I don’t see it, and chatGPT doesn’t see it either.

So does everything before the move work? Does it create a directory? Does that directory have the correct permissions?

yeap, everythin works, the repertoy is created but the file dosnt move, i try 0777 and 0755 and dont work

if you var_dump(move_uploaded_file($imagen_temp, $ruta_imagen));, what does it say?

Still waiting for you to do this ^

show this but i dont know what mean

Array
(
    [imagen] => Array
        (
            [name] => Array
                (
                    [0] => hj.JPG
                    [1] => 
                )

            [type] => Array
                (
                    [0] => 
                    [1] => 
                )

            [tmp_name] => Array
                (
                    [0] => 
                    [1] => 
                )

            [error] => Array
                (
                    [0] => 1
                    [1] => 4
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 0
                )

        )

)

thank you very much was the size of the file i alredy test it and work resizing file

Your code has no useful error handling for the uploaded files. Just testing if the [‘name’] element is not empty() is not sufficient. You must test the [‘error’] element and handle cases where the upload failed due to something the user has control over and cases where they don’t. There a list of error values in the php documentation - https://www.php.net/manual/en/features.file-upload.errors.php For the error 1 value, you should check what the current setting is for upload_max_filesize and set it to a reasonable value. But you must still check the [‘error’] element in your code before using the uploaded file information.

thank you very much for your help

Sorry, I thought it had been fixed but no.

Your statement doesn’t contain any information upon which to help you.

  1. Did it actually work for some file(s)?
  2. Did you make the changes to the setting and to the code that I stated?
  3. What is the current symptom or error?

The rest of the code has a number of problems, where it may work under perfect conditions, but it won’t work and won’t tell you why when anything goes wrong. There is also a lot of unnecessary code. Some of the problems -

  1. If the total size of the form data exceeds the post_max_size setting, both the $_POST and $_FILES arrays will be empty. Your code needs to first detect if a post method form has been submitted, test for this condition, and setup an error message for the user letting them know that that the form data was too large to process, and log an error message letting you (the site owner/developer) know that this has occurred. After your code has tested that there is data in $_POST and $_FILES, you can continue with the form processing code.
  2. Except for unchecked checkbox/radio fields, all other post form fields will be set, even if they are empty. There’s no need to use isset() with these always-set fields and the lines you have doing so don’t do anything useful and should be removed.
  3. Don’t copy variables to other variables for nothing. Keep the post form data as a set, in a php array variable, then operate on elements in this array variable throughout the rest of the code.
  4. You need to trim, mainly so that you can detect when all white-space characters were entered, then validate all the user entered post form data, before using it.
  5. The session variable(s) are inputs to your code. You need to validate them before using them. If it/they are required, but are not set or are empty, you should not display any items on the page, nor process any form data that requires the session variable(s) to be valid.
  6. That you have a session variable containing a redirect url says you are redirecting around on your site. Don’t do this, it sets you site up for a phishing attack. The only redirect you should have is upon successful completion of post method form processing and is should be to the exact same url of the current page to cause a get request for that page. This will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded.
  7. Don’t put dynamic values directly into sql query statements. Use a prepared query instead. If it seems like using prepared queries with the mysqli extension is overly complicated, it is. This would be a good time to switch to the much simpler and better designed PDO extension.
  8. In php8+, the mysqli and PDO extensions use exceptions for errors by default. Any discrete error handling logic you have now will never get executed upon an error and should be removed, simplifying the code.
  9. If any insert/update query could result in duplicate data, the column(s) that must be unique need to be defined as a unique index. You would then test in the exception catch block if a duplicate index error number occurred, and setup a message for the user letting them know that they submitted duplicate data.

Lastly, you have 4 similar blocks of form processing code, that only differ in some fields/columns and the table name. Don’t Repeat Yourself (DRY.) Instead of writing out all this code, dynamically validate and process the form data, by defining an array of expected fields for each different operation. You would then loop over the correct definition to validate the input data, build the sql query statement, and build an array of input data to execute the prepared query with.

sorry the code was perfect but the problem was in php.ini and i talk to support and they change the max size to 8mb and alredy work perfect. thanks for every thin

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.