Storing Images Like Facebook with PHP

Store your images like Facebook, Google, and Youtube.

Today I want to talk about image storage using PHP. Many websites like Facebook, Twitter and YouTube create a random string for the name of the image uploaded to there server via user. Using PHP, we will achieve the same method of storing the string (name of the image) in the database and store the physical image in a folder. On a site like Facebook, you might have many folders for the images; such as one for user profile images, one for user post images, and so on. We will go over exactly how they achieve this.

If you look at your profile image on Facebook, you can see that the URL of your profile image has a weird image name, like the example below:

Facebook stores your profile image 2 folders deep on a CDN server called They use for their CDN sever to host images on.
Today we will go over how to store a users profile image on the same domain. You want to store the users image in a folder and store the name in the database.

The Database

Let’s start by creating a database called Users and a table named User_images.

Folder Structure

Our image structure will look like this:

Create a folder on your server called User.

Warning: Storing all images in the same folder may cause the server to run slow.

The Image Storage

When we upload an image to our site, we create a random string for the name of the image . After we create the string, insert it into the database for the user the image belongs to. Then save the image to the folder called User.

Create the random string and store it in a variable called $random_string. Random string looks something like this: 1ds9d27d7ddAD790346789FSoBdQzl

Now that we have our random string, we can insert it into the database.

Next, insert the image into the User folder.

Example: user/1ds9d27d7ddAD790346789FSoBdQzl.jpg
The image should now be saved in your User folder, like the example above.

The full image storage code

Retrieving the Image

To display the users profile image, simply get the users profile picture name from the database. Then display the name in a <img> tag.

Now you can store your images like Facebook, Google, and Youtube.
I hope this helps you.


Tagged with:

View all contributions by


Related Articles


Stay connected with us

Add us on Google+

Follow us on Facebook

Follow us on Twitter

Get updates via RSS

Get email updates


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">