Home Error PHP - move_uploaded_file() Unable to move file from tmp to dir
Post
Cancel

Error PHP - move_uploaded_file() Unable to move file from tmp to dir

Issue

Ketika Anda memiliki website semacam online show atau komersil lain, saat hendak menambahkan produk berserta image muncul error seperti berikut.

[10-Aug-2023 05:16:45 UTC] PHP Warning:  move_uploaded_file(uploads/thumb_470.webp): Failed to open stream: No such file or directory in /home/user/public_html/add_product.php on line 19
[10-Aug-2023 05:16:45 UTC] PHP Warning:  move_uploaded_file(): Unable to move '/tmp/phpZwx3da' to 'uploads/thumb_470.webp' in /home/user/public_html/add_product.php on line 19

Kode yang digunakan

1
2
3
4
5
$image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
$image_path = "uploads/" . $image;

move_uploaded_file($image_tmp, $image_path);

Solution

Perbaiki kode menjadi seperti berikut.

1
2
3
4
5
6
7
8
$image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];

// perbaikan kode
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$image_path = $destination_path . "uploads/" . $image;
// $image_path = 'uploads/' . $image;
move_uploaded_file($image_tmp, $image_path);

Penjelasan dari perbaikan tersebut:

  • Buat variable $destination_path dengan fungsi getcwd().DIRECTORY_SEPARATOR untuk mendapatkan direktor kerja yang digunakan saat ini. Lalu dengan DIRECTORY_SEPARATOR pemisah direktori (slash atau backslash) tergantung pada sistem operasi yang digunakan.
  • Perbaiki variable $image_path dengan menambahkan $destination_path untuk membentuk path lengkap ke lokasi tujuan penyimpanan gambar yang diunggah.

Selanjutnya dapat dicoba menambahkan produk berserta image yang akan digunakan.

This post is licensed under CC BY 4.0 by the author.