I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.
Related
I run into this problem sometimes with the update form which contains files to upload to a database.
now to explain :I have a submit form with two input Fields. The first input is the name of the image , and the second one is the image itself. The form is submitted to upload.php as you can see the code
upload.php
if(isset($_POST['submit'])){
include 'connection.php';
$imageName=$_POST['imageName'];
$image=$_FILES['image'];
$imageTmpName=$image['tmp_name'];
$imageName=$image['name'];
$imageExt=explode('.',$imageName);
$imageExt=strtolower(end($imageExt));
$newImageName=uniqid('',true).'.'.$imageExt;
$path='C:/xampp/htdocs/test/img/'.$newImageName;
if(move_uploaded_file($imageTmpName,$path)){
echo 'file moved';
}
$query="INSERT INTO imagedata(imageName,image) VALUES ('$imageName','$newImageName')";
if(mysqli_query($conn,$query)){
echo 'data posted to database';
}
}
You can see from the code that I am moving the image temporary name to my path and in the same time I'm and storing the new image name into the database.
I am using the same principle update the image name and the image itself in a new form that is submit to update.php as show below:
if(isset($_POST['update'])){
include 'connection.php';
$uImageName=$_POST['uimageName'];
$uImage=$_FILES['uImage'];
$uImageTmpName=$Image['tmp_name'];
$uImageName=$uImage['name'];
$uImageExt=explode('.',$uImageName);
$uImageExt=strtolower(end($uImageExt));
$uNewImageName=uniqid('',true).'.'.$uImageExt;
$uPath='C:/xampp/htdocs/test/img/'.$uNewImageName;
if(move_uploaded_file($uImageTmpName,$uPath)){
echo 'file updatet';
}
$query="UPDATE imagedata SET imageName='$uImageName',image='$uNewImageName'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
Remember that I am querying database and echo the values inside the input field values itself.Now the problem occurs in the update.php file, whenever i update the image name without uploading any new image, it will update the database with a blank image and return that to my update form.
So what i want to do is whenever i want to update the database without an image from my update form, i want the previous uploaded image to remain the same. Or if i want a new image to be uploaded to the database then i want the database to be updated with the new image and also to delete the old image that i have previous uploaded.
I want to thank you for your help with this
Simple way to keep old image if new image not selected!
Here is the easy way, create a hidden input and echo your old image name in value, and keep new image value empty as follows:
<input type="hidden" name="YourOldFile" value="YourOldFileName">
<input type="file" name="YourNewFile" value="">
Then do if statement in PHP part:
if(!empty($POST['YourNewFile'])) {
$newFile = $_POST['YourNewFile'];
// Then do your update query with uploading new image here and delete old image from the server.
} else {
$YourOldFileName = $_POST['YourOldFile'];
//Then do your query here with oldname and do not delete image from server.
}
Note: you can do same for insert and update, and you need to set where clause for update query.
UPDATE :
Displaying with or without image extention is a different question because its a part of your upload code, and how you save and display.
So, your codes in page looks like this :
include 'connection.php';
if(!empty($_FILES['uImageName'])) {
// Then do your update query with uploading new image here and delete old image from the server.
if(isset($_POST['update'])){
$uImageName=$_FILES['uimageName'];
//Your upload code doesnt look right coded to me, I would use an upload class, You can search for how to upload image
// I use verot upload class its very simple.
$uImageTmpName=$Image['tmp_name'];
$uImageName=$uImage['name'];
$uImageExt=explode('.',$uImageName);
$uImageExt=strtolower(end($uImageExt));
$uNewImageName=uniqid('',true).'.'.$uImageExt;
$uPath='C:/xampp/htdocs/test/img/'.$uNewImageName;
if(move_uploaded_file($uImageTmpName,$uPath)){
echo 'file updated';
}
$query="UPDATE imagedata SET imageName='$uImageName'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
} else {
$YourOldFileName = $_POST['YourOldFile'];
//Then do your query here with oldname and do not delete image from server.
//Solution 1. You can update image column with your old image name.
$query="UPDATE imagedata SET image='$YourOldFileName'";
//Solution 2. You can update all other columns without image column dont update image column and dont include image column in your query.
$query="UPDATE imagedata SET yourColumnName='$DataYouWantToInsert'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
<form>
/*Your inputs here*/
<input type="hidden" name="YourOldFile" value="YourOldFileName">
<input type="file" name="YourNewFile" value="">
/*Your buttons*/
</form>
Read comments in code.
Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end
I have a website that allows users to upload a file. when uploading the file on another page users can download that file. the problem is if the file name has a space in it will only pick up the first work not the whole file name. i was wondering is there a way to download the file with spaces in it or an easy option might be to add underscores to the file name so that it can be downloaded.
//This is the directory where images will be saved
$target = "../images/avatars/";
$target = $target . basename($_FILES['photoLocation']['name']);
// Check to see all fields have been completed
$photoLocation =($_FILES['photoLocation']['name']);
if (!empty($photoLocation))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblPhotoUpload (photoLocation) VALUES ('$photoLocation')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
//Writes the photo to the server
if(move_uploaded_file($_FILES['photoLocation']['tmp_name'], $target))
// Close connection to the database
mysql_close()
And i am displaying the file like this.
while($record = mysql_fetch_array( $result ))
{
?>
<tr class="row">
<td class="cell"><a href= http://xxxxxxxxxxxxxxxxxxxxxx.com/images/avatars/<?php echo $record["photoLocation"];?>>Download</a> </td>
You're dealing with an escaping scheme within an escaping scheme when you work with URLs. In particular, you have to escape the URL so as to be a URL, and then you have to escape the URL as to embed it in HTML:
$url = "http://somesite.tld/some/path/" . urlencode($filename);
echo 'link';
It's pretty damn hard to think of a (realistic) situation that actually requires htmlspecialchars, but wooo paranoia!
Oh, and also, it's typically a good idea to just go ahead and quote all of your attribute values.
When you do: <tag attr=value with spaces> browsers interpret with and spaces as additional attributes, notas part of the value for attr
If you do go the replacement route though, you're just looking for a simple str_replace call:
$val = str_replace(' ', '_', $replaceMe);
Haven't tested but this logic seems right.
$name = str_replace(' ', '_', $photoLocation);
i would recommend to not display image by it original name, since there alot of security problems associated with that.
a way u can do it is to encode file name and save it in extra field in database.
example
$sql = "INSERT INTO tblPhotoUpload (photoLocation,photourl) VALUES ('$photoLocation','".md5($photoLocation)."')";
and when display use phtolocation in url and make display route that to photo location.
good luck,if u need full example let me know
str_replace()
$file= str_replace(' ','_',$file);
or in your case :
$target = $target . basename(str_replace(' ','_',$_FILES['photoLocation']['name']));
$photoLocation =(str_replace(' ','_',$_FILES['photoLocation']['name']));
I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.
I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.