morshed
morshed

Reputation: 315

Replace file url with query string php

I have 1000 images in my website (running in codeingiter), which are named as

My_image_1.png, My_image_2.png ........ My_image_1000.png

and available in this url http://example.com/files/My_image_1.png

But i want the url is http://example.com/images?cid=1.png = My_image_1.png How can i do this in php?

This is what i'm trying

if ( !function_exists('get_img_by_cid')) {
function get_img_by_cid() {
    if ( isset($_GET['cid']) ) {
        $cid = $_GET['cid'];
        return '/path_to_image/My_image_'.$cid.'.png';
    } else {
        return 'Please specify compound id';
    }
}

}

This function return the original path, but i need url like the example below.

In address bar or img tag wherever i use

Here is an example https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=2244

Any help or tutorial will be greatly appriciated :)

Upvotes: 0

Views: 430

Answers (3)

Dooley_labs
Dooley_labs

Reputation: 206

Building on the code provided by @Shishil Patel, a friend and I wrote this:

<?php
$file = "My_image_".$_GET['cid'];
$size = getimagesize($file);
$fp = fopen($file, "rb");
if ($size && $fp) {
    header("Content-type: {$size['mime']}");
    fpassthru($fp);
    exit;
} else {
        header("HTTP/1.0 404 Not Found");
}
readfile("{$file}");
?>

With this, https://example.com/?cid=1.png will display your image without any issues... as long as it's stored to index.php, otherwise your url is similar to https://example.com/index.php?cid=1.png, but with the proper php file name in the url.

EDIT:

On an additional note, $file should contain the folder path to your file, for example

$file = "/path_to_image/My_image_".$_GET['cid'];

Let me know if this was of use, your question was the same issue we had!

Upvotes: 0

Ravi Sachaniya
Ravi Sachaniya

Reputation: 1633

You need to write .htaccess rule :

RewriteCond %{QUERY_STRING} cid=([0-9]+) [NC]
RewriteRule ^images$ /files/My_image_%1.png [L]

Edit :

nginx configuration

location / {
  if ($query_string ~* "cid=([0-9]+)"){
    rewrite ^/images$ /files/My_image_%1.png break;
  }
}

Upvotes: 0

Shishil Patel
Shishil Patel

Reputation: 3967

You can achieve it by following code.

Your URL = http://example.com/images.php?cid=1.png

write below code to images.php file

<img src="<?php echo "My_image_".$_GET['cid'];?>">

Above line will display image with named My_image_1.png

Hope this will helps you

Thanks & Regards

Upvotes: 2

Related Questions