How to store user's profile picture in mysql - php

I am developing a chat application for iOS.
In this app, the users can set up an image as their profile picture.
So my question is, how can i be able to store images in mysql ?
I have seen that many people say, just store the link to the image(on device) in mysql, but how will the images be available on different iOS Devices, from a database right ?
I have also tried using BLOB, but when the table rows are displayed(json encoded), the value for BLOB field comes out to be NULL.
Please answer in brief.
Thanks,

This is fairly simple :) The physical image will be stored on a server and you will store in your DB only the image name, or the relative path to the image, or however you want it. So, if you like, you will have to store in your DB a "pointer" to that image.
So:
- Image in folder on the server
- In DB -> path/to/file or file_name.format OR if you know you path, and you know your format just file_name
Hope this helps! :D

May be late But I just found way to do that.
Way 1: Get image from user and rename with the id (Pref. Primary key) and in Your public_html create folder for images. Set proper permissions for that folder. and save image in that folder and the url of that image will be stored DB column . Like
https://www.example.com/images/user1.png do in that style.
Way 2: use other things to rename that image like user's email,username etc
way 3: In above 2 cases it may happen that other users,hackers may try to download images by using IDs,emails etc.
That's why , another way you can do is you can generate a hash for profile and check if the hash already exists in column if exits then generate another one. Likely I don't think there is possibility of generating similar hashes.but you may check to avoid error in future. and now rename image using that generated hash.
You may also reduce size of that link column using only storing generated hash and in your app declare some variables and achieve
https://www.example.com/images/generated_hash.png
here the url will be same in all columns excluding that hash key.
you may only store that hashes.
Hope it will help
Reference from : https://www.techupdates.live/how-to-save-profile-picture-in-php-in-5-simple-steps/

Related

For image upload, should I add a field to the MYSQL database to check against, or simply use PHP to check if the image exists?

I have a simple image upload form. When someone uploads an image, it is for a football pool, so there always is a $poolid that goes with the image they upload.
Right now, I am naming the uploaded image using the poolid. So for example, if someone uploads an image, it might get named P0714TYER7EN.png.
All the app will ever do is, when it outputs the football pool's page, it will check to see if an image exists for that pool and if so, it will show it. It checks like this:
if (file_exists("uploads/".$poolid.".png")) { //code to show it }
My first thought when planning this was to add a field called "image" in my MYSQL database's table for all the pool information (called pools) and I would store a value of either the image name (P0714TYER7EN.png) or empty if there wasn't one uploaded. Then I would check that field in the database to determine if an image exists or not.
But I realized I don't really need to store anything in the database because I can simply use the PHP file_exists check above to know if there is an image or not.
In other words, it would seem redundant to have a field in the database.
Everything works doing it this way (i.e. NOT having a field in the database) but I'm wondering if this is bad practice for any reason?
If anyone feels that I should absolutely still have a field in the database, please share your thoughts. I just want to do it the proper way.
Thank you.
The approach could depend a lot on what exactly you're trying to do. Seems like the options you would have is:
File System Only
Benefits would be the speed of accessing static files of an image and use of it in your HTML directly which makes it a more simple solution. Also if you're comfortable with using these functions it will be faster to finish.
Drawbacks would be that you're limited to using file_exists and similar. Any code to manage files this way has to be very specific and static. You also can not search or perform operations efficiently on this. In general relying on the file system alone is not a best practice from my experience.
Database Only
Benefits, you can use Blob type as a column with meta data like owner, uploader, timestamp, etc. in the same row. This makes checking for existing files faster as well as any searching or other operations fast and efficient.
Drawbacks, you can't serve files statically using a CDN or even a cookie-less subdomain or other strategies for page performance. You also have to use PHP and MySQL to generate then serve any images via code rather than just referring to the image file directly.
Hybrid
Benefits, basically the same benefits as both above. You can have your metadata in MySQL with a MD5 hash and location of the file available as well. Your PHP then renders the page with a direct link to the file rather than processing the Blob to an image. You could use this in conjunction with a CDN by prefixing or storing the CDN location as well.
Drawbacks, if you manually changed names of files on the server you'd have to rely on a function matching hashes to detect this, though this would also affect a File System Only that needs to detect a duplicate file potentially.
TLDR; the Hybrid approach is what you'll see most software use like WordPress or others and I believe would be considered a best practice while file system only is a bit of a hack.
Note: Database only could be a best approach in specific situations where you want database clustering and replication of images directly in your database rather than to a file system (especially if the file system is restricted access or unable to be modified for any reason, then you have full flexibility on the DB).
You can also use the blob datatypes from mysql. There you can save the image as binary data next to the data about the football pool.
So when you want to load an football pool you simple fire an sql statement and check if it returns a result, if so load the image from the database and display the data, otherwise throw an error.
If you have very frequent access you can simply put the images into a seperate table and load the image independent of the data about the football pool. Additional set some cache headers on the image and put it in a seperate file, this way you could simply save the primary key of the images in football table. Then you want to display the web page you simply load another document, pass it the primary key of the image, there the image will be loaded, or if the browser has it in cache, will load it from cache without querying the database.
This way you also have a better consistency of data and images.
Your uploading an image to specific folder and that too with poolid which will be unique. It should work just fine.
Problem :
The code you have written works great. But the problem is, for the first time if the image loaded is .png and second time loaded file in jpeg or jpg then file exists wont check that and hence it may fail.
Caution :
If you have already taken a caution to check that the image uploaded must and should be png than the file_exists will work great.
Alternate Solution :
In case if your not checking for the image type to be .png then I highly advice you to take a boolean image column in your table by is_image_uploaded or something which can be set once you upload the file every time.
This makes sure that in case next time you wan to upload the image then you can directly go and check in your database table and see that if is_image_uploaded column is set or not. If not set then upload or else ignore or do whatever you want

Image upload in PHP with mySQL

I am reading a lot about uploading images with PHP. I have come to the conclusion that it's best to have a folder /images to keep the files. And have a db table that holds the path to the file and i'd also like to keep track of what it is an image of (in my case houses).
I would have 3 fields in the table:
id
unit
image
Does this sound like the proper way to handle this? I am unable to find any definitive article on how to do this.
Also, when it comes to uploads, are there any recommended articles on how to accomplish this in the manner I want?
Yes it is.
Although mysql lets you store images into records just as strings or numbers it is generally preferred to keep separated "records" from "files".
I'd suggest to avoid recording the path to the image.
Instead, as the image is associated with a record, give the image a name that links it to the record. Assuming your table have an unique, primary key, auto-increment, integer field named id each image will have filename id.jpg
After the upload you'll move the image from the php upload directory to the images directory renaming the file.
For information on how manage file uploads with php google for php upload files

How to add pictures into a blob field using php

I have an SQL DB that comes with a BLOB field that needs to be fill with pictures.
The pictures are in a folder.
How can I use PHP to import the pictures into the blob field automatically if the pictures have the name of the ID field?
edit:
I am not creating the database, just filling it.
The program which is using the database is a merchandise management system, which only allows to store a blob.
That way I have to get the pictures into the SQL and cannot only store the filepath.
Database is DBISAM.
So far I tried to to store the pictures using SQL commands, but cannot see how it would work, so that I hoped someone could help me solving this using PHP.
Best Kurt
I'm not sure if this is helpful, but can I assume that the point of storing the pictures within a BLOB field is simply to associate the image with a specific record in the database? If this is the case, it might be more appropriate to simply reference the filepath of the appropriate image in the DB, rather than trying to store the actual file within the DB. This is more common practice than storing actual resources in the DB, which would take up way too much space for an application of any size.
For example, if you're creating a "users" table and you want to associate a profile picture with an individual user, rather than trying to store a raw .jpg inside the database, instead store /path/to/image/from/webroot.jpg in a field called something like "profile_pic_path" for each user. Then you can reference this path whenever you want to use the image.
You can use
$data = file_get_contents($_FILES['photo']['tmp_name']);
to get your imagedata into a variable (assuming that the file is uploaded and its form element is called 'photo', otherwise change the path). The content of this variable can be stored within a blob field of your database.

Identify folder with PHP

I'm making an image gallery script with PHP which is including a comment system.
The basic function of the script is to read the folder's name and to show a gallery with the folder's
name as title and it's images.
The problem is, that the comment system, which is made with mysql saves a comment like this:
ID | Folder | Image
This works great, but when I change the name of the folder, the script isn't working because there is set the wrong foldername in the Mysql table.
Also when I just save the image's name there is the possibillity of having two pictures in diffrent
folders with the same name.
Is it possible to identify a folder without using it's name?
//Note:
Thank you for your help, I think I found a solution. Now I just save the md5 hash of the image and save it in the Database instead of the foldername.
I guess it's better use another table where you'll save folders ids and their names
folder_id | folder_name
Something like that. Relying on folder names is not a good practice
No. You need to synchronize your filesystem with your database. Whenever you rename/remove/edit a folder, update its entry in the mysql database.
One possibility could be to look at using a checksum of the image contents as a unique identifier. As long as the content doesn't change then you should be OK. As far as identifying changing names of the folders I can't think of any cunning way of detecting this unless you look at using a hash that 's a function of the files contained in it.
I think to be honest that it would be good to re-think the way you're storing/identifying these items in the database.
You could always just do it this way:
Create 3 tables:
galleries -> with the columns
(id,title)
files -> with the columns (id,
gallery, name, filename)
comments -> with the columns (id,
file_id, comment)
You would then create all your galleries with their name in the "galleries" table. When you created the gallery you would put all the images that you want to display in a folder, for example uploads/. You would then insert the name of the file (Maybe generate random filenames too) in the database along with it's real name. For example "Dolphins at Beach" could point to dolphins1234142.png that's in the uploads folder. All your comments would then be in the comments table where you would setup a relationship to the files table. This will allow you to have comments for a certain image.
Just my view on a gallery system, hope it makes sense.

PHP file rename

I have a form where an admin will upload three pictures with different dimensions to three different designated directories. now to make sure that i don't get into the problem of duplicate file names i implemented something like the php will compare the uploaded file name and it will check if that file name exist in the designated directory if yes then it will echo an error and stop the script execution.
Now one of my friend suggested me that it is very bad asking the admin to manually rename the picture file and asking them to take care of the file duplication problem. the solution he suggested was to rename the file automatically and then store it in the database and then direct it to directory.
I am confused about what combination should i give to the renamed file and also make sure it will remain unique file name to be more precise i would like you to understand my directory structure
as i said there will be three pictures files the admin will be uploading namely
a) Title Picture b) Brief Picture c)
Detail Picture
and all the three picture files will be moved to the different respective directory, like title picture goes to title directory and so on.
i am using to script below currently just to move and store the file name with path using varchar in the database.
$ns_pic_title_loc= $_FILES["ns_pic_title"]["tmp_name"];
$ns_pic_title_name = $_FILES["ns_pic_title"]["name"];
move_uploaded_file($ns_pic_title_loc, $ns_title_target.$ns_pic_title_name) or die(mysql_error());
that is just the sample code i havent included the validation function which i am using. i was thinking like i want to rename all the files like
a) In title directory the file should be stored as.
title_1.jpg
title_2.jpg
title_3.jpg
title_4.jpg
and so on
and the same way to rest of the pictures. how do i do that? what function do i use to achieve my target. and if this is not the good way to rename the file i would appreciate any suggestion followed to rename the file.
thanks in advance
Well, here's a possible solution:
Get uploaded filename from $_FILES["ns_pic_title"]["name"] and separate extension OR if we are only talking about image files get the image type with getimagesize($_FILES["ns_pic_title"]["tmp_name"]);
Check your database for the maximum id of the image records and make the the $file_name variable 'title_'.($max_id + 1)
At this point you should have $file_name and $file_extension so do move_uploaded_file($_FILES["ns_pic_title"]["tmp_name"], $ns_title_target.$file_name.'.'.$file_extension)
Hopefully this makes sense and helps.
There are a couple of good options with various pros and cons.
Use php's tempnam when moving the file, and store the path in your mysql database. tempnam generates a unique filename.
Use mysql to store the image content in a blob. This way you will access the image content via an id instead of a pathname.
Instead of having logic to figure out what the latest picture name is and calculate the next number increment, why not just use PHP's tempnam() function? It generates an unique name with a prefix of your choice (i.e., "title", "brief", "detail"). You could also simply prepend a timestamp to the file name -- if you don't have a whole lot of admins uploading pictures at the same time, that should handle most name conflicts.
Since your pictures are going to be sorted into title, brief and detail directories already, it's not really necessary to name each picture title_*, brief_*, and detail_*, right? If it's in the title directory, then it's obviously a title picture.
Also, you're going to be putting the file names in the database. Then elsewhere in the app, when you want to display a picture, I assume you are getting the correct file name from the database. So it isn't really important what the actual file name is as long as the application knows where to find it. If that's correct, it's not necessary to have a very friendly name, thus a tempnam() file name or a timestamp plus the original file name would be acceptable.
Because you are storing references into the DB, I would prefer to just md5 the datetime and use that for the filename and store the disk filename to the DB also. It doesn't matter what name it is written to disk with as long as you can point to it with the unique name into the DB.
I use this methodology, and in none of my testing does the disk name (md5 from the datetime) ever require multiple tries.

Categories