Thứ Năm, 15 tháng 1, 2026

Thay cho input fiile thông thường

==== html

<input type="file" id="avatar-file" name="savepic" hidden multiple style="display: none;">

  <button type="button" id="choose-button-img" class="btn btn-primary">
        <i class="fa fa-picture-o"></i>  Chọn hình ảnh liên quan
  </button>

 <script>
    document.getElementById('choose-button-img').onclick = function () {

        document.getElementById('avatar-file').click();
    };
</script>

==== Save Pic

function uploads__savepic(){

    if (empty($_FILES['savepic']['name'])) {

        return '';

    }

    // $upload_dir = "uploads/News/pic";

    $upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/uploads/News/pic/";

    if (!is_dir($upload_dir)) {

        mkdir($upload_dir, 0777, true);

    }

    $name     = $_FILES['savepic']['name'];

    $tmp_name = $_FILES['savepic']['tmp_name'];

    $error    = $_FILES['savepic']['error'];

    if ($error != 0) {
        return '';
    }

    $info = pathinfo($name);

    $filename = preg_replace('/[^a-zA-Z0-9-_]/', '-', $info['filename']);

    $filename = trim($filename, '-');

    $ext = strtolower($info['extension']);

    // chỉ cho phép ảnh

    $allow = array('jpg','jpeg','png','gif','webp');

    if (!in_array($ext, $allow)) {

        return '';

    }

    $new_name = $filename.'.'.$ext;

    $path = $upload_dir.$new_name;


    // nếu trùng tên → thêm (1)(2)...

    $i = 1;

    while (file_exists($path)) {

        $new_name = $filename.'('.$i.').'.$ext;

        $path = $upload_dir.$new_name;

        $i++;

    }

    if (move_uploaded_file($tmp_name, $path)) {

        return $new_name; // ✅ RETURN TÊN FILE

    }

    return '';

}

Không có nhận xét nào:

Đăng nhận xét