Skip to content

Instantly share code, notes, and snippets.

@cahsowan
Created March 31, 2015 04:49
Show Gist options
  • Save cahsowan/6d64c82a0bebdaca6cae to your computer and use it in GitHub Desktop.
Save cahsowan/6d64c82a0bebdaca6cae to your computer and use it in GitHub Desktop.
Example of upload file using PHP
<?php
$data = json_decode(file_get_contents('data.txt'), true) ?: [];
$upload_directory = 'upload/';
if ($_POST) {
$fruit = $_POST['fruit'];
$picture = $_FILES['picture'];
if (! empty($fruit) && file_exists($picture['tmp_name'])) {
$data[$fruit] = $upload_directory . $picture['name'];
file_put_contents('data.txt', json_encode($data));
if (move_uploaded_file($picture['tmp_name'], $upload_directory . $picture['name'])) {
print 'file tersimpan';
} else {
print 'gagal menyimpan file';
}
} else {
die('pastikan form terisi');
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>
<h1>Mengunggah Berkas</h1>
<form action="<?php $PHP_SELF ?>" method="POST" enctype="multipart/form-data">
<p>
<label for="fruit">Buah Kesukaanmu</label>
<input type="text" name="fruit">
</p>
<p>
<label for="picture">Gambar Buah</label>
<input type="file" name="picture">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
<hr>
<?php if (! empty($data)): ?>
<table border="1">
<tr>
<th>Nama</th>
<th>Gambar</th>
</tr>
<?php foreach ($data as $fruit => $path): ?>
<tr>
<td><?php print $fruit ?></td>
<td><img src="<?php print $path ?>" alt=""></td>
</tr>
<?php endforeach ?>
</table>
<?php endif ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment