简体   繁体   中英

How can I dynamically use PHP script as img tag and pass text and image name/type in url to execute PHP script

I'm pretty much trying to do my own internal placeholder.com functionality. Where I can pass an image name and text in a URL to a PHP script but have the URL act like an image.

I have a PHP script that will dynamically insert text over an image using the GD PHP library . This part works fine but the URL is (for example): https://my-domain.com/images/image.php?text=Hello%20World

<?php
//http://www.phpforkids.com/php/php-gd-library-adding-text-writing.php
//https://stackoverflow.com/questions/13267846/how-to-add-text-to-an-image-with-php-gd-library
//https://www.php.net/manual/en/book.image.php
//https://stackoverflow.com/questions/43965548/how-to-wrap-text-written-on-an-image-with-the-gd-library
  //Set the Content Type
  header('Content-type: image/jpeg');

  $text = $_GET['text'];

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('paper-2056025_1920.jpg');

  // Allocate A Color For The Text
  $color = imagecolorallocate($jpg_image, 0, 0, 0);

  // Set Path to Font File
  $font_path = 'SourceSansPro-Light.ttf';

  // Set Text to Be Printed On Image
  //$text = "This is a sunset!";

  // Print Text On Image
  imagettftext($jpg_image, 120, 0, 600, 618, $color, $font_path, $text);

  // Send Image to Browser
  imagejpeg($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);
?>

How can I change the URL so I can use this in <img> tags and pass the image name and file type and text for example: https://my-domain.com/images/my-picture.jpg?text=Hello%20World or https://my-domain.com/images/smiley.png?text=More%20Text

For example, Placeholder.com does this by passing the text and image name/type in the URL which allows you to use this as an image tag: https://via.placeholder.com/728x90.png?text=Visit+WhoIsHostingThis.com+Buyers+Guide

在此处输入图片说明

There are similar questions but nothing looks like it's specific to my use case: Create Image From Url Any File Type

You can configure your web server for getting file extension and other vars. Why you don`t use rewrite features in your web server?

so send all requests to your x.php and parse file extension and query strings.

example for nginx:

       rewrite ^/index.php?(.*)$ /$1 permanent;

        try_files $uri @rewriteapp;
        location @rewriteapp {
                rewrite ^(.*)$ /index.php/$1 last;
        }
var_dump($_SERVER['REQUEST_URI']);
//string(17) "/image.png?text=2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM