Uploading an image file, resizing it then inserting it into a table - php

I've looked at this PHP file upload/resize method, but I have two questions.
When the image file is uploaded to the directory, the file is the name of the image uploaded from the person's device. I'd prefer it to be some kind of ID / number so that, for example, if person A uploads an image from their device called image1.jpg and so too does another person, it won't overwrite the original.
I know that imgur uses a 7-character string with numbers 0-9 and letters a-Z, so maybe it could generate something similar but also check if it already exists, and if it does, generate another. I'm not sure how to achieve this kind of thing.
I also want to insert the image that's been uploaded into a table.
How could I achieve these two things using the method I linked?

<?php
if(isset($_POST['submit']))
{
$newname = time().'_'.$_FILES['image']['name'];/*Rename image - New unique name of image*/
move_uploaded_file($_FILES['image']['tmp_name'],'upload/'.$newname);/*upload image*/
/*Now use this $newname and use it for insert into database*/
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="submit" value="submit">
</form>

Related

Saving image to PHP session

What I'm attempting to accomplish
Hi! I've scoured the web and can't quite find what I'm looking for. We are working on an internal email signature creation tool. I would like to add an image to a session so I can insert that image into the tool at the end. I do not want to store it in a temp folder or save it to a database. I know this is not best practice to put images in a session. The tool copies all rendered HTML to your clipboard to be immediately inserted into Gmail/Outlook.
My code on Page 1
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
My code on Page 2
<?php
$_SESSION["fileToUpload"] = $_POST['fileToUpload'];
?>
The result
"image.png" text is inserted into the signature tool. Instead of the file info/name inserted into the tool, I want the actual image itself. Is this possible? Thanks!
So you're trying to do something like markdown? That's not going to work...
You could try this:
https://github.com/ziggi/zimg-host
You can convert an image to base64 encode and then play with it.
Example:
$img = file_get_contents('<path>/image.jpg');
$data = base64_encode($img);
As result, you will have a bit string that you can save the value in the session.
But keep in mind that this is not a best practice.
Also, you can use this string in the source of an image.
Example:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAyACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" />

Remember a file upload on form submission

I'm using codeigniter and jquery to create a form that takes text values and a single file upload.
I want it so that if the form validation fails, the uploaded image is still visible to the user, but I'm at a loss now about how to do this without issues popping up.
My current solution is uploading the image regardless if the form validated or not, and then checking if a file with the same name as the name in $_FILES exists, and serving that. But this leads me to a problem with duplicates. I'm appending duplicate file name with a number (eg. file2.jpg), but that means the file uploaded will always find the image name "file.jpg" even if the file the user uploaded with allocated the name "file3.jpg".
There must be a simpler way.
How about save file with hashed name md5(name+actualTimestamp) and save this file name to user session (you could save this filename in cookies or use session mysql table with serialized session data).
How about you assign a unique id to the form, probably a combination of year, month, day, hour, minute and seconds then move uploaded image to a temp directory on your server, save the image with the same name as the form id....
your code should be something like:
<form method="post" action="process.php">
<input type="hidden" name="form_id" value="<?php if(isset($_POST['form_id'])){ echo $_POST['form_id']; }else{ echo date("Ymdhis"); }" />
<!-- other form objects goes here -->
</form>

How to store images to file system (on internet) and store the paths to the database?

We are trying to create a site for wallpapers so that would be somehow large files(2mb-5mb) so we'll be needing to store the images on the disk space instead in the database and only the paths to the database. So if you can give some ideas on how to do that (the method we know for now is creating a PHP script with the upload function and by manually selecting the images from the PC to be uploaded) unless you guys would have other suggestions. Tutorials will be much appreciated. Thanks a lot!
This is for the admins to add images not for the users.
Note: we haven't developed any script so this is to get some ideas from you guys on what we can use with this, if none guess we will just go with the php script.
Your form,
<form action="PHP_FILE_PATH.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
The PHP Part
<?php
if($_FILES['image']['name'])
{
$save_path="FOLDER_PATH_TO_SAVE_UPLOADED_IMAGE"; // Folder where you wanna move the file.
$myname = strtolower($_FILES['image']['tmp_name']); //You are renaming the file here
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.$myname); // Move the uploaded file to the desired folder
}
$inser_into_db="INSERT INTO `database`.`table` (`folder_name`, `file_name`) VALUES('$save_path', '$myname'))";
?>
For each file uploaded, generate a UUID and use that for the filename on disk. That avoids collisions, sanitizing filenames and path traversal vulnerabilities.
You'll have a table like this: (id, description, filename) with values like (1, "Green field", "0D729DCD-5116-4480-81CE-90A0380B557A.png").
Next, you want to avoid the problem of having too many files in one folder — you'll hit a filesystem limitation for many FSes.
To work around this problem, create directories based on the first few letters of the filename. For 0D729DCD-5116-4480-81CE-90A0380B557A.png, you would store it in /0/D/7/0D729DCD-5116-4480-81CE-90A0380B557A.png.

