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
}
Related
I still have the error 2 days after. Help...
I have an error with picture upload in my code. The file upload works perfectly when i remove anything image related but fails once i add anything image related.
I get 2 errors
"Sorry, there was a problem uploading your file." and
"Problem uploading item". I have no idea why...
I'll post the section i have the problem with.
if((($_FILES["pic"]["type"] != "image/jpg")
|| ($_FILES["pic"]["type"] != "image/jpeg")
|| ($_FILES["pic"]["type"] != "image/png")
|| ($_FILES["pic"]["type"] != "image/pjpeg"))
&& ($_FILES["pic"]["size"] > 1000000))
{
$_SESSION['itemerror'][] = "Pic must be jpg, jpeg, png or pjpeg and must be less than 1mb";
}
//final disposition
if (count($_SESSION['itemerror']) > 0) {
die(header("Location: postitem.php"));
} else {
if(registerItem($_POST)) {
unset($_SESSION['formAttempt']);
$_SESSION['itemsuccess'][] = "Successfully Uploaded";
die(header("Location: postitem.php"));
} else {
error_log("Problem uploading item: {$_POST['name']}");
$_SESSION['itemerror'][] = "Problem uploading item";
die(header("Location: upload.php"));
}
}
function registerItem($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$target = "img/";
$target = $target . basename( $_FILES['pic']['name']);
$pic=($_FILES['pic']['name']);
$poster = htmlspecialchars($mysqli->real_escape_string($_POST['user']));
$itemcategory = htmlspecialchars($mysqli->real_escape_string($_POST['category']));
$itemname = htmlspecialchars($mysqli->real_escape_string($_POST['name']));
$itemdescription = htmlspecialchars($mysqli->real_escape_string($_POST['description']));
$itemprice = htmlspecialchars($mysqli->real_escape_string($_POST['price']));
$itemlocation = htmlspecialchars($mysqli->real_escape_string($_POST['addr']));
$itemcity = htmlspecialchars($mysqli->real_escape_string($_POST['city']));
$itemstate = htmlspecialchars($mysqli->real_escape_string($_POST['state']));
$itemphone = htmlspecialchars($mysqli->real_escape_string($_POST['phone']));
$itemnegotiate = htmlspecialchars($mysqli->real_escape_string($_POST['negotiate']));
if(move_uploaded_file($_FILES['pic']['tmp_name'],$target)){
$query = "INSERT INTO Product
(category,name,upload_date,user,
description,price,location,city,
state,phone,negotiatable,pic_link)" .
" VALUES ('{$itemcategory}','{$itemname}',NOW(),'{$poster}',
'{$itemdescription}','{$itemprice}','{$itemlocation}'" .
",'{$itemcity}','{$itemstate}','{$itemphone}','{$itemnegotiate}', '{$pic}')";
if ($mysqli->query($query)) {
$itemname = $mysqli->insert_itemname;
error_log("Inserted {$itemname} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
} else {
$_SESSION['itemerror'][] = "Sorry, there was a problem uploading your file.";
}
}
The form contains this:
<form id="userForm" method="POST" action="upload.php">
And this for the picture input:
<label for="pic">Pictures: </label>
<input class="input100" type="file" id="pic" name="pic">
Add the attribute enctype="multipart/form-data" to your <form>
Like this
<form id="userForm" method="POST" action="upload.php" enctype="multipart/form-data">
I do not know if that will solve your problem, but it will probably help you.
It seems to me that it's mandatory for an upload form.
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";
}
}
}
Hi I am trying the data like title,Description and image.If i give only title and description without adding image the data should be inserted into database.But if I am trying that getting error.Here is my error and code:
error: error while uploading
my code
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0)
die("error while uploading");
else
{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
else
{
echo "failure";
}
Html Code
<form method="POST" action="blogs.php" enctype="multipart/form-data">
<div>
<label for="title">Title</label>
<input type="text" name="blog_title" value="">
</div>
<div>
<label for="image">IMAGE</label>
<input type="file" name="image">
</div>
<div>
<label for="blog_description">Description</label>
<textarea name="blog_description" class="text" style="width:50%;"> </textarea>
</div>
<input type="submit" value="Submit"/>
</form>
According to your code if you are not uploading the image, value of $error becomes 4. So your if() condition is getting executed. So remove your if condition.
if ($name = $_FILES["image"]["name"] != '') {
if ($type == "image/png" || $type == "image/jpg" || $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe") {
move_uploaded_file($temp, "upload/" . $name);
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
}else{
echo "File type not supported.";
}
session_start();
header("Location:blogimage.php");
} else {
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
First of all, start session at the very top of your PHP script, like this:
<?php
session_start();
?>
And now comes your issue. First use is_uploaded_file() function to check whether a file is uploaded or not, and then process your form accordingly.
So your code should be like this:
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if($error > 0){
die("error while uploading");
}else{
$permissible_extension = array("png", "jpg", "jpeg", "svg", "jpe");
if(in_array($ext, $permissible_extension)){
if(move_uploaded_file($temp,"upload/".$name)){
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}else{
echo "File couldn't be uploaded";
}
}else{
echo "Invalid format";
}
}
}else{
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
You have to use like below:
...
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
} else {
$sql=mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
}
session_start();
header("Location:blogimage.php");
...
I am using mysqli_query with your code, because mysql_* is deprecated:
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "yourDb");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name = "";
$failure = "";
if(isset($_FILES["image"]["name"])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0){
$name = "";
}
else{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
}
}
}
$sql = mysqli_query($link,"INSERT INTO blogs (image,blog_title,blog_description)
values('$name','$result','$description')");
if($sql){
//echo "upload complete";
session_start();
header("Location:blogimage.php");
die();
}
else{
echo 'failure';
}
?>
Explanation:
I am checking if if $_FILES["image"]["name"] is set than execute the file upload code.
further more if $error is not equal to 0 use move_uploaded_file()
Query will run in default either file empty or not, if empty than use $name as empty else use file name.
From PHP Manual:
mysqli::query -- mysqli_query — Performs a query on the database
Note that, its a procedural structure of mysqli_* extension, ist param of mysqli_query should be your connection identifier and second param should be your MYSQL Statement.
You have to make your fields and values dynamic :
Try this :
$_POST = array('image'=>'','blog_title'=>'yes','blog_description'=>'nothing');
foreach ($_POST as $key => $value) {
if(!empty($value)){
$fields .= $key.',';
$values .= "'".$value."'".',';
}
}
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
echo "INSERT INTO blogs($fields)values($values)";
I am trying to upload a file to an images folder and also insert the directory path into a mysql db.
Here is my HTML form
<form enctype="multipart/form-data" method="post" action="newfacility.php">
<fieldset>
<legend>New Facility</legend>
...
<label for="photo">Facility Photo:</label>
<input type="file" id="facilityphoto" name="facilityphoto" /><br />
<label for="province">Photo Description:</label>
<input type="text" id="photodesc" name="photodesc" /><br />
....
<input type="submit" value="Create" name="submit" />
</fieldset>
</form>
newfacility.php
require_once('../appvars.php');
require_once('upload_image.php');
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
// Grab the user data from the POST
$facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
....
....
//This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');
//facility photo
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
$facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));
// check if the faciliy info already exists.
if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {
$query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$data = mysqli_query($dbc, $query);
//if the facility is unique insert the data into the database
if (mysqli_num_rows($data) == 0) {
//insert into facility table
$query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
. " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
. " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
. " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
. "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
. "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
mysqli_query($dbc, $query);
//query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
$getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$facilityID = mysqli_query($dbc, $getFacilityID);
//insert into photo table
$photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
. "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
mysqli_query($dbc, $photoQuery);
// Confirm success with the user
echo '<p>You have succesfully created a new facility. '
. 'Please go back to the admin panel.</p>';
//testing to see if I can view the image
echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';
//close db connection
mysqli_close($dbc);
exit();
}
And finally here is upload_image.php
if(isset($_FILES["facilityphoto"])) {
// Check if file already exists
if (file_exists($facilityPhoto)) {
echo "Sorry, facility photo already exists.";
}
if($_FILES['facilityphoto']['error'] !==0) {
echo "Error uploading facility photo image.";
} else {
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
So the error I keep hitting right now is: echo "Sorry, there was an error uploading the facility photo.";
I don't understand what I am doing wrong here that is resulting in the image not being uploaded into my images/ directory.
I am going to provide an answer that addresses only the file upload problem, all the database stuff is striped from the answer as it is not relevant.
// returns true only if the file was written to $to,
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading the facility photo.";
return false;
}
if (isset($_POST['submit'])) {
define('MM_UPLOADPATH', 'images/');
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityphoto"]["tmp_name"];
$saved = save_facility_photo($from, $facilityPhoto, $status_msg);
}
else {
// handle upload error
}
// continue with code
}
The following is an explanation of what I think is happening in your scripts.
At the top of newfacility.php, require_once('upload_image.php'); is called. Now lets step though upload_image.php noting that $facilityPhoto has not yet been defined
// this is very likely true
if(isset($_FILES["facilityphoto"])) {
// $facilityPhoto is undefined so file_exists(NULL) will return false
if (file_exists($facilityPhoto)) { }
// the image upload was probably successful, so we jump to the else branch
if($_FILES['facilityphoto']['error'] !==0) {
}
else {
// $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL)
// will return false, so we jump to the else branch
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
}
else {
// resulting in this error
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
Replace these lines:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
with these:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
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'
}
}