What is the right way to save images to a server?

Asked

Viewed 2,244 times

2

I know the answer to this question is not exact, but I am asking because of alerts I received from a client’s hosting (media temple - DV Developer)

The system I developed saves the images as follows:

/uploads/nome-do-modulo/ano/mes/dai/nome-imagem-encriptado.ext

The media temple sent me an alert saying that i have many images in a single folder.

Really


My host config

  • Ubuntu 12.04 server
  • Apache 2.4.x
  • PHP 5.5.x

Sorry for my English.

If you need more informations, Tell me.

  • 2

    Take a look at this link here Ḿicrosoft, I think it will be very useful for you to have more information about how you will store the images. A summary you can find here Stack Overflow. Usually what I do is store the images in the filesystem and keep a reference to them in the database.

2 answers

5

I use a technique I learned from the structure of an EC platform called Prestashop.

It’s a bit complicated to explain, so I’ll show you an example. Also, I don’t know if there’s an appropriate term to define this technique.

For images of a product, whose ID is 150, the images would be inside the following structure

/images/products/1/5/0/ddshdfhiioiuo.jpg
/images/products/1/5/0/eyfghioiuor.jpg
/images/products/1/5/0/aytdklkkoiuo.jpg

For image names, I use a script that generates unique strings, in order to avoid conflict with existing files. But this is something personal, you can opt for other methods. The most important thing here is the structure where images are stored.

If I want to generate images of different dimensions, example 150px, 750px, 350px, it would look like this:

Taking with example the first image from the list above:

/images/products/1/5/0/ddshdfhiioiuo.jpg (essa é a original, sem compressão, filtros, etc)
/images/products/1/5/0/ddshdfhiioiuo_150.jpg (essa é a de 150 px)
/images/products/1/5/0/ddshdfhiioiuo_750.jpg (essa é a de 750 px)
/images/products/1/5/0/ddshdfhiioiuo_350.jpg (essa é a de 350 px)

The purpose of keeping the original is to be able to generate other images with different dimensions if necessary.

Why did your host ask you to reduce the amount of images in one folder? Obviously because it gets too heavy. Imagine a small Ecommerce of 50,000 products, each of which has 5 images with 3 or 4 versions of each image. When you enter this folder via FTP it is a nightmare. A nightmare, mainly for the host server.

Let’s learn something interesting and very simple with PHP

How to generate a directory images/products/1/5/0 from number 150?

/**
Aqui é definido a base do diretório.
Evite usar paths relativos. Utilize sempre paths absolutos.
*/
$path = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'images/products' . DIRECTORY_SEPARATOR;

/**
O id do produto
*/
$item_id = 150;

/**
Cada caracter será convertido em valores de índices num array
*/
$arr = str_split( $item_id );

/**
Converte o array numa string onde cada valor é separado por DIRECTORY_SEPARATOR

Exemplo, 150 ficará como 1/5/0 ou 1\5\0
*/
$folder = implode( DIRECTORY_SEPARATOR, $arr );

/**
Concatena a base com o folder, formando o path absoluto final
*/
$path .= $folder . DIRECTORY_SEPARATOR;

/**
Descarta os objetos que não serão mais usados. 
Isso é útil somente para micro otimizações.
*/
unset( $arr, $folder );

/**
Verifica se o path já não existe. Caso não existir, prossegue a operação
*/
if( !file_exists( $path ) )
{

    /**
    A função mkdir faz a mágica com ajuda do terceiro parâmetro.
    Quando o terceiro parâmetro receber (bool)TRUE, indica que os subfolders são criados recursivamente. Portanto, não precisa se preocupar em fazer laços de repetição para criar os subfolders.
    */
    if( !mkdir( $path, 0777, true ) )
    {
        /**
        * Se cair aqui, houve algum erro. É aconselhável retornar códigos de erro
        O código abaixo é meramente didático, para exemplo.
        */
         $error_code = 303;
    }
}
  • Daniel, thank you for your answer. I know this method to save images and generate only on demand, but in this client I could not apply when I developed, and now I believe that migrating would be complicated. Furthermore, I believe that, even if there is only 1 image for each product/post, even in 1 or 2 years depending on the demand, the paste will still be full and heavy. Or not?

  • The folder can have more than 1 billion images without problems. The problem is having "1 billion" files in a single folder. The logic of this structure that I presented to you is to reduce the amount in sectioned subfolders. So it is not heavy for listings, for example. The current problem with you, which your host complained about is the exception of files in a single folder, as I mentioned above.

  • Another point is, it doesn’t require any migration.. Maybe you misunderstood when I mentioned Prestashop. I didn’t say you should migrate to Prestashop or any other platform.. Just apply the implementation directly to your current application. One more detail. The structure I passed above is based on Prestashop, however, I have not read the PS codes to see how it is done. I created my own that is there, which presents the same result.

  • Yeah. I’m going to do a little research on this method. In my case it was still well divided: module/year/month/day/name-of-image, but still there was this complaint of the server. No more, I thank you.

  • this technique is also cool. So why does the host complain? Maybe the size of the files?

1

Normally I prefer to convert the images into a Base64 string and save in the database with the name and source in a table pictures.

  • not quite so... the problem is the excess of files in a single folder.

  • Thank you for the reply my friend, but that’s not quite it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.