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

Source code Template website sekolah dengan react js

Bismillaahirrohmaanirrohiim... Berikut ini source code yang dapat dimodifikasi untuk membuat front end website sekolah dengan…

6 days ago

Subdomain pada cyberpanel tidak dapat diakses

Bismillaahirrohmaanirrohiim... Jika domain dan sub domainnya berada dalam satu vps cyberpanel, maka seringkali jadi tidak…

2 weeks ago

10 Aplikasi Kasir Terbaik di Indonesia (2025)

Bismillaahirrohmaanirrohiim... Dalam era digital saat ini, penggunaan aplikasi kasir (Point of Sale/POS) menjadi solusi penting…

2 weeks ago

Website di aapanel sering mati sendiri

Bismillaahirrohmaanirrohiim... Saat browsing-browsing saya seringkali melihat iklan aapanel, sekilas membuat penasaran sampai akhirnya saya mencoba…

2 weeks ago

Reset password cyberpanel via SSH

Bismillaahirrohmaanirrohiim... Berikut ini perintah untuk reset password admin cyberpanel melalui SSH command line. pastikan login…

2 weeks ago

Template Blogger Blogspot Gratis dan Bagus

Bismillaahirrohmaanirrohiim... Berikut ini beberapa template blogspot yang dapat anda gunakan secara gratis namun tampilannya bagus.…

2 months ago