Upload image with caption and store caption & session username to database - php

I want to implement a simple image uploader that stores a caption, the user logged in ($_SESSION['username']) and the path that the file is saved.
The session is working, the code is correct, the database table exists, but it writes only the 'path' value, the 'username' and 'caption' remain empty on the database.
This is the code for uploading:
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"] < 5000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
$caption = $_POST['caption'];
$uploaderUsername = $_SESSION['username'];
$path = "upload/" . $_FILES['file']['name'];
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
mysql_query("INSERT INTO images (caption,username,path) VALUES
('$caption','$uploaderUsername','$path')");
header('Location: members.php');
}
}
} else {
echo "Invalid file";
}
I guess there is something wrong in this part:
$caption = $_POST['caption'];
$uploaderUsername = $_SESSION['username'];
$path = "upload/" . $_FILES['file']['name'];
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
mysql_query("INSERT INTO images (caption,username,path) VALUES
('$caption','$uploaderUsername','$path')");
header('Location: members.php');

To add to my note above
"I don't see you calling session_start() before attempting to access the session variables. (which just happen to be one of the two variables you aren't getting :O). And in your form make sure you are setting the name='caption' for the caption input"
using the code you provided, to implement the caption you would want to do something along the lines of
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<label for="caption">Caption: </label>
<input type="text" id="caption" name="caption" placeholder="Add a caption here"><br>
<input type="submit" name="submit" value="Submit">
</form>

Related

Upload Image on server using php but it doesn't exsist on server

I am really confused I have this image upload code and it's working fine on my home server "Xampp" and when I click on upload button it upload image and send it to Upload folder but When I upload this php and html page to server and works fine but it can't save image to Upload folder on server please help me out. Thanks
you can try it on my site
http://bing.freevar.com/image_upload.html
Here is HTML file
<html>
<body>
<form action="upload_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>
Here is a PHP file
<?php
$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"] <= 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"] / 10024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
chmod("upload", 0644);
?>
If it works on your local server, but not on production you need to make sure that the folder exists on the production server and that it can be written to by the user account that the PHP script is executing under.
I think you got this PHP script from this link of w3schools.com. This php script has two extra parentheses in if condition. Remove these extra parentheses.
if (/*removed*/($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/x-png")// removed
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts))
It worked for me. Hope it will work for you also. I think you need more validation. You can use getimagesize() function to check width, height, MIME type, attr of the uploaded image.

PHP File Upload Does Nothing

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.";
}
}

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.

How to insert image path in to database?

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>

Error while retrieving files from server

<?php
if(isset($_POST['pic'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 300000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
echo "<h1>Done! Looks Great!</h1>";
}
}
else
{
echo "Invalid file";
}
}
?>
<form action="editprofile.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<p>Image format should be png or jpg.</p>
<center><p class="submit"><input type="submit" name="pic" value="Upload Picture" /></p></center>
</form>
</div>
<p style="text-align:center; font-size:18px;">Current Picture</p>
<?php
$filename = $_FILES['file']['tmp_name'];
?>
<img src="/path/to/the/upload/folder/<?php echo $filename; ?>"/>
<img src="../../upload/foto.PNG" class="picture"/>
I am getting an error like undefined index - file.
Error is in the last few lines.
I basically have a folder which has an image. I want it to display the only image in the folder.
If you open the page for the first time, no form has been sent yet and $_FILES is therefore empty. You try to access $_FILES even in case of first load. This is the faulty line:
$filename = $_FILES['file']['tmp_name'];
You should check that $_POST["pic"] is set before accessing the $_FILES variable (just as you have done on the top of the code).

Categories