I got some problems and it looks like I can't find any way to work around it. I tried use isset for each POST data, but while it would solve all the problems, the data won't be added.
I'll leave you the HTML code and PHP, so maybe you will be able to help me debugging this code.
adm_prod.php (the html page which handles the form)
<form method="POST" action="includes/prod-add.php">
Product Name<br>
<input type="text" name="Name"><br>
Price:<br>
<input type="number" name="Price"><br>
Product Description<br>
<input type="text" name="Description"><br>
Photo<br>
<input type="file" name="Photo"><br>
</br>
<button name="submit">Add Product</button>
</form>
prod-add.php (php file which handles the inserting/validating info)
<?php
include 'databaseConnection.php';
$name = $_POST['Name'];
$price = $_POST['Price'];
$description = $_POST['Description'];
$target_dir = "images-uploads/";
$target_file = $target_dir . basename($_FILES['Photo']['name']);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['Photo']['tmp_name']);
if($check !== false) {
$uploadOk = 1;
} else {
echo "The File Is not an image";
$uploadOk = 0;
}
}
if(file_exists($target_file)) {
$filename = $_FILES['Photo']['name'];
$extension = end(explode(".",$filename));
$name = rand(pow(10, 7), pow(10, 8)-1);
$newfilename = $name . "." .$extension;
$uploadOk = 1;
echo "Image already exists. Image Name changed to " . $newfilename;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
$uploadOk = 0;
echo "Sorry, only JPG, PNG and JPEG are accepted";
}
if ($uploadOk == 0) {
echo " Sorry, your product was not added, please check the error";
$fileupload = 0;
} else {
if (move_upload_file($_FILES['Photo']['tmp_name'], $target_file)) {
$fileupload = 1;
$imagePath = basename( $_FILES['Photo']['name']) . "." . $imageFIleType;
}
}
if($fileupload == 1) {
$addProd = "INSERT INTO meniu (name, price, description, path) VALUES ('$name','$price','$description','$imagePath')";
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
if ($conn->query($addProd) == TRUE) { ?>
<script>
window.alert("Product: <?php echo $name; ?> has been added successfully ");
</script>
<?php } else { ?>
<script>
window.alert("Error: <?php echo $conn->error; ?>");
</script>
<?php }
}
?>
I'm sorry if the code is not very clear, I'm still learning PHP. Usually I don't have any problem like this, but it's the first time I'm using image upload.
Basically, in the database I wanna introduce Name, Description, Price, Photo Path. The path should be something like ../uploads/photoname.extension .
Thanks for help.
The error is caused when the form is submitted without filling all the fields first. So, you need to check if the $_POST variables are set by firstly checking if the form has been submitted.
Also, add this to your form tag in the html enctype="multipart/form-data".
$name=$price=$description="";
if($_SERVER['REQUEST_METHOD']=="POST") {
//if the form has been submitted, initialize the values.
$name = $_POST['Name'];
$price = $_POST['Price'];
$description = $_POST['Description'];
$target_dir = "images-uploads/";
$target_file = $target_dir . basename($_FILES['Photo']['name']);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
:
//rest of the code
:
}
Inside that check if the file was uploaded with it:
if(isset($_POST['submit']) && isset($_FILES['Photo'])) {
$check = getimagesize($_FILES['Photo']['tmp_name']);
}
Encapsulate the entire process inside the if statement.
Also, as told by tadman, use parameterized queries using Prepared Statements or PDO in your mysql queries.
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'm creating a PHP and SQL blog. Among other files, I have upload_file.php and edit_post.php. Every time I edit a post, it updates all the information except for the featured image. It won't upload a new featured image. Here is upload_file.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_FILES['post_image']['name'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["post_image"]["name"]);
$image_name = basename($_FILES["post_image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["post_image"]["tmp_name"]);
if($check !== false) {
$file_image = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$file_not_image = "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$file_exists = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["post_image"]["size"] > 5000000) {
$file_too_large = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$file_not_allowed = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$file_not_uploaded = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["post_image"]["tmp_name"], $target_file)) {
$file_uploaded = "The file ". basename( $_FILES["post_image"]["name"]). " has been uploaded.";
} else {
$file_error = "Sorry, there was an error uploading your file.";
}
}
}
}
?>
Here is edit_post.php, minus the form:
<?php include("session_start.php")?>
<?php include("upload_file.php")?>
<?php include("links.php"); ?>
<?php include("navigation.php"); ?>
<?php
if($_GET['id'] != ""){
$post_id = $_GET['id'];
$sql = "SELECT * FROM posts WHERE post_id='$post_id' AND user_name='$user_name'";
$post = mysqli_query($connection, $sql) or die(mysqli_error($connection));
}
?>
<?php
$sql = "SELECT DISTINCT post_category FROM posts WHERE user_name='$user_name'";
$cat = mysqli_query($connection, $sql) or die(mysqli_error($connection));
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$post_title = isset($_POST['post_title']) ? $_POST['post_title'] : null;
$post_content = isset($_POST['post_content']) ? $_POST['post_content'] : null;
if($_POST['new_category']==""){
$post_category = ($_POST['choose_category']);
}else{
$post_category = ($_POST['new_category']);
}
$post_date = isset($_POST['post_date']) ? $_POST['post_date'] : null;
if (isset($image_name)){
$sql = "UPDATE posts SET post_title='$post_title', post_content='$post_content', post_category='$post_category', post_date='$post_date', post_image='$image_name' WHERE post_id='$post_id' AND user_name='$user_name'";
}else{
$sql = "UPDATE posts SET post_title='$post_title', post_content='$post_content', post_category='$post_category', post_date='$post_date' WHERE post_id='$post_id' AND user_name='$user_name'";
}
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));
header('Location: index.php');
}
?>
<?php include "footer.php";?>
How can I fix this?
I just realized the reason this wasn't working is because I forgot to put enctype="multipart/form-data" on my form!
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
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i am updating name , email in DB of registered user through php form. its working fine.
class.usr.php
public function update($uname,$email, $tax)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ? , tax = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email, $tax , $_SESSION['userSession']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
form related code to save in db
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
after this, now i am uploading an image to folder through same php form successfully with below code.
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
now images are just saving in folders, what i need is i want that image path to save in database and assign that image path to uploaded user in database. so that one registered user can update the existing image, but not upload one more image.
i tried below code , but not working:
<?php
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
$tax= $full_path;
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
db columns : userName, userEmail, tax , photo
with help of google i done all above, i am new to php, so please kindly help me.
Here is another solution:
First of all execute this query manually to add the new column:
ALTER TABLE `tbl_users` ADD `photo` VARCHAR(255) NOT NULL ;
Then this is the php code:
<?php
$dbConn = new Database();
$dbConn->dbConnection();
$user_home = new USER();
function uploadUserPhoto($uid) {
global $dbConn;
if(isset($_FILES["photo"]["error"])) {
if($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$userDir = $uid;
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)) {
if(!is_dir('upload/'.$uid)) {
mkdir('upload/'.$uid);
}
$photoname = time().$uid.'_photo'.'.'.$ext;
// delete all the files in this directory
$files = glob('upload/'.$uid.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
// Upload the photo
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);
$updateData = array(':userID' => $uid, ':photo' => $photoname);
$stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
$stmt->execute($updateData);
echo "Your file was uploaded successfully.";
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "";
}
}
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
uploadUserPhoto($uid);
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
There is $dbConnection variable which is the connection to the DB but because I don't know the rest of your code you should replace it with your proper db connection variable.
The photo of the user is saved in photo column in tbl_users and for every user is created sub dir in uploads dir. The subdir is the userID. So for example for user with userID = 1 its upload path will be uploads/1/<filename>.
File name is generated dynamically - this avoids caching of uploaded photo with the same name for example ... and it is better approach.
You have to make a change in code for displaying the photo because now its filename is in the DB and there is subdir in uploads (which is the userID of the user)
Add new function for saving files and use global php var $_FILES
1
Add new column to your DB to store file path, let's name it photo
2
Add new functions for your user class:
<?php
class User {
...
const PATH_PHOTOS = '/path/to/photo/folder/';
const BASE_URL = 'http://YOUR_DOMAIN_NAME:YOUR_PORT/YOUR_PATH/';
public function add_photo($file)
{
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$file['new_name'] = uniqid(rand(), true) . ".$ext";
if (!$this->_upload_file($file))
return false;
return $this->_remove_previous_photo()->_add_file_to_db(self::PATH_PHOTOS . basename($file['new_name']));
}
protected function _remove_previous_photo()
{
$photo = $this->get_photo();
if ($photo)
unlink($photo);
return $this;
}
public function get_photo()
{
global $_SESSION;
$stmt = $this->conn->prepare('SELECT photo FROM tbl_users WHERE userID = ? ');
$stmt->execute(array($_SESSION['userSession']));
$result = $stmt->fetch();
return reset($result);
}
public function get_photo_url()
{
$pathInfo = pathinfo($this->get_photo());
$last_dir = end(explode(DIRECTORY_SEPARATOR, $pathInfo['dirname']));
return self::BASE_URL . "$last_dir/" . basename($this->get_photo());
}
protected function _upload_file($file)
{
$uploadfile = self::PATH_PHOTOS . $file['new_name'];
return move_uploaded_file($file['tmp_name'], $uploadfile);
}
protected function _add_file_to_db($file_path)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET photo = ? WHERE userID = ? ');
return $stmt->execute(array($file_path, $_SESSION['userSession']));
} catch (PDOException $e) {
echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
}
}
...
}
?>
3
The main file should look like this:
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid) && $user_home->add_photo($_FILES['photo']))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Hope this helps
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'
}
}