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

Cara Mematikan Mode SSL Virtualmin Webmin

Bismillaahirrohmaanirrohiim... masalah muncul saat akses https://ipaddress:10000 muncul seperti ini Error – Document follows This web…

2 weeks ago

eBook: menjadi kaya dimasa kini dan masa depan

Bismillahirrohmaanirrohiim... Ebook ini menghadirkan wawasan mendalam mengenai pergeseran kekayaan dari uang, aset, tanah, dan bahan…

4 weeks ago

Tombol back tutup modal bootstrap tanpa kembali ke halaman sebelumnya

Bismillaahirrohmaanirrohiim... Jika kita membuat aplikasi web base menggunakan bootstrap, saat user membuka modal, kadangkala mereka…

4 weeks ago

Kode css yang berguna

Bismillaahirrohmaanirrohiim... Berikut ini kumpulan css yang berguna, untuk mengingat saja. Input atau button delay saat…

1 month ago

Grouping warna pada tabel dengan PHP

Bismillaahirrohmaanirrohiim... Berikut ini cara grouping warna baris pada tabel dengan PHP, dimana jika ada kode…

1 month ago

CMS Website Desain Interior – PHP MySQL

CMS (Content Management System) Web untuk Desain Interior adalah solusi lengkap untuk mempresentasikan bisnis desain…

2 months ago