questions

Append text string to end of image file on page load / download

Rate this post

I want to append something like this in real time (god help me) to a low traffic site:

When the page loads, some assets (images) are loaded (lazily)) let’s assume the page would normally serve image1.png, image2.png, and image3.png

I would like to concat “username:%user%” where user is the logged in wp_user to the end of image1/2/3.png (not as a watermark, but by literally adding the string to the file itself) by real-time copying them to a temp directory and serving them from there.

While this is an unorthodox request, is there any realistic way to do this using nginx or wordpress?

Including site.conf

server {
server_name test.com www.test.com;
root /var/www/test.com/public_html/;
index index.php index.html index.htm index.nginx-debian.html;
client_max_body_size 100M;
location / {
     proxy_max_temp_file_size 0;
     try_files $uri $uri/ /index.php?q=$uri&$args; 
}

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }
    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt { log_not_found off; access_log off; allow all; }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        expires max;
        log_not_found off;
    }
    location = /xmlrpc.php {
      deny all;
      log_not_found off;
      return 200;
    }

listen 443 ssl; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

 

✔️Solution:

Here it is. First, an nginx config part. If there are only PNG files inside the wp-content/uploads/master directory, you could use more simple

location ^~ /wp-content/uploads/master/ {
    rewrite ^ /pngproxy.php last;
}

(note the ^~ modifier, with its help this location would take priority over the location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ { ... } one. If there are files of other types in that directory, use the regex matching location

location ~ ^/wp-content/uploads/master/.+\.png$ {
    rewrite ^ /pngproxy.php last;
}

(should be before the location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ { ... }) This way any request for a PNG file inside the /wp-content/uploads/master/ directory would go to the pngproxy.php script.

Now the PHP part. Name this file pngproxy.php and put it into the WordPress root:

<?php
// load WordPress core
require_once('wp-load.php');

if ( is_user_logged_in() // if WordPress user is logged in
     // get an original URI from 'REQUEST_URI' FastCGI parameter and check if it is a path to .png file
     // regex can be changed to be more strict, for example including the '/wp-content/uploads/master/' path prefix
     && preg_match( '/^\\/([^?]*\\.png)(?:$|\\?)/', $_SERVER['REQUEST_URI'], $matches )
     // and the file exists
     && file_exists( ABSPATH . $matches[1] )
     // and it is readable
     && ( $png = file_get_contents( ABSPATH . $matches[1] ) ) ) {

        $current_user = wp_get_current_user();
        // add user name signature
        $png .= "username:%{$current_user->user_login}%";
        // output the headers
        header( 'Content-Type: image/png' );
        header( 'Content-Length: ' . strlen( $png ) );
        // disable any sort of cache
        header( 'Cache-Control: no-cache, no-store, must-revalidate' );
        // output the data
        echo $png;

} else {
    // generate HTTP 404 Not Found
    header( $_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
    // or use HTTP 403 Forbidden if you like it more
    //header( $_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
}
?>

Leave a Reply

Your email address will not be published.

Back to top button