Categories: PHP

Upload multiple file menggunakan PHP CURL mudah

Bismillahirrohmaanirrohiim…

Segala puji bagi Allah SWT yang memberikan kita segala nikmat yang tak terhingga banyaknya…

Di sini saya ingin menuliskan kode cara upload multiple file dengan PHP CURL, tentunya dengan tujuan remote API.

Berikut kode client nya:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title>Upload API</title>
  </head>
  <body>

<form action="uploadapi.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <br /><br />
    <input type="text" name="param" value="coba" />
    <br />
    <input type="file" name="upload_file[]" />
    <br />
    <input type="file" name="upload_file[]" />
    <br /><br />
    <input type="submit" value="Upload Files" name="submit">
</form>

<?php
if (isset($_POST['param'])) {
    
    $postfields = array();
    
    $upload_file = (isset($_FILES['upload_file'])) ? $_FILES['upload_file'] : array();
    
    if (isset($upload_file['name'])) {
        
        foreach ($upload_file["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK) {
            
                if (function_exists('curl_file_create')) { // For PHP 5.5+
                    $postfields["upload_file[$key]"] = curl_file_create(
                        $upload_file['tmp_name'][$key],
                        $upload_file['type'][$key],
                        $upload_file['name'][$key]
                    );
                    
                } else {
                    $postfields["upload_file[$key]"] = '@' . realpath(
                        $upload_file['tmp_name'][$key],
                        $upload_file['type'][$key],
                        $upload_file['name'][$key]
                    );

                }
                    //$file = curl_file_create($file);
                   //$file = '@' . realpath($file);
         
            }
        }
    }
    
    $postfields['param'] = $_POST['param'];
    
    $ch = curl_init();
    $headers = array("Content-Type:multipart/form-data");
    curl_setopt_array($ch, array(
        CURLOPT_POST => 1,
        CURLOPT_URL => "http://urlapi/test.upload.php",
        CURLOPT_RETURNTRANSFER => 1,
        CURLINFO_HEADER_OUT => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields
    ));
    
    $result = curl_exec($ch);
    
    curl_close ($ch);
    echo '<hr />';
    
    echo $result;

}

?>

  </body>
</html>

 

Dan di bawah ini adalah kode di server nya:

//start proses files
$upload_file = (isset($_FILES['upload_file'])) ? $_FILES['upload_file'] : array();


$count = 0;
$message = array();
$upload_file_name = array();
if (isset($upload_file['name'])) {
    $valid_formats = array("jpg", "png", "gif", "zip", "rar", "7z", "gzip", "bmp", "pdf", "doc", "docx", "rtf", "html", "odt", "txt");

    $max_file_size = 1024*50000; //50000 kb
    $path = dirname(__FILE__)."/";
    $dirname = "uploads/".date('Y-m')."/";
    if (!is_dir($path.$dirname)) {
        if(!mkdir($path.$dirname, 0777, true)) {
            $err_msg = 'Gagal dalam membuat folder upload.';
            errorResponse('custom_msg', $queries, $err_msg);
        }

    }



    foreach ($upload_file['name'] as $f => $name) {
        if ($upload_file['error'][$f] == 4) {
            continue; // Skip file if any error found
        }

        if ($upload_file['error'][$f] == 0) {
            $ext = pathinfo($name, PATHINFO_EXTENSION);
            $ext = strtolower($ext);
            if ($upload_file['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }

            elseif( ! in_array($ext, $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }

            else { // No error found! Move uploaded files
                $name_file = $dirname.date('dHis').'_'.$name;
                if (@move_uploaded_file($upload_file["tmp_name"][$f], $path.$name_file)) {
                    $count++; // Number of successfully uploaded file
                    $upload_file_name[] = $name_file.' => '.$path.$name_file;
                }
            }
        }
    }


}

echo 'uploaded: '.$count.' file(s)';
//finish proses files

if (count($message)) {
  echo '<pre>';
  print_r($message);
  echo '</pre>';
}
if (count($upload_file_name)) {
  echo '<pre>';
  print_r($upload_file_name);
  echo '</pre>';
}

echo '<h3>REQUEST</h3>';
if (count($_REQUEST)) {
  echo '<pre>';
  print_r($_REQUEST);
  echo '</pre>';
}

Demikian, silahkan dicoba sendiri 🙂

Bagikan
rasupe

Recent Posts

Aplikasi Bimbel – Les – Private – Training Multifungsi

🚀 Kelola Bimbel / Les / Private Jadi Lebih Mudah & Profesional! Apakah Anda masih…

3 weeks ago

Script PosKasir, miliki sendiri untuk bisnis Anda

🚀 Punya Usaha Tapi Masih Pakai Kasir Manual? Ini Solusi yang Lebih Cerdas! Mengelola bisnis…

3 weeks ago

Aplikasi Manajemen RT Berbasis PHP & MySQL

Solusi Digital untuk Administrasi RT yang Transparan dan Efisien Di era digital seperti sekarang, pengelolaan…

3 months ago

Script Aplikasi Booking System + AI (PHP & MySQL)

Solusi Booking Otomatis untuk Berbagai Jenis Bisnis Sedang mencari script aplikasi booking sistem lengkap dengan…

4 months ago

compress gambar sebelum diupload dengan javascript

Bismillaahirrohmaanirrohiim... Berikut ini cara kompress gambar sebelum diupload menggunakan javascript, tujuannya agar misalkan gambar dari…

6 months ago

Format angka dengan javascript

Bismillaahirrohmaanirrohiim... Berikut ini cara format angka menggunakan javascript, misalkan 1000 menjadi 1.000 atau 1500000 menjadi…

7 months ago