This takes a name, 2 images and a birthday for an artist, uploads images and insert info into MySQL. I seem to be missing something and I'm looking to see if I'm following best practices.
<?php
require_once '../config.php';
require 'includes/functions.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Admin Area</title>
</head>
<body>
<h1>Add Artist</h1>
<?php
if (isset($_FILES['artist_thumb'], $_FILES['artist_profile_image']) === true) {
$thumb_name = $_FILES['artist_thumb']['name'];
$profile_image_name = $_FILES['artist_profile_image']['name'];
// Checking if extension allowed
$allowed_ext = array('jpeg','jpg','gif','png');
$thumb_ext = explode('.',$thumb_name);
$thumb_ext = strtolower(end($thumb_ext));
$profile_image_ext = explode('.',$profile_image_name);
$profile_image_ext = strtolower(end($profile_image_ext));
$errors =array();
if (in_array($thumb_ext, $allowed_ext) === false || in_array($profile_image_ext, $allowed_ext) === false) {
$errors[] = 'File type not allowed';
}
// If there is any error echo it
if (!empty($errors)) {
echo output_errors($errors);
} else {
// Upload image
$thumb_tmp = $_FILES['artist_thumb']['tmp'];
$profile_image_tmp = $_FILES['artist_profile_image']['tmp'];
$thumb_dir = upload_image($thumb_tmp, $thumb_name);
$profile_image_dir = upload_image($profile_image_tmp, $profile_image_name);
}
}
if (empty($_POST) === false) {
$required_fields = array('artist_name', 'artist_thumb', 'artist_profile_image', 'birthday');
foreach ($_POST as $key => $value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterstrik are required';
break 1;
}
}
}
if (isset($_GET['success'])) {
echo 'You\'ve added a new artist.';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$artist_data = array(
'artist_name' => $_POST['artist_name'],
'artist_thumb' => $thumb_dir,
'artist_profile_image' => $profile_image_dir,
'birthday' => $_POST['birthday'],
);
add_artist($artist_data);
header('Location: add_artist.php?success');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li>
Artist Name*: <input type="text" name="artist_name">
</li>
<li>
Choose an image: <input type="file" name="artist_thumb">
<!--Artist Thumbnail*: <input type="text" name="artist_thumb">-->
</li>
<li>
Choose an image: <input type="file" name="artist_profile_image">
<!--Artist Profile Image*: <input type="text" name="artist_profile_image">-->
</li>
<li>
Birthday*:
<input type="date" name="birthday">
</li>
<li>
<input type="submit" value="Add Artist">
</li>
</ul>
</form>
<?php } ?>
</body>
</html>
Upload image function:
<?php
// Upload image function
function upload_image($tmp,$name) {
$name = time() . $name;
$upload_dir = 'images/new/';
move_uploaded_file($tmp,$upload_dir.$name);
return $upload_dir . $name;
}
?>