Multi file upload - change status of the file basis hidden element - php

I am trying to upload multiple files using PHP which is working fine. Now in my form, I am displaying the file options dynamically along with the type of document it is, resume, id proof, etc.,
It is not necessary that the user should upload all the files at once, he can select whatever docs he has and use the submit button to upload them, after which I'd like to update that doc status to "Received". While trying to do this, I am seeing that only last record is getting updated no matter how many files are selected.
Here's my Form code -
<table class="table striped bordered border hoverable white">
<?php
$returnMsg = "";
$docsNStatus="SELECT * FROM applicantdocs where username = '$login_session' and docStatus='Not Received'";
if(!$result=mysqli_query($db,$docsNStatus))
die('There was an error retrieving the information');
echo "<form method='POST' action='../../actionHandler.php' enctype='multipart/form-data' target='resultFrame'>";
while ( $row = $result->fetch_assoc() ){
$uploadFileName = "fileUpload".$row['sno'];
$docID = $row['sno'];
echo "<tr>
<td>".$row['docName']."</td>
<td>".$row['docStatus']."</td>
<td>
<input type='hidden' name='docNumber' value='$docID'/>
<input type='hidden' name ='docNumber_$docID' value='$docID'/> //Here I am dynamically setting the hidden element docnumber and the id
<label style= 'padding: 5px!important;' class='myLabel'>
<input type='file' name='uploadingFiles[]' id='uploadBtn'/>
<span>Upload doc</span>
</label>
</td></tr>";
}
echo "</table><br/><input type='submit' name ='uploadFile' value='Click here to upload files' class='formButton'/> ";
?>
PHP code:
if(isset($_POST["uploadFile"])){
$userIDquery = "SELECT firstName, lastName from applicants WHERE username= \"{$login_session}\"";
$userRes= mysqli_query($db, $userIDquery);
$userRec= mysqli_fetch_array($userRes, MYSQLI_ASSOC);
$lName = $userRec["firstName"].'_'.$userRec["lastName"];
$storageLocation = "Assets/Documents/".$lName."/";
$errors = array();
$extension = array('jpg','png','jpeg','gif','pdf');
$bytes = 1024;
$allowedMB = 10;
$totalBytes = $allowedMB * $bytes * 1024;
foreach($_FILES["uploadingFiles"]["tmp_name"] as $key=>$tmp_name) {
$docNo = mysqli_real_escape_string($db, $_POST["docNumber"]);
$onlyDocNumToUpdate = mysqli_real_escape_string($db, $_POST["docNumber_".$docNo]);
$uploadThisFile = true;
$file_name=$_FILES["uploadingFiles"]["name"][$key];
$file_tmp=$_FILES["uploadingFiles"]["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["uploadingFiles"]["size"][$key] > $totalBytes) {
array_push($errors, "File size must be less than 10MB. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename=basename($file_name,$ext);
$newFileName=$filename.$ext;
if(move_uploaded_file($_FILES["uploadingFiles"]["tmp_name"][$key], $storageLocation.$newFileName)){
$query = "UPDATE applicantdocs set docStatus ='Received'
where username = '$login_session'
and sno=$onlyDocNumToUpdate";
if(!mysqli_query($db, $query)){
print '<br><b style="color:#B60000">Exception:</b> ';
throw new Exception(showerror($db));
} else
print "The selected files have been uploaded successfully.";
}
}
}
mysqli_close($db);
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
My form looks something like below -
Appreciate taking a look at it.

Related

How to add profile image to user php

I want a logged in user to add a profile picture. No errors are shown, the picture is just not added to the folder where it should be.
I know I have to use prepared statements, I will. I just want to sort this problem out first.
When the user has not changed the profile pic, the default picture displays perfectly. The file profile pic just wont upload to the folder.
This is the page where you change the picture.
<?php
session_start();
include_once 'dbh.php';
<html>
<body>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
}
else {
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
}
else {
echo "There are no users!";
}
if (isset($_SESSION['id'])) {
echo "You are logged in!";
echo '<form action="includes/upload.inc.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD FILE</button>
</form>';
}
else {
echo "You are not logged in!";
}
?>
This is the php page for the upload
<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
//I now need to create a unique ID which we use to replace the name
of the uploaded file, before inserting it into our rootfolder
//If I don't do this, we might end up overwriting the file if we
upload a file later with the same name
//Here I use the user ID of the user to create the first part of the
image name
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
I suspect logical issue near your below update query:
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
Your logic will run fine for only those users who already having corresponding record in profileimg table. But UPDATE query will do nothing for new user.
So, you will have to first check whether there is a record in profileimg for particular user. If no record then run INSERT query, if record exists then run UPDATE query..

check if file input field is empty using foreach loop

I have 7 file input fields namely:
<input type="file" accept="image/*" name="imgreq1">
<input type="file" accept="image/*" name="imgreq2">
<input type="file" accept="image/*" name="imgreq3">
<input type="file" accept="image/*" name="imgreq4">
<input type="file" accept="image/*" name="imgreq5">
<input type="file" accept="image/*" name="imgreq6">
<input type="file" accept="image/*" name="imgreq7">
How can I check if the other input fields are empty if I for example uploaded a file in the first and the second input fields. Then submit the form leaving the other fields empty?
Update:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) || !file_exists($_FILES['imgreq'.$i]['tmp_name'])){
echo "$i";
// your code
}else{
//to retrieve user_id to stored in the request table in the database
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$sid= ''.$row['user_id'].'';
$coll=''.$row['college'].'';
$stat="Pending";
//$query="SELECT document_name FROM document_tbl WHERE document_id = '$passed_id'";
//$dn=mysql_query($query);
//$getname=mysql_fetch_assoc($dn);
//var_dump($getname);
//to analyze the contents of the image selected in filebrowser1
$image1=addslashes($_FILES['imgreq1']['tmp_name']);
$name1=addslashes($_FILES['imgreq1']['name']);
$image1=file_get_contents($image1);
$image1=base64_encode($image1);
//to analyze the contents of the image selected in filebrowser2
$image2=addslashes($_FILES['imgreq2']['tmp_name']);
$name2=addslashes($_FILES['imgreq2']['name']);
$image2=file_get_contents($image2);
$image2=base64_encode($image2);
//to analyze the contents of the image selected in filebrowser3
$image3=addslashes($_FILES['imgreq3']['tmp_name']);
$name3=addslashes($_FILES['imgreq3']['name']);
$image3=file_get_contents($image3);
$image3=base64_encode($image3);
//to analyze the contents of the image selected in filebrowser4
$image4=addslashes($_FILES['imgreq4']['tmp_name']);
$name4=addslashes($_FILES['imgreq4']['name']);
$image4=file_get_contents($image4);
$image4=base64_encode($image4);
//to analyze the contents of the image selected in filebrowser5
$image5=addslashes($_FILES['imgreq5']['tmp_name']);
$name5=addslashes($_FILES['imgreq5']['name']);
$image5=file_get_contents($image5);
$image5=base64_encode($image5);
//to analyze the contents of the image selected in filebrowser6
$image6=addslashes($_FILES['imgreq6']['tmp_name']);
$name6=addslashes($_FILES['imgreq6']['name']);
$image6=file_get_contents($image6);
$image6=base64_encode($image6);
//to analyze the contents of the image selected in filebrowser7
$image7=addslashes($_FILES['imgreq7']['tmp_name']);
$name7=addslashes($_FILES['imgreq7']['name']);
$image7=file_get_contents($image7);
$image7=base64_encode($image7);
//function nga defined sa dalum para i insert ang uploaded files sa databasess
saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll);
}
}
}
}
}
function saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll){
$con=mysql_connect("localhost","root","");
mysql_select_db("dummy",$con);
$qry="INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id','$image1','$image2','$image3','$image4','$image5','$image6','$image7','$stat','$coll')";
$result=mysql_query($qry,$con);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>
From OP's comment,
But how can you do it using for each loop this feature of php is a deep one ...
Use a simple for loop, in conjunction with is_uploaded_file() function, to check whether user has uploaded a file via HTTP POST or not, like this:
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name'])){
// user has uploaded a file
}
}
Update:
Based on the below discussion with OP, the complete solution would be like this:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$sid = $row['user_id'];
$coll =$row['college'];
$query = "INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id'";
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) && $_FILES['imgreq'.$i]['size']){
$query .= ",'" . base64_encode(file_get_contents(addslashes($_FILES['imgreq'.$i]['tmp_name']))) . "'";
}else{
$query .= ",NULL";
}
}
$query .= ",'$stat','$coll')";
saveimage($query);
}
}
function saveimage($qry){
$con = new mysqli("localhost", "root", "", "dummy");
$result=mysqli_query($con, $qry);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>
As a sidenote, learn about prepared statement as it prevents your query from any kind of SQL injection attacks. Here's a good read on how you can prevent SQL injection in PHP.

move_uploaded_file not working but no error

I have been having an issue with my code, specifically with the move_uploaded_file. I changed the folder I keep the images in's permissions to 777 to make sure it wasn't a problem with the permissions. I also read a php manual on how to use move_uploaded_file of w3schools.com. I have run out of ideas on how to upload my image to a folder using php. Please help.
Here is the portion of the code with the move_uploeaded_file:
<?php
if (#$_GET['action'] == "ci"){
echo "<form action='account.php?action=ci' method='POST' enctype='multipart/form-data'><br />
Available file extention: <stong>.PNG .JPG .JPEG</stong><br /><br />
<input type='file' name='image' /><br />
<input type='submit' name='change_pic' value='Change' /><br />
</form>";
if (isset($_POST['change_pic'])) {
$errors = array();
$allowed_e = array('png', 'jpg', 'jpeg');
$file_name = $_FILES['image']['name'];
$file_e = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$file_s = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if(in_array($file_e, $allowed_e) === false) {
$errors[] = 'This file extension is not allowed.';
}
if ($file_s > 2097152) {
$errors[] = 'File size must be under 2MB';
}
if (empty($errors)) {
move_uploaded_file($file_tmp, '../images/'.$file_name);
$image_up = '../images/'.$file_name;
$check = mysqli_query($connect, "SELECT * FROM users WHERE usename='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
if($query = mysqli_query($connect, "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'"))
echo "You have successfuly changed your profile picture!";
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}
?>
Here's the last chunk of the code, slightly rewritten. move_uploaded_file returns a boolean, so we can test if it's true or false by setting up a variable $result:
if (empty($errors)) {
$image_up = 'images/'.$file_name;
$result = move_uploaded_file($file_tmp, $image_up);
if($result){
//this line had a typo usename -> username
//Also, you should change this over to using parameters and binding values ASAP. This leaves you open to hacking.
$check = mysqli_query($connect, "SELECT * FROM users WHERE username='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
$q = "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'";
if($query = mysqli_query($connect, $q)){
echo "You have successfuly changed your profile picture!";
}
} else {
echo "Upload failed.";
}
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}

My script can uploads the Avatar/Profile image but can't change the size (height and width)

Thanks for the support really appreciated.
I am newbie in PHP, and i heard that i can find my solution from those PHP expert who are here in Stackoverflow.
I have bought this script a while ago and now the producer stopped offering support.
Avatar upload form
http://i.stack.imgur.com/YO7PD.jpg
My Question
The script have ability to upload profile for every user but it doesn't resize the image.
If a user upload a 2 mb image so the script use 2 mb image in all over the website which makes my website to run slower.
I want that the script should resize the image to
([width=100px and height=auto] and
[width=19px and height=auto])
so i use a lighter image in size (like ~150 kb and ~55kb) and let my site run faster.
This is the avatar.php file that process the uploading
<?php
// declare variables
$msg = '';
$f_avatar_image = '';
// ------------------------------------------------------------
// UPLOAD AVATAR
// ------------------------------------------------------------
if(isset($_POST['btnUploadAvatar']) && !empty($_FILES['fileUpload']['name']))
{
// create variables
$avatar_directory = AVATAR_FILE_DIRECTORY;
$file_name = $_FILES['fileUpload']['name'];
$file_type = $_FILES['fileUpload']['type'];
$file_size = $_FILES['fileUpload']['size'];
$file_size_limit = AVATAR_FILE_SIZE;
$calc_kilobites = 1024;
$file_size_kb = round($file_size / $calc_kilobites, 2);
$temp_file_name = $_FILES['fileUpload']['tmp_name'];
$upload_error = $_FILES['fileUpload']['error'];
// create unique file name
$unique_file_name = $user_name.'-'.$file_name;
$avatar_img_url = AVATAR_IMAGE_URL.$user_name.'-'.$file_name;
// if upload error display error message
if($upload_error > 0)
{
echo 'ERROR:' . $upload_error;
}
// if no upload error - check for file types
if($upload_error == 0 &&
$file_type == 'image/gif' ||
$file_type == 'image/jpeg' ||
$file_type == 'image/png' )
{
// if file size is within limits
if($file_size <= $file_size_limit)
{
// move uploaded file to assigned directory
if(move_uploaded_file($temp_file_name, $avatar_directory . $unique_file_name))
{
// get user id
$get_user_id = mysqli_query($conn, "SELECT UserId FROM users WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user id exist
if(mysqli_num_rows($get_user_id) == 1 )
{
$row = mysqli_fetch_array($get_user_id);
$user_id = $row['UserId'];
// check if user profile already exist
$check_user_profile = mysqli_query($conn, "SELECT UserId FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user profile exist - update
if(mysqli_num_rows($check_user_profile) == 1 )
{
// update profiles
$update_profile = mysqli_query($conn, "UPDATE profiles SET AvatarImage = '$avatar_img_url' WHERE UserName = '$user_name'") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_update_failed;
}
}
else
{
// create profile
$insert_profile = mysqli_query($conn, "INSERT INTO profiles(UserId,UserName,AvatarImage) VALUES($user_id,'$user_name','$avatar_img_url')") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_create_failed;
}
}
}
else
{
// user id not found
$msg = $profile_update_failed2;
}
}
else
{
$msg = $avatar_upload_failed;
}
}
else
{
$msg = $avatar_file_too_large;
}
}
else
{
$msg = $avatar_wrong_file_type;
}
}
elseif(isset($_POST['btnUploadAvatar']) && empty($_FILES['fileUpload']['name']))
{
$msg = $avatar_empty;
}
// ------------------------------------------------------------
// DISPLAY AVATAR ON PAGE LOAD
// ------------------------------------------------------------
if($user_name)
{
// get user id
$get_avatar_image = mysqli_query($conn, "SELECT AvatarImage FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
if(mysqli_num_rows($get_avatar_image) == 1)
{
$row = mysqli_fetch_array($get_avatar_image);
if($row['AvatarImage'] != 'NULL' && $row['AvatarImage'] != '')
{
$f_avatar_image = $row['AvatarImage'];
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
?>
This is the avatar.html.php file form
<?php require_once(ROOT_PATH.'user/modules/accordion/avatar.php'); ?>
<div class="profileWrap">
<form name="frmAvatar" method="post" action="" enctype="multipart/form-data" class="htmlForm">
<div class="infoBanner2">
<p>REQUIREMENTS: File Size: <?php echo AVATAR_FILE_SIZE / 1024 ?> kb max. File Type: gif, jpg, png</p>
</div>
<!-- error msgs -->
<ul>
<?php echo $msg; ?>
</ul>
<p><input name="selectFile" type="image" src="<?php echo $f_avatar_image; ?>" class="img"></p>
<p><label for="fileUpload">Avatar Image:</label><input name="fileUpload" type="file" id="fileUpload" maxlength="255" ></p>
<input name="btnUploadAvatar" type="submit" value="Upload" class="gvbtn btn" onclick="return confirm('Are You READY to UPLOAD?');"/>
</form>
</div>
The avatar.php file is linked to a configuration file (web.config.php) file
// ------------------------------------------------------------
// 16. AVATAR IMAGE FILE
// ------------------------------------------------------------
define('AVATAR_FILE_SIZE', 2097152); // 50 Kb max. -> 1 kilobyte = 1024 bytes
define('AVATAR_FILE_DIRECTORY', ROOT_PATH.'user/upload/avatars/'); // upload directory
define('AVATAR_IMAGE_URL', SITE_URL.'user/upload/avatars/'); // default avatar url
define('DEFAULT_AVATAR_IMAGE', 'default-avatar.png'); // default avatar image
If you needed to ask anything i am ready to answer.
Let me thank the one who answer it.
Take a look at this lib and doc
https://github.com/Nimrod007/PHP_image_resize

How to upload image and save path to database?

I have a page where some images are shown (database driven). Here is the code of my gallery.php :
<ul id="portfolio-list" class="gallery">
<?php
$sql="select * from eikones ";
$res=mysql_query($sql);
$count=mysql_num_rows($res);
for ( $i = 0; $i < $count; ++$i )
{
$row = mysql_fetch_array( $res );
$co=$i+1;
if(isset($row[ "path" ]))
{
$path= $row[ "path" ];
}
if(isset($row[ "auxon" ]))
{
$auxon = $row[ "auxon" ];
}
if($_SESSION['role'] == "admin")
echo "<li class=\"pink\"><img src=\"$path\" alt=\"Pic\"></li>\n";
}
?>
</ul>
Now I want to have a form where I will be able to upload an image. I am trying this but it doesn't work :
<form enctype="multipart/form-data" action="gallery.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include 'conf.php'; //database connect
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO eikones"; //table name = "eikones" and it has two columns named "auxon" and "path". The auxon is the id.
$query .= "(image) VALUES ('','$data')";
$results = mysql_query($query, $link) or die(mysql_error());
print "DONE";
}
else {
print "NO IMAGE SELECTED";
}
?>
It says "NO IMAGE SELECTED" and nothing new comes into the database.
After some hours I found a solution. It works. Although I would still be happy to find a second solution (according to the code I first posted here). Here is the second solution :
form page :
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
insert to database page :
<?php
include 'conf.php';
if ($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="images/".$_FILES["image"]["name"];
$sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
There are plenty of small classes you can download to handle your image uploads. Here's something small I just coded up. It will allow you to set validation for file type and file size. Feel free to make some methods private or hardcode the protected variables in the constructor if you know they'll always be the same. It may need a little work, but you can either use this class or pull out the bits you need to do it procedurally. Forgive any minor errors.
class ImageUploader{
protected
$size_limit,
$allowed_extensions;
$failed_saves;
public function __construct(int $limit, array $extensions){
$this->size_limit = $limit;
$allowed_extensions = $extensions;
}
public function saveImage(array $images){
foreach($images as $image){
if($this->meetsSizeLimit($image['size'])){
if($this->hasValidExtension(end(explode(".", $image["name"])))){
$this->storeImage($image, $this->getNextImageIndex());
}
else $failed_saves[$image["name"] = "Invalid file type.";
}
else $failed_saves["name"] = "File is too large.";
}
return $failed_saves;
}
public function meetsSizeLimit(int $size){
return $size <= $this->size_limit;
}
public function hasValidExtension(string $extention){
return in_array($extension, $this->allowed_extensions)
}
public function storeImage($image, $unique_id){
move_uploaded_file($image["tmp_name"], "you_relative_file_path" . $image["name"]);
rename('your_relative_file_path' . $image["name"], 'your_relative_file_path/img' . $unique_id . '.' . $extension);
//Place your query for storing the image id and path in table 'eikones'
}
public function getNextImageIndex(){
//Code to get the next available image id or MAX(id) from table 'eikones'
}
}

Categories