I\'m trying to make a site in which I can upload a file to my sql database, but it does not seem to work.
This is my code;
You should save the files in some folder during the upload process and save the name of file in database, so later you can call the name of file from database and link it as a hyperlink to download, i am using the following code to upload images in a folder called files
and saving the name of files in database. At the end i have the file name in variable $newname
if ($_FILES['file']['name']) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 500000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = end(explode(".", $_FILES["file"]["name"]));
$filename = current(explode(".", $_FILES["file"]["name"]));
$newname = $filename . '_' . time() . '.' . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],
"files/" . $newname);
}
} else {
echo "<div class='alert alert-success'>Image type or size is not valid.</div>";
}
}
I hope this helps you:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<?php
function output_errors($error) {
echo '<ul><li><font color="red">'.$error.'</font>/li></ul>';
}
if($_POST) {
//Connecting to the database
$connect = mysqli_connect("localhost", "root" ,"", "picturedatabase");
$name = $_FILES['Image']['name'];
if(!empty($name)) {
$tmp = $_FILES['Image']['tmp_name'];
$type = $_FILES['Image']['type'];
$allowed_type = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
if(!in_array($type, $allowed_type)) {
$error[] = $type. ' is not allowed file type';
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo output_errors($error);
} else if(empty($error)){
$path = 'images/'.$name;
$query = mysqli_query($connect, "INSERT INTO `images` (`image`) VALUES ('$path')");
if(!$query) {
echo 'Insert into db went wrong';
} else {
move_uploaded_file($tmp, $path);
echo '<font color="green">Upload succesful</font>';
}
}
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
</body>
</html>