Upload Sederhana Menggunakan PHP
<?php // http://www.touchoftechnology.com/simple-way-to-clean-up-filenames-in-php/ function safe_file_upload_name($str, $separator = '') { return preg_replace('/[^a-z0-9\.]/', $separator, strtolower($str)); } function my_err_msg() { echo '<h1 style=background:red;color:yellow>', implode(' ', func_get_args()), '</h1>'; } function my_log_msg() { echo '<pre style=background:#333;color:#eee>'; foreach (func_get_args() as $a) print_r($a); echo "</pre>"; } $file_destination = date('YmdHis') . '_'; $is_upload_ready = $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['myfile']); if (!empty($_GET['delete'])) { $file = basename($_GET['delete']); if ($file === substr(basename(__FILE__), 0, 50)) { $var_err = 'Tidak bisa hapus file ini.'; } elseif (file_exists($file)) { if (@unlink($file)) { $var_log = 'Berhasil menghapus file.'; } else { $var_err = 'Gagal menghapus file.'; } } else { $var_err = 'File tidak ditemukan.'; } } if ($is_upload_ready) { $myfile = $_FILES['myfile']; if ($myfile['error'] === UPLOAD_ERR_OK) { $file_destination .= substr(safe_file_upload_name($myfile['name']), -25); if (@move_uploaded_file($myfile['tmp_name'], $file_destination) === false) { $var_err = 'Gagal memindah file.'; } else { $var_log = 'Berhasil mengunggah file. <b>' . $file_destination . '</b>'; } } else { my_err_msg('[ERROR]: Tidak bisa file.'); } } ?><!DOCTYPE html> <html lang="id"> <head> <meta charset="UTF-8"/> <title>20170329</title> </head> <body style="background-color: #222; color: #fff;font-family: monospace;"> <?php if(isset($var_err)) my_err_msg('[ERROR]:', $var_err); ?> <?php if(isset($var_log)) my_log_msg($var_log); ?> <?php /* diberi action=x. supaya-jika di _GETnya ada param lain, akan di timpa. misal, ?rename=x akan membuat kode menampilkan error. */ ?> <form method="post" action="?post" enctype="multipart/form-data"> <input type="file" name="myfile"/> <button type="submit">unggah</button> </form> </body> </html>
Dibuat pada Rab, Mar 29 2017 13:55:50
Komentar
Posting Komentar
Komentar ...