Created
March 31, 2015 04:49
-
-
Save cahsowan/6d64c82a0bebdaca6cae to your computer and use it in GitHub Desktop.
Example of upload file using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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