I'm working on uploading an image file from a form to a folder on the server and recording the location in a mysql db via PHP and I'm having a lot of trouble with it. Currently this is my html code for the form:
<body>
<div class="container">
<form action="upload.php" method="post" class="m-auto" style="max-width:600px">
<h3 class="my-4"><?php echo "{$family_info['Family_Name']} Family Image Upload";?></h3>
<hr class="my-4" />
<div class="form-group mb-3 row"><label for="family_mem5" class="col-md-5 col-form-label">Family Member</label>
<div class="col-md-7"><select class="form-select custom-select custom-select-lg" name= "family_mem" id="family_mem5">
<option></option>
<?php
while($row = $family_members-> fetch_array(MYSQLI_BOTH))
{
echo "<option value='".$row['Family_Member']."'>".$row['Family_Member']."</option>";
}
?>
</select><small class="form-text text-muted">Please select a family member to upload a photo for.</small></div>
</div>
<hr class="bg-transparent border-0 py-1" />
<div class="form-group mb-3 row">
<label for="image1" class="col-md-5 col-form-label">Image</label>
<div class="col-md-7"><input type="file" class="form-control form-control-lg" id="image1" name="image" required><small class="form-text text-muted">Please select an image.</small></div>
</div>
<hr class="my-4" />
<div class="form-group mb-3 row"><label for="upload-image8" class="col-md-5 col-form-label"></label>
<div class="col-md-7"><button class="btn btn-primary btn-lg" type="submit" name="submit" id="submit">Upload Image</button></div>
</div>
</form>
</div>
This is my PHP code for the upload.php file that the form POSTs to.
<?php
session_start();
$membernumber = $_SESSION['membernumber'];
$family_member = $_POST['family_mem'];
echo "Member Number: ".$membernumber;
echo "<br />";
echo "Family Member: ".$family_member;
echo "<br />";
/*
* Custom function to compress image size and
* upload to the server using PHP
*/
function compressImage($source, $destination, $quality) {
// Get image info
$imgInfo = getimagesize($source);
$mime = $imgInfo['mime'];
// Create a new image from file
switch($mime){
case 'image/jpeg':
$image = imagecreatefromjpeg($source);
break;
case 'image/png':
$image = imagecreatefrompng($source);
break;
case 'image/gif':
$image = imagecreatefromgif($source);
break;
default:
$image = imagecreatefromjpeg($source);
}
// Save image
imagejpeg($image, $destination, $quality);
// Return compressed image
return $destination;
}
// File upload path
$uploadPath = "uploads/";
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
echo "empty";
}
// If file upload form is submitted
$status = $statusMsg = 'Image uploaded for so and so';
if(isset($_POST["submit"]))
{
$status = 'error';
if(!empty($_FILES["image"]["name"]))
{
// File info
$file = $_FILES['image']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
$fileName = "$family_member.$ext";
echo 'Filename: '.$fileName;
$imageUploadPath = $uploadPath . $fileName;
$fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','JPG','png','jpeg','gif');
if(in_array($fileType, $allowTypes))
{
// Image temp source
$imageTemp = $_FILES["image"]["tmp_name"];
$imageSize = $_FILES["image"]["size"];
// Compress size and upload image
$compressedImage = compressImage($imageTemp, $imageUploadPath, 75);
if($compressedImage)
{
$compressedImageSize = filesize($compressedImage);
$status = 'success';
// $statusMsg = "Image compressed successfully.";
}
else
{
$statusMsg = "Image compress failed!";
}
}
else
{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}
else
{
$statusMsg = 'Please select an image file to upload.';
}
}
// Display status message
echo $statusMsg;
?>
The issue is that the image file is showing up empty as you can see from the check empty code, as if it never makes it over. What could I be doing wrong? I've gotten the upload working in smaller example code before but as soon as I start adding features it falls apart. Right now I'm lost as to why it does not pass the file from the form.
Thank you very much for any help. I'm surprised by how hard moving files is in PHP, or maybe how clueless I am lol.
Related
I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>
I am trying to make an avatar image upload for user, where they can crop the avatar too. At this moment I'm able to save the normal size of the image on my server, but when I am trying to crop that image it's like the coordinates are fixed, I think on the left top corner.
Here is my form in accounts.php:
<a href="#" data-toggle="modal" data-target="#change-profile">
<div id="profile-result">
<?php if (file_exists('accounts/images/' . $session_username . '.jpg')): ?>
<img src="<?php echo 'accounts/images/' . $session_username . '.jpg'; ?>" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php else: ?>
<img src="accounts/images/default.png" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php endif ?>
</div>
</a>
<div class="modal fade" id="change-profile">
<div class="modal-dialog">
<div class="" style="background: #fff; padding: 10px;">
<div class="ajax-response" id="loading"></div>
<h4 class="m-t-5 m-b-5 ellipsis">Change profile</h4>
<div class="image-full-div" style="width: 70%;">
<form action="crop.php" enctype="multipart/form-data" method="post" onsubmit="return checkCoords();">
<p>Image: <input name="image" id="fileInput" type="file" /></p>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input name="upload" type="submit" value="Upload" />
</form>
<p><img id="filePreview" style="display:none;"/></p>
</div>
</div>
</div>
</div>
This is my crop.php file for the upload:
<?php
//if upload form is submitted
if(isset($_POST["upload"])){
//get the file information
$error = '';
$fileName = basename($_FILES["image"]["name"]);
$fileTmp = $_FILES["image"]["tmp_name"];
$fileType = $_FILES["image"]["type"];
$fileSize = $_FILES["image"]["size"];
$fileExt = substr($fileName, strrpos($fileName, ".") + 1);
//specify image upload directory
$largeImageLoc = 'accounts/images/'.$fileName;
$thumbImageLoc = 'accounts/images/thumb/'.$fileName;
//check file extension
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
if($fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png"){
$error = "Sorry, only JPG, JPEG & PNG files are allowed.";
}
}else{
$error = "Select a JPG, JPEG & PNG image to upload";
}
//if everything is ok, try to upload file
if(strlen($error) == 0 && !empty($fileName)){
if(move_uploaded_file($fileTmp, $largeImageLoc)){
//file permission
chmod ($largeImageLoc, 0777);
//get dimensions of the original image
list($width_org, $height_org) = getimagesize($largeImageLoc);
//get image coords
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$width = (int) $_POST['w'];
$height = (int) $_POST['h'];
//define the final size of the cropped image
$width_new = $width;
$height_new = $height;
//crop and resize image
$newImage = imagecreatetruecolor($width_new,$height_new);
switch($fileType) {
case "image/gif":
$source = imagecreatefromgif($largeImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($largeImageLoc);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($largeImageLoc);
break;
}
imagecopyresampled($newImage,$source,0,0,$x,$y,$width_new,$height_new,$width,$height);
switch($fileType) {
case "image/gif":
imagegif($newImage,$thumbImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumbImageLoc,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumbImageLoc);
break;
}
imagedestroy($newImage);
//remove large image
//unlink($imageUploadLoc);
//display cropped image
echo 'CROP IMAGE:<br/><img src="'.$thumbImageLoc.'"/>';
}else{
$error = "Sorry, there was an error uploading your file.";
}
}else{
//display error
echo $error;
}
}
?>
And my Javascript file:
//set image coordinates
function updateCoords(im,obj){
$('#x').val(obj.x1);
$('#y').val(obj.y1);
$('#w').val(obj.width);
$('#h').val(obj.height);
}
//check coordinates
function checkCoords(){
if(parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
}
$(document).ready(function(){
//prepare instant image preview
var p = $("#filePreview");
$("#fileInput").change(function(){
//fadeOut or hide preview
p.fadeOut();
//prepare HTML5 FileReader
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("fileInput").files[0]);
oFReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
//implement imgAreaSelect plugin
$('img#filePreview').imgAreaSelect({
// set crop ratio (optional)
//aspectRatio: '2:1',
onSelectEnd: updateCoords
});
});
This is my image with the coordinates but I'm not sure because the normal size of the image is 1920/1080
And this image is after I press upload button
I have a table where each row has an image and some text. Currently, when I update the content without selecting an image, the database field for the image gets cleared out. However, I want to keep the old image if there's no image selected.
How can I accomplish this?
As a note, I know that mysql_* functions are deprecated.
<?php
include("db/db.php");
$select_db = "select * from aboutus WHERE id=1";
$run_news = mysql_query($select_db);
while ($row = mysql_fetch_array($run_news)) {
$id = $row['id'];
$image = $row['image'];
$content = $row['content'];
}
?>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update About Content</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" method="post" action="aboutcontent.php?id=1" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Reselect Image *(H=530px, W=800px)</label>
<input type="file" name="user_image" id="exampleInputFile">
</div>
<div class="form-group">
<label >Content</label><br>
<textarea name="content" class="tinymce" class="form-control" rows="15"><?php echo $content; ?></textarea>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</form>
</div>
<?php
include("db/db.php");
// Code for UPDATE button
if (isset($_POST['update'])) {
$content = $_POST['content'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if ($imgFile) {
$upload_dir = 'images/about/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000, 1000000) . "." . $imgExt;
if (in_array($imgExt, $valid_extensions)) {
if ($imgSize < 5000000) {
unlink($upload_dir . $row['image']);
move_uploaded_file($tmp_dir, $upload_dir . $userpic);
}
else {
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else {
// if no image selected the old image remain as it is.
$userpic = $row['image']; // old image from database
}
// if no error occured, continue ....
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
$query = mysql_query($sql);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
echo "<script>alert('Successfully Updated!!!'); window.location='index.php?aboutcontent'</script>";
}
}
?>
The problem can easily be solved by checking if a file was submitted or not:
if(!empty($userpic)){
// SQL update here
} else {
// No file submitted so don't update
}
The reason you were getting empty mysql fields is because you were updating the field with an empty variable.
Since I can't comment yet, when you submit without an image are you landing in the if or else statement (place a die('some content) in each part) to figure this out. If you are not making it to the else, try:
//initialize error message
$errMSG = '';
//this error means 'There is no error, the file uploaded with success'
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
}
else{
$userpic = $row['image'];
}
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
OR just make two different database calls, one for when you have an image and one for when you dont
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
//if everything else is true (has filename and correct file size)
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
else{
$userpic = $row['image'];
$sql = "UPDATE aboutus SET content='$content' WHERE id=1";
}
http://php.net/manual/en/features.file-upload.errors.php
I've been trying to solve why my file is not getting uploaded. I thought it was my school's permission causing error so I am running it over wampserver but I am still getting an undefined error and 'file was not uploaded'. I tried several echos, the file name is right, the directory is right and being create but the file will not upload to the directory. When I put it manually in the directory it uploads fine to my database so I have no idea what's wrong.
Outside of my header/body
<?php
session_start(); // Starting Session
require_once('config.php');
$link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die ('Your DB connection is misconfigured. Enter the correct values and try again.');
//$query = mysqli_query(
?>
And here's the file upload:
<?php include 'navigation.php';?>
<h1> Welcome, <?php
echo $_SESSION['login_user']; ?> !</h1>
<!-- upload file script-->
<?php
if(!file_exists ("uploads/".$_SESSION['login_user'])){ //making the user directory
mkdir("uploads/".$_SESSION['login_user'], 0777, true);
}
$img_target_dir = "uploads/".$_SESSION['login_user']; //puts stuff in uploads
$target_file2 = $img_target_dir. basename($_FILES["imgfile"]["name"]); //img file
echo $_FILES["imgfile"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file2,PATHINFO_EXTENSION);
// Allow certain file formats for images (png)
// Check if image file is a actual image or fake image
if(isset($_POST['submit'])) {
if($imageFileType == "png") {
$check = getimagesize($_FILES["imgfile"]["tmp_name"]);
echo $img_target_dir . "/" . $_FILES["imgfile"]["name"];
if($check != false) {
if (move_uploaded_file($_FILES["imgfile"]["name"], $img_target_dir . "/" . $_FILES["imgfile"]["name"])) {
//chmod("uploads/img/lab2_upload.png",0777);
//echo "Image file size: ";
//echo filesize("uploads/img/lab2_upload.png") . "<br>";
//echo '<img src= "uploads/img/lab2_upload.png" height="300" width="300">';
}
else {
echo "file was not uploaded";
}
}
else {
echo "error uploading image";
}
}
else {
echo "File not png<br>";
}
}
?>
<!-- FORM FOR PHP UPLOAD -->
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<!-- Upload image-->
<h2> Image Upload </h2>
<h4> Ensure that the file upload is a PNG file!</h4>
<form action="profile.php" method="post" enctype="multipart/form-data">
<div><h2>Upload a PNG file: </h2>
<input class="btn btn-default btn-xl wow tada" id="imgfile" type="file" name="imgfile" value="imgfile">
<br>
<input class="btn btn-default btn-xl wow tada" id="Upload" type="submit" name="submit" value="Upload">
</div>
</form>
</div>
</div>
</div>
And a screenie: http://puu.sh/o7x1c/e3ee43d124.jpg
I know this question is repeated over and over.. But can't seem to find solution for my problem...
How can I create a form which will allow user to upload xy images at once?
Here's my html code:
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
And here's my php code:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>
Is it possible to solve this problem with foreach? If so, how should I do that?
Try this (add as many file fields as you want):
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" />
Php:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
echo "<p>$status</p>";
}
}
?>
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[1]" multiple="multiple">
<input id="image" type="file" name="image[2]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
PHP
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image1']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image1']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image1']['tmp_name'], $path))
if( #is_uploaded_file($_FILES['image2']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image2']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image2']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
}}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>