Using htaccess to check file in another directory - php

Ok, I am starting to wonder if this is even possible. I have been pouring over htaccess tutorials and examples and I just can't seem to get it working right.
I have a script that creates dynamic images running in a directory on a friends website. I have access to / but the actual directory I am using is in /mydir/. In order to display the images they are output to png via PHP. I have the following RewriteRule setup to take the filename requested and run a PHP script. Each filename represents a separate file with a serialized object used in the display.php script
RewriteRule ^(.*)\.jpg$ display.php?file=$1
That part is working fine, however if someone requests a file that doesn't exist it just throws PHP errors because the script gets called but there is no object for it to use.
What I am trying to do now, and utterly failing at, is to have it check if the file exists in ./Cache/ directory then run the script as usual and if not then the server can just throw a standard 404.
I have tried things like
RewriteCond %{REQUEST_URI} ^(.*)\.jpg$
RewriteCond %{DOCUMENT ROOT}/img/Cache/%1.jpg -f
and other combinations of REQUEST_URI, REQUEST_URL, SCRIPT_FILENAME, SCRIPT_NAME, etc. I can't seem to come up with the proper variable and regex expression to handle this so I am turning to you guys for help. The biggest problem is not knowing what is actually in each of those variables so I can see where I am going wrong. I would kill for some kind of var_dump(),

Use this rule:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/mydir/img/Cache/$1.jpg -f
RewriteRule ^(.*)\.jpg$ display.php?file=$1 [L]
This needs to be placed into .htaccess file in /mydir/img folder
If you move this folder somewhere else or rename parent folder, you will need update it as well in RewriteCond line.
If you wish you can try this approach, which is more flexible (no need to specify parent folder names) but I cannot guarantee that this will work on your setup (but it DOES work on my PC):
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^(.*)/([^/]+)\.jpg$
RewriteCond %1/Cache/%2.jpg -f
RewriteRule ^(.*)\.jpg display.php?file=$1 [L]
Here the current physical folder is determined automatically from requested URL. But if you have symbolic links or some other settings, it may produce incorrect results. Plus .. it has 1 more Condition .. which makes it a bit slower (1 extra regex to check).

I would use the PHP file to check it:
use file_exists in your PHP and if it does not exist, use header("HTTP/1.0 404 Not Found"); or header('Location to a 404 image

Related

Rewrite PNG URL to PHP File

Please forgive me, but I'm VERY new to PHP, and even worse with url rewrites.
I'd like to write a PHP script that will dynamically output an image that will then be used as a signature on a forum that I belong to.
I have a base PHP file that I'm working with and will be editing that so I'm able to host it for other users of this forum.
The information will be stored in a database, and I'd like to call the PHP script with a PNG URL
Example:
http://somedomain.com/somecode.png
rewriting that to
http://somedomain.com/sig_img.php?img=somecode
Where somecode is the database table primary index.
I don't really need help with the PHP script (yet), but I have no clue where to begin with the .htaccess mod_rewrite code.
Thank you all for any assistance!
Assuming that mod_rewrite is enabled, something like this should work:
<Location />
RewriteEngine On
# ensure requested resource is not a file.
RewriteCond %{SCRIPT_FILENAME} !-f
# ensure requested resource is not a directory.
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*\.png)$ sig_img.php?img=$1 [NC,L]
</Location>
This will redirect any request that is a not a file or directory to the script sig_img.php with the requested filename as the parameter. You may want to restrict this to only .PNG file requests, in which case please read about the options.
Make sure you treat the request as untrusted and parameterise the input; don't just concatenate $_GET['img'] into your query string.

Moving a HTML site to PHP

