Skip to main content

JS FormData Image Upload to PHP Image can not be uploaded

i want to upload an image over Ajax and PHP. To get the Image i use FormData. The Ajax call is working fine from my point of view, but in my PHP code I always get the Error

Fatal error Uncaught ValueError: Path cannot be empty in C:\xampp\htdocs\fitnesslaeufer-redesign\profile\includes\settings\profile-settings-update-image.php:43

Stack trace: #0 C:\xampp\htdocs\fitnesslaeufer-redesign\profile\includes\settings\profile-settings-update-image.php(43): getimagesize('')

#1 C:\xampp\htdocs\fitnesslaeufer-redesign\profile\includes\settings\profile-settings-update-image.php(2): update_user_image()

#2 {main} thrown in C:\xampp\htdocs\fitnesslaeufer-redesign\profile\includes\settings\profile-settings-update-image.php on line 43
"

when I want to get informations ($fileinfo) about the image that is uploaded.

I tried to find a solution in some Posts but nothing helped to solve my problem.

For the Background I know how to upload an Image with PHP and now I want to update my image upload to Ajax / JS so that I can use SweetAlert2.

PHP Code:

    if(isset($_GET['user_id'])) {
        $user_id = mysqli_real_escape_string($connection, $_GET['user_id']);
    }

    $get_user_information = $connection->prepare("SELECT user_id, user_username, user_logo FROM user WHERE user_id = ?");
    $get_user_information->bind_param("s", $user_id);
    $get_user_information->execute();
    $result = $get_user_information->get_result();
    $row = $result->fetch_assoc();

    $user_id = $row['user_id'];
    $user_username = $row['user_username'];
    $user_logo_old = $row['user_logo'];

    $get_user_information->close();
    
    if($user_id > 0) {
        $targetDir = "../assets/img/users/";
        $allowed_image_extensions = array("png","jpg","jpeg","PNG","JPG","JPEG");

        if(isset($_FILES['user_logo']) && !empty($_FILES['user_logo']['name'])) {

            $fileinfo = @getimagesize($_FILES['user_logo']['tmp_name']);
            $width = $fileinfo[0];
            $height = $fileinfo[1];

            $user_image = pathinfo($_FILES['user_logo']['name'], PATHINFO_EXTENSION);
            if(!in_array($user_image, $allowed_image_extensions)) {
                echo "extension";
                exit;
            } else if(($_FILES['user_logo']['size'] > 1048576)) {
                echo "large";
                exit;
            } else if($width > "500" || $height > "500") {
                echo "size";
                exit;
            } else {
                unlink("../assets/img/users/$user_logo_old");
                $user_logo_new = $user_id.$user_username;
            }

            move_uploaded_file($_FILES['user_logo']['tmp_name'], $targetDir.$user_logo_new.".".$user_image);

            $user_logo_path = $user_logo_new.".".$user_image;

            $update_user_informations = $connection->prepare("UPDATE user SET user_logo = ? WHERE user_id = ?");
            $update_user_informations->bind_param("ss", $user_logo_path, $user_id);
            $update_user_informations->execute();
            $update_user_informations->close();

            echo 1;
            exit;

        } else {
            $get_user_logo = $connection->prepare("SELECT user_logo FROM user WHERE user_id = ?");
            $get_user_logo->bind_param("s", $user_id);
            $get_user_logo->execute();
            $result = $get_user_logo->get_result();
            $row = $result->fetch_assoc();

            $user_logo_path = $row['user_logo'];

            $get_user_logo->close();

            $update_user_informations = $connection->prepare("UPDATE user SET user_logo = ? WHERE user_id = ?");
            $update_user_informations->bind_param("ss", $user_logo_path, $user_id);
            $update_user_informations->execute();
            $update_user_informations->close();
            
            echo 0;
            exit;
        }
        echo 0;
        exit;
    }

JS Code cutout:

....
const user_id = getCookie('user_id');

var formData = new FormData();
var file = $('#user_logo');
formData.append('file', file);

$.ajax({
   url: "../profile/includes/settings/profile-settings-update-image.php?user_id=" + user_id,
   method: "POST",
   data: formData,
   contentType: false,
   cache: false,
   processData:false,
   success: function(response) {
       if(response == 1) {
           Swal.fire({
             title: "Profile picture is changed!",
             type: "success",
             closeOnConfirm: true
           });
        } else {
           Swal.fire({
              title: "Something went wrong!",
              type: "error",
              closeOnConfirm: true
           });
        }
   }
})
....


source https://stackoverflow.com/questions/68975931/js-formdata-image-upload-to-php-image-can-not-be-uploaded

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...