How to upload image and save path to database? - php

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'
}
}

Related

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

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.

How to INSERT an array of uploaded filenames into a table and later display them?

I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}

file_get_contents(): Filename cannot be empty (uploading files to be optional)

I am new to php. I made a simple upload form in php. This is my code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) )
{
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
if ($_FILES['upload']['name'] == 0 ){
echo "<br><br> New record created successfully";
}
else {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) === TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
It works fine. But if I press the submit with no files attached, it displays the error, Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\contractdb\filetest.php on line 20 .
I want uploading files to be optional because not every user has the files to attach. I also want the user to download the files after uploading without removing file_get_contents($_FILES['upload']['tmp_name']).
How do I do this?
Your check should take in place before calling file_get_content() so it does not throw an error and you only call the function if file input is not empty:
if(isset($_POST['submit']) ) {
if ($_FILES['upload']['size'] != 0 ) {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']
['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else {
echo 'error: empty file';
}
}
Try this:
if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
// Statement
}

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 />';
}
}
}
}

Difficulty uploading & updating images to directory/MySQL using PHP

I can upload images as a serialized array no problem, but all I need is to store the raw filename string on my database and I'm not sure where to start editing my pre-existing code get this to work. This should be easier but as a PHP novice I can't get it to work.
Essentially, I want to be able to upload images then display them on the front end of my site doing something like this:
<img src="img/<php echo $config->photo_a ?>"/>
My existing code is:
<?php
//connect to db //
session_start();
include('../config.php');
// check for login to use //
if (!$user->authenticated)
{
header('Location: login.php');
die();
}
//post form as array using class photo_loader//
if (isset($post->form_action))
{
$a = new photo_loader(false, $db);
$a->name = $post->name;
$image_files = array();
for ($i=1; $i<10; $i++)
{
if (isset($_FILES['file'.$i]['name']) && $_FILES['file'.$i]['name'] != "")
{
$img = new upload($_FILES['file'.$i], M_ENV_SITE_URL, M_ENV_SITE_ROOT);
$img->set_upload_target("/img/");
$n = $img->do_upload();
if (!$n)
{
$err = "Image file ".$i." too big or wrong file type.";
}
else
{
$image_files[] = $n;
$img->batchResize("/img/", "/img/", $n, array("320x240", "800x600"));
}
}
}
if (empty($image_files)) $err = "You must include at least one image.";
$a->value = $image_files;
if (!$err)
{
$a->create();
$succ = "Success!";
}
}
?>
Using a simple form like this:
<form action="" method="post" enctype="multipart/form-data">
<div class="control-group"><label for="file" class="control-label">Attach Slideshow Images:</label><div class="controls">
<?php
for ($i=1;$i<10;$i++)
{
echo "<input name=\"file".$i."\" type=\"file\" value=\"\" id=\"file".$i."\" />";
} ?>
</div></div>
<input type="hidden" name="name" value="photo_a">
<div class="form-actions">
<input type="submit" name="form_action" class="btn btn-large btn-primary" value="Save" />
</div>
</form>
and photo_loader.class.php looks like this:
<?php
class photo_loader
{
private $properties;
var $db;
function __construct($id, $dbase)
{
$this->db = $dbase;
if (is_numeric($id))
{
$sql = sprintf(
"SELECT * FROM minty_config
WHERE ID=%d",
$this->db->clean($id)
);
$result = $this->db->query($sql);
$fields = $this->db->fetch_array($result);
foreach ($fields as $k => $v)
{
$this->properties[$k] = $v;
}
$this->value = unserialize($this->value);
}
}
function __get($k)
{
return $this->properties[$k];
}
function __set($k, $v)
{
$this->properties[$k] = $v;
}
function update()
{
$sql = sprintf(
"UPDATE minty_config SET
name='%s',
value='%s'
WHERE ID=%d",
$this->db->clean($this->name),
serialize($this->value),
$this->ID
);
$this->db->query($sql);
}
function create()
{
$sql = sprintf(
"INSERT INTO minty_config
(name, value)
VALUES('%s', '%s')",
$this->db->clean($this->name),
unserialize($this->value)
);
$this->db->query($sql);
}
function delete()
{
$sql = sprintf(
"DELETE FROM minty_config
WHERE ID=%d",
$this->ID
);
$this->db->query($sql);
}
}
?>
I presume I need to remove the $image_files = array(); section but I don't know what to replace with! Seemingly keep making mistakes and returning blank pages with errors or not uploading the image. I can't see it being too diffuclt but I presume I'm going the wrong way about it. Many thanks in advance!!

Categories