I currently run a site with 750 pages of .html webpages (yeah I know it was a stupid idea, but I'm a novice). I'm looking to move these to php. I don't really want to set up 750 individual 301 redirects and rewrite each page to .php
I've heard that I can use htaccess to this. Anyone know how?
A few additional questions -
Can I permanently redirect these links from html to php without losing my search engine rankings and
if I want to add php to each of the files (i.e. a php file menu (using the include command) to make the links quicker to update will this work? Because won't they still be html files?
Sorry for the stupid questions, but I'm still learning.
Congratulations on a 750 page site - you must have put some work into that.
To collect your current list of pages use a tool called xenu to create an export into excel. You can then easily change the name the files to PHP in column b and create a .htaccees file.
However why would you want 750 php files? If you have lots of data pages, make it one page and suck in the HTML main content and reference one page. If you have a page called warehouse-depot-22-row-44.html then change that to show-warehouse-row.php?depot=22&row=44 and return that content only. This will significantly reduce your number of pages and to start using databases to render the content.
For redirecting you could use the Apache Module mod_rewrite: https://httpd.apache.org/docs/current/mod/mod_rewrite.html
You can use url rewriting to match a specific file name request with a regular expression and then decide where to redirect if matched
RewriteRule ^myname/?$ myname.php [NC,L]
http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/
Depends on the structure you have.
You want the user to access them in their natural location?
/public_html/folder1/file.php
user would access like
mydomain.com/folder1/file
or you want to map them differently?
Personally I think I would use a rewrite rule to map all requests to my /public_html/index.php and would map the requests from there using php (using include for instance). This gives great flexibility, plus you have a single point of entry for your application which is very beneficial since you can easily maintain control of the application flow.
The .htaccess would look like this
#
# Redirect all to index.php
#
RewriteEngine On
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# RewriteCond %{REQUEST_URI} !^/index\.php
# RewriteCond %{REQUEST_URI} (/[^.]*|\.(php|html?))$ [NC]
RewriteCond %{REQUEST_URI} (/[^.]*|\.)$ [NC]
RewriteRule .* index.php [L]
of course I place all my not directly accessible files (everything except index and css, js, images, etc) to a folder outside the public_html to ensure no user can ever access them directly ;)
I've had a similar (yet much much smaller) site that went through the same thing.
I have this in my .htaccess:
RewriteEngine On
RewriteRule ^(.*)\.html$ $1.php [L]
This will help redirect any visitors to your .html addresses to your .php addresses.
You hopefully have an IDE (I recommend Aptana), and you can use some of the find/change functions project-wide, and hopefully with some time and patience get your internal links from .html to .php.
But, I caution you a little bit - Perhaps it is time to look into a database based CMS, such as Wordpress or Drupal?

How to avoid htaccess rewrite rule from modifiying link on php

Alright, so pretty much I have this on Htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index2.php?url=$1
And I'm trying to execute in a php file the following
mime_content_type('Doggy.png')
and it returns an error saying path of file not found, which I'm pretty sure it does exist,
trying to find what the error could be I ended thinking it's htaccess.
Can anybody help me solve this?
Thank you in advanced.
No, it's not your .htaccess rules. Those only rewrite HTTP requests into file execution rules. Once your PHP executes, they have no influence anymore whatsoever.
The problem is simply that the file Doggy.png does not exist relative to the file where this command is executed. The file must be in the same directory as index2.php, assuming that's the file that contains the line mime_content_type('Doggy.png'). Otherwise you need to use relative paths like mime_content_type('../Doggy.png') or mime_content_type('img/Doggy.png').
As we've established already, the problem is not in rewrite rules.
What actually matters is not he relative location of the files, but rather location of your image file relative to a working directory.
For example, if your directory structure is:
/
/index.php
/inc/imagelib.php
/inc/Doggy.png
and you're doing manipulation on Doggy from the imagelib.php, but it is actually included from index.php and your working directory is /, then, despite being in the same folder, you'll need to address the file as inc/Doggy.png.
The working directory may change, depending on what your entry point in the program will be (in case of a web application - where was the file that originally got the request), or (in case of command line), where were you in shell when executing the command.
To avoid problems with relative paths, i suggest using absolute paths.
So (assuming the same scenario as in the previous example), in imagelib.php you would need to construct the path to image path like this:
`$absolute_path = dirname(__FILE__)."/Doggy.png"`

How do I make this mod_rewrite scheme work with PHP as CGI/FCGI?

Here's the contents of .htaccess:
Options -Indexes
RewriteEngine On
RewriteBase "/"
# Disallow direct access to PHP files.
RewriteRule ^(.*)\.php$ $1 [F,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?<!common/dispatch\.php/)(.*)?$ common/dispatch.php/$1 [NS,L]
Essentially I have all my pages (PHP files) arranged as they would be for direct access without mod_rewrite but I also have dispatch.php in a directory called common, through to which I want all requests to be directed so that I can do some processing before the page script is executed.
It's basically the same idea as used by most frameworks, except I want the page hierarchy to be at the top level and the dispatch script to be kept out of the way with some other bits and pieces in its own subdirectory.
This script works fine on my development machine (which is running PHP as mod_php), but on the production machine it produces an error saying "No input file specified." if running under FCGI. Under normal CGI it works for the most part but if, for example, I go to /foo/bar (with trailing slash missing) and /foo/bar is a directory in the docroot, it sends me to /foo/bar/?/foo/bar. The rest of the script works fine but I don't really want my URIs getting mangled like this, and ideally I'd like to be able to use FCGI as well.
A potential fix for the problem with FCGI seems to be to put the matched $1 in the query string (i.e. after a ?), but this causes all sorts of other odd behaviour that I haven't been able to fix. Is there a straightforward way of fixing this?
Would it not be easier just to use the auto_prepend_file directive in php?

How to understand PHP's URL parsing/routing?

I just inherited a website built in PHP. The main page of www.mysite.com has a href to www.mysite.com/index/35.html somewhere in the page. In the site's root directory and its children there is no document 35.html.
The number 35 is actually an id found in a DB which also holds the html contents of the page.
If I load URL: www.mysite.com/index.php?id=35 the same page loads.
How does PHP know how to automatically convert
/index/35.html
to
/index.php?id=35
EDIT
Based on the answers, I have found a .htaccess file containing rewrite instructions that would explain the functionality.
However, IIS doesn't seem to (or is not configured) know how to use this. (probably because this is an Apache feature?)
So this begs the following question: Is there a way to configure IIS to work with this?
it will be done usign URL Rewriting using .htaccess - should be in the webroot.
It may look something like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
May have other bits, but what this basically tells apache is to send anything that DOES NOT physically exist to index.php
It doesn't. There is a mod_rewrite rule that rewrites from /index/foo to /index.php?id=foo, either in a .htaccess file somewhere or in the httpd configuration itself.
RewriteEngine On
RewriteRule ^index/([\d]+)\.html /index.php?id=$1 [NC,L]
This is off the top of my head. Any browsers trying to load an address starting with index/ has any number ending in .html will be internally redirected to index.php?id= whatever the number is.
Edit: Just saw that your working on IIS. This probably won't work for you. Sorry.
I think you will be using .htaccess to redirect all requests to index.php. From there You can pass the query string a routing class, which will parse the url and identify the unique ids.
In this case we can say like, your routing class will parse the request /index/35.html to indexController, indexAction, id=35. now you can pass this id to the model to get corresponding page contents
NB : Here I a am assuming you are using mvc pattern. Anyway it can be treated in your own way, with the concept remaining the same. Hope this make sence.

Categories