How to insert image path in to database? - php

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>

Related

Notice: Undefined index: file uploading video

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.

image rotation not working properly

I am trying to rotate image using php, image fail to create the jpeg rotated image.
first file 4a.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<?php include '4b.php';?>
<?php
function UploadOne($fname)
{
$uploaddir = 'upload/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?>
<body>
<?php
if ($_FILES['file']['name'] != "")
{
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = 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"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
}
$res = UploadOne($_FILES['file']);
$filname = $_FILES['file']['name'];
echo ($res);
LoadJpeg($_FILES['file']);
//and save it on your server...
}} ?>
<form action="4a.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>
<form action="imageup.php" method="post">
<input type="hidden" name="view" value="view">
<br><input type="submit" name="view" value="view"/>
</form>
</body>
</html>
<style>
.sucess{
color:#088A08;
}
.error{
color:red;
}
</style>
4b.php
<?php
function LoadJpeg($fname) {
$degrees=180;
//header('Content-type: image/jpeg');
$f= $fname['name'];
$source = imagecreatefromjpeg($f);
$rotate = imagerotate($source, $degrees, 0);
$j=imagejpeg($rotate,$fname['name'],100);
?>
<img src="upload/<?php echo $fname['name'];?>">
<img src="upload/<?php echo $j;?>">
<?php
// file_put_contents("upload/".$fname['name'],$j);
}
?>
it shows that
"failed to open stream: No such file or directory in E:\wamp\www\Gomal_FinalTask\4b.php on line 6"
The file name of the uploaded file on the server is in $fname['tmp_name']. $fname['name'] is just the file name as it was on the client-side
You need to use that entry when loading the image into an image resource, ie
$f= $fname['tmp_name'];
$source = imagecreatefromjpeg($f);

PHP tot MySQL image uploading not working

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>

Uploading image path into Database

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.

Unable to store File details in Database

I am trying to store uploaded file details in my database. I have written the following code, but I am unable to understand why its not reading the Query Block. Its not generating any MySQL error message or any other Syntax error. Kindly check it.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="file_upload_test2.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="file" name="file2" id="file"><br>
<input type="file" name="file3" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
include 'connect.php';
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
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"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 200000) . " kB<br>";
$image_name= $_FILES["file"]["name"];
$path= move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . rand().$_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
if (mysql_query ("Insert into category_images (image_name,image_location) VALUES ('$image_name', '$path')"))
{
echo "successfull";
}
else {
mysql_error();
}
}
}
else
{
echo "Invalid file";
}
?>
try
$sql = "INSERT INTO `category_images` (`image_name`,`image_location`) VALUES ('".$image_name."', '".$path."')";
$result = mysql_query($sql);
if ($result)
{
// Successful query execution
echo "successfull";
}
else {
// Some error occured while executing query.
// Show some useful information using echo/print.
// Then stop execution after taking other necessary steps
die(mysql_error());
}
also, your database is vulnerable to SQL Injection attack since you are not sanitizing your input. You should use at least mysql_real_escape_string() method to ensure that this doesn't occur.
If the above doesn't work, try checking if your connection parameters are ok and if MySQL is running.

Categories