Non blocking functions PHP

后端 未结 7 1818
粉色の甜心
粉色の甜心 2020-12-29 16:12

I have a project in which a user uploads an image through a form and the server does some thumbnails. The thumbnail making process is very slow so I thought that doing the i

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 16:51

    Better solution I usually go for: Create the thumbnails dynamically when needed, not upon upload.

    You create a script that generates thumbnails on the fly, and all your image tags point to this script:

    
    

    This delays the thumbnail generation until it is needed and works "asynchronously". With some .htaccess rewrite magic you can even make it look like a normal image file and cache images in a way that the Apache server will serve them the next time without invoking the script.


    To be a little more detailed, I use this for user profile images:

    Image tags:

    
    

    .htaccess:

    
        RewriteEngine On
    
        # Rewrites requests for user images to match directory structure.
        # E.g.: URL /img/users/123456/50.jpg -> /img/users/123/123456/50.jpg
        # Intermediate directory level is introduced to avoid cramming too many directories into the same directory.
        RewriteRule ^img/users/(\d{1,3})(\d*)/(\d+\.\D+)$ img/users/$1/$1$2/$3 [nocase,last]
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
    
    
    

    This first of all rewrites image requests to a deeper directory structure. If the image exists, Apache will serve it as usual. If it doesn't, my regular application is invoked. In the app, I route /img/users/... URLs to a module that ends up with two pieces of information: the user id 123456 and the requested size 50. It then generates a thumbnail roughly according to this logic:

    1. Find profile image for user 123456
    2. Generate thumbnail in requested size
    3. Write thumbnail to /img/users/123/123456/50.jpg, where it will be picked up by Apache next time
    4. Output image

提交回复
热议问题