INSERT IMAGE INTO DATABASE and enctype="multipart/form-data"

I'm trying to insert an image into my database. I've read a few posts and I'm clearly doing this wrong. I know that the column datatype needs to be a blob for the image. This I have done.
My form looks like this:
<form id="Dev_test" name="Dev_test" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" enctype="multipart/form-data">
<input type="file" name="call_file" id="call_file">
<input type="submit" name="submit" id="submit" value="SUBMIT">
</form>
This is where I've seen multiple variations of how to do this, and I even came across a post that said this might not be possible.
$query = "INSERT INTO `******`.`******` (img) values ('{$_POST['file']}')"
I know the above isn't right.
So my question(s) is/are the following, is there a reason why $_POST['file'] isn't posting, and is there a better method to insert the image into my database? As an fyi, I'm aware that inserting an image directly into the database is not the most efficient method and that there are other methods by referencing file paths.
What you want to use is php's $_FILES superglobal instead.
$content = file_get_contents($_FILES['call_file']['tmp_name']);
You may want to do virus checking on $content or the like.
I would also suggest that you store the file on the system rather than as a blob in the database and store the path to the file instead.
To store image file in a DB (which is generally a bad idea because filesystem is an db designed specially for effective storing of files) you need to read the contents of the uploaded file and then put it into the query.
In php you should use $_FILES global array to get information about uploaded files, use is_uploaded_file() to check if everything is ok with uploaded file, then you have to read the contents of the uploaded file with standard file access functions and then you MUST escape the contents of the file when inserting it to database.

Upload files using list box in PHP

I want to upload files from a list box in php.
I am able to do it by using <input type="file"> which I found on http://www.tizag.com/phpT/fileupload.php
But when I change this <input type="file"> by <select>
i am trying this way
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<select name="uploadedfile" id = "fileName" size="3" style="width: 100%">
<option id = "uploadedfile" value="c:\text.txt">c:\text.txt</option>
</select>
<input type="submit" value="Upload File" />
</form>
and PHP code remains the same for both cases
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['value']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['value']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
it does not work........
Regards
Hemant
You can only use an <input type="file" /> to upload files for security reasons. These input types display a file select box and allow a user to select a file in a secure way. Allowing a server to select arbitrary files to upload like you are trying to do would be a gross breach of security.
For instance, say I implemented your <select> based option (and it worked). I could select your Windows password file to upload. I could select all sorts of nasty files that are in predefined locations.
As a total aside, your HTML has two elements with the same name. Which one is actually sent to the server will be somewhat dependant on your browser and server. You really only want one form element with the same name.
I'm not sure how this is supposed to work, since you are using a drop down box to ask a user to upload a file.
Drop down menus (select > option) are not, in my experience, used as inputs other than for specific choices, like "blue" vs "red".
however, you are going to run into issues with your setup because a) you the first file option outside of the select element and b) you gave both of them the same name, which means that when php gets the POST variable, it's going to create an array with two items with the same key (if it is even getting to that point).
Update
After reading Matthew's answer, I now notice the c:/text.txt you have set as the value. As he said, that's a big time no. You could in theory have it copy the entire hard drive (very slowly of course) or have some AJAX that doesn't even ask the user if they are okay with the upload and get anything on the computer.
I thought somehow you were offering the user the option to "upload" some generic file already on the server because they had nothing they could use on their end.

Categories