Replace file url with query string php - 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 :)

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

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;
}
}

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!

Related

PHP Redirect to different URLs based on Parameters

I'm currently using this simple redirect (which passes all URL parameters to the next page) to redirect a link:
<?php
function preserve_qs() {
if (empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], "?") === false) {
return "";
}
return "?" . $_SERVER['QUERY_STRING'];
}
header("Status: 301 Moved Permanently");
header("Location: https://example.com/" . preserve_qs());
?>
One of the issues is that I have with this method is that I need to create a separate file for each redirect.
Is it possible to make this into something that I simply add different URLs inside and based on URL parameter that I call, it sends people to the right URL.
For example, in PHP, we store 3 URLs and we assign them 3 values (parameters):
example1.com = page1
example2.com = page2
example3.com = page3
and the PHP file URL would look like this:
example.com/redirect.php?land=page1?restofparameters
keep in mind that the rest of the parameters need to be sent to the goal page, but not the page1 parameter which calls the URL inside the PHP file.
So the target URL that people will land will would look like this:
example1.com/?restofparamaters
Any help is appreciated. Thank you!
you can try .htaccess method... like this...
In .htaccess file
RewriteEngine On
RewriteRule ^test/(1)? http://triviamaker.com [R=301,L]
then for check this one
localhost/your_project_folder/test/1
Note:- that .htaccess file must be in Root directory of your Project.
& if you have any query or found any problem related to that .htaccess method then you can Search "redirect a specific url to another url with htaccess" in Google. you will Found more details easily about this...
hope this one is Helps to you... Thank You...
I would recommend a link parser.
But here goes an example based on your code for stripping and inheriting GET URL parameters.
<?php
function preserve_qs() {
if (empty($_GET)) return '';
return '?'.http_build_query(array_diff($_GET, ['land']));
}
http_response_code(301);
header('Location: https://example.com/' . preserve_qs());
exit;
?>
I write this in test.php ... just for your Reference
Run This File for check Output...
http://localhost/url_rewrite/test?2
and run also like this http://localhost/url_rewrite/test?land=2
echo $temp = $_GET['land'];
echo $temp = $_SERVER['QUERY_STRING'];
if($temp == "1" || $temp == "land=1"){
header('Location: https://example.com');
}else if($temp == "2" || $temp == "land=2"){
header('Location: https://gmail.com');
}else if($temp == "3" || $temp == "land=3"){
header('Location: https://apple.com');
}else if($temp == "4" || $temp == "land=4"){
header('Location: user/2');
}
I hope this helps to you... Thank you

Only main page being found

