I am trying to upload a simple image file to my project using php and html but when I submit the form, either the _FILE method is empty or the _POST method is empty. My code never makes it passed the if statement checking that all fields are not empty, as I get the error: "All fields are mandatory, please fill all the fields."
Here is my CRUD.php file up until the error message:
// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();
$tblName = 'image';
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
// Allow file formats
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
// Set default redirect url
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
$statusMsg = '';
$sessData = array();
$statusType = 'danger';
// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
//Set redirect url
$redirectURL = PUBLIC_PATH . '/addEdit.php';
//Get submitted data and clean it from injections
$id = $_POST['id'];
$image = $_FILES['image'];
echo $image['name'];
//Store title variable without any html or php tags and trims whitespace from beginning and end
$title = strip_tags(trim($_POST['title']));
// Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input
$regex = '/^[ ,]*[a-zA-Z0-9] (?:[ ,] [a-zA-Z0-9] ){0,5}[ ,]*$/';
if (preg_match($regex, $_POST['tags']) == 0) {
exit('Tags are not valid!');
}
// Makes all tags lower case
$tag_input = strtolower($_POST['tags']);
// Clean up multiple commas or whitespaces
$clean_tag_input = preg_replace('/[\s,] /', ' ', $tag_input);
// Replaces spaces with commas
$comma_tags = str_replace(' ', ',', $clean_tag_input);
// Submitted user data
$imgData = array('title' => $title,'tags' => $comma_tags);
// Store submitted data into session
$sessData['postData'] = $imgData;
$sessData['postData']['id'] = $id;
// ID query string
$idStr = !empty($id)?'?id='.$id:'';
// If the data is not empty
if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
echo $title;
if(!empty($image)) {
$filename = basename($image['name']);
// Get file extension in lower case
$fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
echo $fileType;
// Generate a unique name for the image to prevent throwing exists error
$unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;
// The path of the new uploaded image
$targetFilePath = $uploadDir . $unique_image_name;
echo $targetFilePath;
if (in_array($fileType, $allowTypes)) {
// Check to make sure the image is valid
if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {
if (file_exists($unique_image_name)) {
$statusMsg = 'Image already exists, please choose another or rename that image.';
} else if ($image['size'] > 500000) {
$statusMsg = 'Image file size too large, please choose an image less than 500kb.';
} else {
// Everything checks out now we can move the uploaded image
if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
$imgData['filename'] = $unique_image_name;
$imgData['username'] = $_SESSION['username'];
} else {
$statusMsg = 'Sorry, there was an error uploading your file.';
}
}
}
} else {
$statusMsg = 'Image file is empty or corrupt.';
}
} else {
$statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
}
} else {
$statusMsg = 'Sorry something went wrong.';
}
if (!empty($id)) {
// Previous filename
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$prevData = $imageDB->getRows('image', $conditions);
// Update data
$condition = array('id' => $id);
$update = $imageDB->update($tblName, $imgData, $condition);
if($update) {
//Remove old file from server
if (!empty($imgData['filename'])) {
@unlink($uploadDir . $prevData['filename']);
}
$statusType = 'success';
$statusMsg = 'Image data has been updated successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
//Set redirect url
$redirectURL .= $idStr;
}
} elseif (!empty($imgData['filename'])) {
// Insert data
$insert = $imageDB->insert($tblName, $imgData);
if ($insert) {
$statusType = 'success';
$statusMsg = 'Image has been uploaded successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
}
} else {
$statusMsg = 'All fields are mandatory, please fill all the fields.';
}
And here is my addEdit.php file with the form:
require_once(ROOT_DIR . '/Templates/header.php');
$postData = $imgData = array();
$newViewkey = uniqid();
// Get image data
if (!empty($_GET['imageID'])) {
//include and initialize DB class
require_once(ROOT_DIR . '/Classes/database.class.php');
$addEditDB = new DB();
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$imgData = $addEditDB->getRows('image', $conditions);
}
// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;
// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';
head('Upload Image', $_SESSION['username'])
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div >
<?php echo $statusMsg; ?>
</div>
<?php } ?>
<div >
<h1>Upload Image</h1>
<form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
<label for="title">Title</label>
<input
type="text" name="title" id="title"
placeholder="Type image title here."
value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>
<?php if (!empty($imgData['tags'])) {
$tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
} ?>
<label for="tags">Tags</label>
<textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','." required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>
<input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">
<input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">
<?php if (!empty($imgData['filename'])) { ?>
<div>
<img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >
</div>
<?php } ?>
<input type="submit" value="Upload" name="imgSubmit">
</form>
<div >
<a href="manageUploads.php">Back to Manage Uploads</a>
</div>
</div>
<?php require_once(ROOT_DIR . '/Templates/footer.php')?>
And finally here is my config.php file with all the path definitions:
/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');
/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);
/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
or define('ROOT_DIR', dirname(__FILE__));
defined('SRC_DIR')
or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');
defined('PUBLIC_PATH')
or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('LAYOUT_PATH')
or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');
defined('CSS_PATH')
or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');
defined('JS_PATH')
or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');
defined('LIBRARY_PATH')
or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');
defined('CLASSES_PATH')
or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');
defined('TEMPLATES_PATH')
or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");
defined('IMAGE_UTIL_PATH')
or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');
defined('RATING_UTIL_PATH')
or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');
defined('USER_UTIL_PATH')
or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');
?>
And here is my php error log:
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg): Failed to open stream: No such file or directory in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116 [10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(): Unable to move "C:\xampp\tmp\phpCCA.tmp" to "/Shape_Search/public_html/img/content/973439_1644497526.jpg" in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
CodePudding user response:
It was an issue of directory vs. path.
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
Should be corrected to:
// The folder where the images will be stored
$uploadDir = CONTENT_DIR . '/';
Where the global variables CONTENT_PATH and CONTENT_DIR are:
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('CONTENT_DIR')
or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');