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;
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
<?php
//Connecting to the database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("picturedatabase") or die(mysql_error());
$file = $_FILES['Image']['tmp_name'];
if(!isset($file))
{
echo "Select an image";
}
else
{
$image = addslashes(file_get_contents($_FILES['Image']['tmp_name']));
$image_name = addslashes($FILES['Image']['name']);
$image_size = getimagesize($FILES['Image']['tmp_name']);
}
if($image_size==FALSE)
{
echo "That's not an image.";
}
else
{
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')"))
{
echo "There was a problem uploading the image";
}
else
{
$lastid = mysql_insert_id();
echo "Image uploaded!<p />Your image:<p /> <img src=show.php?id=$lastid>";
}
}
?>
</body>
</html>
And when I run the file, the form stuff shows up (the buttons and I can also select a file), but it also says
"Notice: Undefined index: Image in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 16
Notice: Undefined variable: image_size in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 29"
Could someone tell me what I did wrong and help me fix this?
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>
Related
I am trying to upload a video to my uploads folder. I got the code from another question on here and that works fine. But I keep getting this notice error and I don't know how to fix it. I've been trying all day. I tried to check if it was isset() and that still didn't work. Can someone help me please ?
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$_FILES = $_FILES['file'];
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$unique = date('Y-m-d_H-i-s');
if ((null !==($_FILES["file"]["type"] == "video/mp4")
|| (null !==($_FILES["file"]["type"] == "audio/mp3"))
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
echo 'File uploaded successfully';
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$datetime = date('Y-m-d_H-i-s');
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"] . $datetime . md5($_FILES["file"]["name"]));
}
}
} else {
echo "Invalid file";
}
?>
<form action="profile.php" id="videoupload" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
You're trying to process the file upload before a file is uploaded. You have to check if the form was posted first.
<?php
if (isset($_FILES['file'])) {
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
// $_FILES = $_FILES['file']; // <-- remove this line
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$unique = date('Y-m-d_H-i-s');
if ((null !==($_FILES["file"]["type"] == "video/mp4")
|| (null !==($_FILES["file"]["type"] == "audio/mp3"))
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
echo 'File uploaded successfully';
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$datetime = date('Y-m-d_H-i-s');
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"] . $datetime . md5($_FILES["file"]["name"]));
}
}
} else {
echo "Invalid file";
}
}
?>
<form action="profile.php" id="videoupload" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
$_FILES['file']
means you have input type = file named 'file'. if you don't have the input named 'file', you got an undefined index notice.
if you have that,
$_FILES = $_FILES['file'];
this will bring error to other codes. because it try to override $_FILES.
I am trying to make a script that allows users to change their profile picture for a website that I am making. Here is the HTML code for the form:
<form action="upload_prof_pic.php" method="POST" enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="file" id="file" /><br /><br />
<input type="submit" class="btn btn-default" value="Upload Profile Picture" />
</form>
Here is the PHP code for upload_prof_pic.php:
<?php
session_start();
require("includes/connect.php");
$results = $db->query("SELECT * FROM users WHERE username='".$_SESSION["logged_in"]."'");
$rows = $results->fetch();
$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"] < 20000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
//error: uploading
header("Location: account.php?err=upload");
} else {
//success
move_uploaded_file($_FILES["file"]["tmp_name"],
"prof_pic/users/".$rows["username"]."/" . $_FILES["file"]["name"]);
$db->query("UPDATE users SET prof_pic='".$_FILES['file']['name']."' WHERE username='".$_SESSION["logged_in"]."'");
header("Location: account.php");
}
} else {
//error: invalid file
header("Location: account.php?err=invalid");
}
?>
It always runs the '//error: invalid file' part of the script. Can anyone help? It worked once, then I changed something in the '//success' part. This shouldn't have had any effect, but apparently it did.
i got that same error so i used following javascript coding.
<script type="text/javascript" src="js/jquery-func.js"></script>
<SCRIPT type="text/javascript">
function ValidateFileUpload() {
var fuData = document.getElementById('filename');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Please upload an image");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg")
{
<?php
move_uploaded_file($_FILES["file"]["tmp_name"],
"prof_pic/users/".$rows["username"]."/" . $_FILES["file"]["name"]);
$db->query("UPDATE users SET prof_pic='".$_FILES['file']['name']."' WHERE username='".$_SESSION["logged_in"]."'");
header("Location: account.php");
?>
}
//The file upload is NOT an image
else {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
}
}
}
html part
<input onchange="ValidateFileUpload(this);" type="file" name="file" id="filename"/>
I'm having an issue with uploading an image path into a database. Database called: basketball_database and table called: media, columns: id(int, auto increment), name(varchar), image(varchar)
All the images I try to upload from different directories on my computers are png files.
For some reason I'm only able to upload only 1 image and the database doesn't display the image name or the image path. Can anyone help me fix these problems? Thank you
File 1: upload_image.php
<html>
<body>
<form action="uploaded_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
File 2:upload_file.php
//connection
$username = "root";
$password = "";
$hostname = "localhost";
$database = "basketball_database";
$table = "media";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to Mysql");
// echo "Connected to mysql<br>";
mysql_select_db("$database")
or die("Could not select Basketball_database");
//echo "Connected to database";
//image extensions allowed
$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"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//Successfully uploaded
echo "Your file " . $_FILES["file"]["name"] . " successfully uploaded!!<br>";
echo "Details :";
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//Display Image
echo "<img src=uploaded/" . $_FILES["file"]["name"] . ">";
//Uploaded image folder
if (file_exists("uploaded/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploaded/" . $_FILES["file"]["name"]);
}
}
}
else
{
//error message on the extension that are not allowed
echo "Invalid file";
$filename = preg_replace('/[^A-Z0-9]/','',$_FILES["file"]["name"]) . $extension;
$logo = uploaded/$filename;
//insert into database
$strSQL = "INSERT INTO $table(name,image) VALUES('$name_file','$logo')";
mysql_query($strSQL) or die(mysql_error());
}
?>
Here is a good tutorial to start with upload img with php.
And just build up from here.
I've had several upload forms working before, however, even after almost copying my previous code this on doesn't seem to work, I prefer doing it all in one php script file and so it is all generated in this single file.
My form:
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li>
<label for="file">File : </label>
<input type="file" id="file" name="file" required="required" />
</li>
<li>
<input type="submit" value="Upload" />
</li>
</ul>
</form>
My php upload:
if(!empty($_POST['file']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
When I upload a .png image, the page simply seems to refresh, I've placed the echo "Found."; in there to check if it even has anything in $_POST["file"] but it doesn't seem to have anything.
I don't understand why the page isn't submitting correctly. I've changed action="" to action="upload.php" to make sure it points to the same page but still nothing.
Use $_FILES['file'] instead of $_POST['file'].
Read more about $_FILES at http://www.php.net/manual/en/features.file-upload.post-method.php
replace $_POST['file'] by $_FILES['file'] and set action="".
Try this.... because $_POST not work with files, for files we use $_FILES..
if(!empty($_FILES['file']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
I wouldn't just check the $_FILES variable. I would name the submit input and check if the submit input was submitted. This way you can check if the button was pressed with no files selected and prompt the user as such.
Like So:
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li>
<label for="file">File : </label>
<input type="file" id="file" name="file" required="required" />
</li>
<li>
<input type="submit" value="Upload" name="upload"/>
</li>
</ul>
</form>
Then you can check the post variable for that value.
Like So:
if(!empty($_POST['upload']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
How do is store the image path in database and display it after it is uploaded?
<?php
$sub=0;
ini_set( "display_errors", 0);
if(isset($_REQUEST['submited'])) {
// your save code goes here
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
$sub= 1;
echo "<font size='7' color='white'><b> Success! Your photo has been uploaded.</b></font>";
}
}
}
else
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>.";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="submited" value="true" />
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<label size="16" for="file">Choose Photo:</label>
<input id="shiny" type="file" name="file" onchange="file_selected = true;">
<input id="shiny" type="submit" value="Upload" name="submit">
<?php
}
?>
</form>
here is the database info...and how do I display the picture after inserting the image path in to database? I tried VALUES
('$_FILES["file"]["name"]')"; but that doesn't seem to work..
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$sql="INSERT INTO photo (photo)
VALUES
('$_FILES["file"]["name"]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
"INSERT INTO photo (photo) VALUES ('{$_FILES["file"]["name"]}')"
That should work. To use an associate array in a string, you have to wrap it in curly ({ }) brackets.
3 Points I would like to make that are irrelevant to the specific question:
1: You should always sanatize user input before putting into into the database. So what you should do is:
"INSERT INTO photo (photo) VALUES ('" . mysql_real_escape_string($_FILES["file"]["name"]) . "')"
or use prepared statements with mysqli or pdo.
2: If you are just storing a list of files in the database, what is the point? Why not just iterate over the directory you are storing them in?
3: mysql_* functions are depreciated, you should consider using mysqli or pdo
I just got it solved using Mysqli so I can prevent sql injection too.....thanks for your help guys...
<?php
$sub=0;
ini_set( "display_errors", 0);
if(isset($_REQUEST['submited'])) {
// your save code goes here
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
$sub= 1;
$mysqli = new mysqli("localhost", "root", "", "simple_login");
// TODO - Check that connection was successful.
$photo= $_FILES["file"]["name"];
$stmt = $mysqli->prepare("INSERT INTO photo (photo) VALUES (?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("s", $photo);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<font size='7' color='white'><b> Success! Your photo has been uploaded.</b></font>";
}
}
}
else
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>.";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="submited" value="true" />
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<label size="16" for="file">Choose Photo:</label>
<input id="shiny" type="file" name="file" onchange="file_selected = true;">
<input id="shiny" type="submit" value="Upload" name="submit">
<?php
}
?>
</form>
</div>