So I just started making a new website, or rather modifying an old one. All the code is the same, the only difference is I changed some text here and there. The old website worked perfectly, so this one should as well, so I'm not sure why this is happening, but only the main page can be found using the URLs that I wish to be used. Try going to, for example, the projects page, and not only is the file not found, but my custom not found page won't even be shown. First I'll show some examples then I will show some code.
Main page that works: teivodov.com
Projects page that worked on old site, but not on this one: teivodov.com/projects
Projects page that works, but ugly url form https://teivodov.com?page=projects
Not found page working only if ?page= used: https://teivodov.com?page=blahblah
Here is my htaccess file:
//deny access to this file
<Files ~ ".htaccess">
deny from all
</Files>
//start RewriteEngine
RewriteEngine On
//if the called file is NOT a directory, file or link, we call index.php?page=
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
//disable file listing
Options -Indexes
//set error page 403 (no permission) and 404 (page not found) to our notfound page
ErrorDocument 403 /notfound
ErrorDocument 404 /notfound
order deny,allow
(# replaced with //)
My index.php:
<?php
function dump_error_to_file($errno, $errstr) {
file_put_contents('/errors.log', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler('dump_error_to_file');
//load needed settings, constants, page array and functions
include 'variables.php';
include 'constants.php';
include 'functions.php';
//setting timezone to America/Chicago, needed by some functions
date_default_timezone_set('America/Chicago');
//gets changed to the return of the include file
$ret = 1;
/*
* The include file has to contain the following values:
* Array('filename' => string, -- Filename for template
* 'data' => Array()) -- Array with data for the template
* - At an exception
* string -- Errormessage.
*/
//if no page was called, include the main page
if (!isset($_GET['page'])) {
$ret = include 'includes/' . $files['main'];
} else {
if (isset($_GET['page'])) {
$page = trim($_GET['page']);
} else {
$page = 'main';
}
if (isset($files[$page])) {
//if the file exists include it, else print error message
if (file_exists('includes/' . $files[$page])) {
$ret = include 'includes/' . $files[$page];
} else {
$ret = "Include-File was not found: 'includes/" . $files[$page] . "'";
}
} else {
$ret = include 'includes/' . $files['notfound'];
}
}
//include header template
include 'templates/header.html';
//if the include returns an array, it contains the templatestring and the data array, try to include the template
if (is_array($ret) && isset($ret['filename'], $ret['data']) && is_string($ret['filename']) && is_array($ret['data'])) {
//if the template exists include it, else print error message
if (file_exists($file = 'templates/' . $ret['filename'])) {
$data = $ret['data'];
include $file;
} else {
$data['msg'] = 'Template "' . $file . '" was NOT found.';
include 'templates/error.html';
}
//if the include file returns a string, it returned an exception. So we print it
} else if (is_string($ret)) {
// Exception
$data['msg'] = $ret;
include 'templates/error.html';
//the defualt value of $ret didnt change, so the include didnt return anything. Print error message
} else if (1 === $ret) {
//No return array
$data['msg'] = 'No return in the template!';
include 'templates/error.html';
} else {
//include file has a complete other return like a boolean or something, print error
//everything left
$data['msg'] = 'Include file has an invalid return.';
include 'templates/error.html';
}
//include footer template
include 'templates/footer.html';
Variables.php:
<?php
$files = array();
$files['main'] = 'main.php';
$files['projects'] = 'projects.php';
$files['projects/jda-extended'] = 'projects/jda-extended.php';
$files['contact'] = 'contact.php';
$files['about'] = 'about.php';
$files['notfound'] = 'notfound.php';
An example include file, projects.php:
<?php
$a = array();
$a['filename'] = 'projects.html';
$a['data'] = array();
return $a;
Example template file, projects.html:
<div class="fluid">
<p>
This website is still under construction.
<br><br>
<strong>JDA Extended</strong> - Extension to the JDA API. Allows for quick and easy discord bot development.
</p>
</div>
I believe that should be all the code someone might ask for, but feel free to ask for more if need be. The only difference between my last site and this one, is that the last site was hosted on shared web hosting. This one is hosted on my vps using apache2. It really confuses me as the site is able to find for example includes/main.php and templates/main.html, but not any other files in those folders. The only thing I can think of is something went wrong in the htaccess file as ?page=projects works but /projects does not, but I can't see anything wrong with it?
After playing around, I realized it was an issue with Apache2. By default in /etc/apache2/apache2.conf AllowOverrides is set to None when I needed it to be All. I had done all my testing of the website in windows, which I did not need to bother changing that.

Redirection HTTP/1.1 301 Moved Permanently

I have the following files. The objective of this is to redirect to the correct news. For example:
localhost/tostadotv/esto-es-una-noticia-28.html
If I intentionally modify the url, for example:
localhost/tostadotv/esto-es-una-noticia-modificada-incorrecta-28.html
I should redirect myself to the correct news:
localhost/tostadotv/esto-es-una-noticia-28.html
However, it redirects me to this:
http://localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/esto-es-una-noticia-28.html
Where this error? Could you please help me thanks. Excuse my english I'm from Argentina I do not speak English
.htaccess
RewriteEngine On
RewriteRule ^.*-([0-9]+)\.html$ noticia.php?id_not=$1 [L]
noticia.php
<?php require_once("lib/connection.php"); ?>
<?php require_once("lib/functions.php"); ?>
<?php
fix_category_product_url();
?>
functions.php
function fix_category_product_url() {
$proper_url = get_proper_category_product_url(1);
if ( SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function get_proper_category_product_url($id) {
$product_id = $_GET['id_not'];
$query = sprintf('SELECT titulo FROM noticias WHERE id_not = "%d"', mysqli_real_escape_string($GLOBALS['DB'], $product_id));
$restit = mysqli_query($GLOBALS['DB'], $query);
$noticia = mysqli_fetch_array($restit);
$proper_url = make_category_product_url($noticia['titulo'], $product_id, $id);
return $proper_url;
}
define('SITE_DOMAIN', 'localhost');
function _prepare_url_text($string) {
$NOT_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = iconv('UTF-8','ASCII//TRANSLIT',$string);
$string = preg_replace($NOT_acceptable_characters_regex, '', $string);
$string = trim($string);
$string = preg_replace('#[-_ ]+#', '-', $string);
return $string;
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if ($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}
As said in the comments, the final solution for the asker was to add http:// to the defined SITE_DOMAIN constant.
Before
define('SITE_DOMAIN', 'localhost');
After
define('SITE_DOMAIN', 'http://localhost');
But there's more to it than just that. Let's focus on the following two functions:
function fix_category_product_url(){
$proper_url = get_proper_category_product_url(1);
if(SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url){
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}
The idea here is that $proper_url actually ends up getting a value from make_category_product_url() because its result is returned by get_proper_category_product_url(). It makes sense because make_category_product_url() has more parameters and uses the other to get their values.
What's funny about this is that the else block of the second function doesn't always return a path, but rather a URL. The problem here is that such URL is given without a defined protocol, but starts with the domain name instead. This value is therefore mistaken as a path.
Now take a look at the first function: it ultimately redirects the user using header('Location: '.$proper_url);. As we discussed earlier, $proper_url is not always a path, so the protocol should be added somewhere in the code whenever a URL takes place instead of a path. That's where the actual solution comes in: adding http:// where SITE_DOMAIN is defined is one way to do this, because this constant is only used when a URL takes place. There are many other ways to do this, but this one is completely valid.

Getting a file url for a logged in user and display on screen

Firstly, I am "new"(only been coding for a couple months) to PHP and am trying to get a file for a logged in user to display.
I have tried a few options including baseband and url but it just dosn't seem to work the way I need it to.
Here is a snippet of my code:
$personCalendar = '/folder\calendars\people';
$personFiles = scandir($personCalendars);
$personID = $_SESSION['Person_ID'];
$test = preg_grep('/'.personID.'/',$personFiles);
print_r($test);
echo basename($test);
The output from the print_r gives me Array ( [312] => s15399.ics ) which is great, but I just need the s15399.ics part and have it append to the end of the page url something like https://servername.com/index.php/calendar?s15399.ics so they can take the file and "subscribe" to their calendar.
baseband does not being anything but I am not that surprised by that.
Is this possible, if not, what would be the best way you recommend to do this?
// using \ in a file path is not going to work. Use / instead.
// $personCalendar = '/folder\calendars\people';
$personCalendar = '/folder/calendars/people';
// scandir will work but it will eventually run into problems
// if you have lots and lots of files.
$personFiles = scandir($personCalendars);
$personID = $_SESSION['Person_ID'];
function url(){
return sprintf('%s//%s%s',
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
);
}
// shouldn't the following be $personID, not personID?
$test = preg_grep('/'.$personID.'/', $personFiles);
print_r($test);
$filename = reset($test);
if ( $filename ) {
$fullUrl = url() . $filename;
echo $fullUrl;
} else {
echo "File not found\n";
}
If you need to find a file and you know the file name, you don't need to read all the files. If the file name is the same as the person id, then:
$filename = "s{$personID}.ics";
if ( file_exists($filename) ) {
//
} else {
//
}
You can use current();
$link=current($test);

Reading file contents of a website?

All I want to check is that if a image exists in the link. I load it into an iframe. It was working fine but it seems they have removed the image but a blank.gif still exits.
NOTE: The link is a different domain
I tried the following codes in vain:
<?php
$varia = file_get_contents($url);
echo $varia;
echo "<pre>";
print_r(get_headers($url));
?>
and
$variablee = get_data($url);
pr($variablee);
All I get in the output is:
HTTP ERROR 404
Problem accessing
I want to put the condition that if blank.gif exits......some condition else some other condition.
What should I do?
In my opinion, the best way to test if an URI actual is an image, is to see what getimagesize returns. If it returns an array, it is an image :
function imageExists($uri) {
$info = #getimagesize($uri);
return is_array($info);
}
if (imageExists($uri)) {
...
}
Try
$content = #file_get_contents($url);
if ($content !== false) {
// FILE EXISTS
} else {
// FILE NOT EXISTS
}
?>
You can use this code:
if(getimagesize($url))
{
//image exist
}
else
{
//image not exist
}

Categories