Run PHP code from .htaccess? - php

Say I have a rewrite that needs to pass the url to a PHP function and retrieve a value in order to tell what the new destination should be? is there a way to do that?
Thanks.
UPDATE:
Thanks so far guys..I am still having trouble but i'll show you my code:
.htaccess
#I got the file path by echoing DOCUMENT_ROOT and added the rest.
RewriteMap fixurl prg:/var/www/vhosts/mydomain.com/httpsdocs/domain_prototype/code_base/url_handler.php
RewriteEngine On
RewriteRule (.*) ${fixurl:$1} [PT]
PHP:
set_time_limit(0); # forever program!
$keyboard = fopen("php://stdin","r");
while (1) {
$line = trim(fgets($keyboard));
print "www.google.com\n"; # <-- just test to see if working.
}
However I am getting a 500 Internal Server Error I am not sure if there is an error in my .htaccess or in my PHP?

There is something called a RewriteMap.
You can call an executable script that will return the URL to rewrite to.
Check this article for more information and examples (in Perl, but are totally applicable to any other language):
http://www.onlamp.com/pub/a/apache/2005/04/28/apacheckbk.html
Summary of caveats:
Must run a read STDIN loop (ie, don't exit after receiving an URL)
Must print the URL to rewrite to WITH a trailing newline
Must be readable and executable by the user Apache runs as
This is the way to create the map
RewriteMap fixurl prg:/usr/local/scripts/fixit.php
And now we can use it in a RewriteRule:
RewriteEngine On
RewriteRule (.*) ${fixurl:$1}
EDIT: About the Internal Server Error. The most probable cause is what Gumbo mentions, RewriteMap cannot be used in .htaccess, sadly. You can use it in a RewriteRule in .htaccess, but can only create it in server config or virtual host config. To be certain, check the error log.
So, the only PHP / .htaccess only solution would be to rewrite everything to a certain PHP program which does the checking and redirects using the Location header. Something like:
RewriteRule (.*) proxy.php?args=$1 [QSA]
Then, in proxy.php
<?php
$url = get_proper_destination($QUERY_STRING); #args will have the URI path,
#and, via QSA you will have
#the original query string
header("Location: $url");
?>

Yes; you need a RewriteMap, of the External Rewriting Program variety.

What I would do is pass the URL to the PHP page and then do the final redirect using the PHP headers option.
header("Location: new-page.php");
If you didn't want it to redirect, you could also do an include of the page you want. I find that this is a little more flexible than using RewriteMap.
Hope this helps!

Note that the RewriteMap directive can only be used in the server config or virtual host context.

Related

How to clean a url with php without using htaccess?

I have a problem with a project I'm doing with PHP and it's in the URLs.
When I load a script like index.php everything works fine, the problem is when I load a script that is located within two or more directories.
In the URL the scripts with the routes begin to be enmeshed
Here is an example of the problem I have
I need to load a script, even if it is in several levels of nesting, make its functionality and in the url is reflected as:
I need to have something like this
1:
I thank you in advance.
Regards
You can't use PHP to achieve this. PHP is not responsible for determining if PHP (let along a particular PHP script) will handle any given URL.
You have to configure your webserver to do it. Since you mention .htaccess but provide no further information about your server, I'm going to assume you are using Apache HTTPD.
For Apache, that means using mod_rewrite, Alias or something similar. You can put the configuration for those tools in .htaccess, but you don't want to and the documentation advises not to use them.
So put your mod_rewrite or Alias configuration in the main Apache configuration.
You're going to need an htaccess rule no matter what. However, it doesn't have to be a mod_rewrite rule. The reason you need this rule is because PHP is not responsible for the routing - it is merely responsible for the execution of your script.
The point of the rule is to direct apache and instruct it to execute the right script (in your case, script32.php) while keeping the request uri as intact as possible.
There are two ways around it, basically.
Way 1 (cleaner): mod_rewrite
This is pretty straightforward, the set of rules you need are as follows:
# If the requested file name is a valid file/inode
RewriteCond %{REQUEST_FILENAME} -f [OR]
# ...or a directory
RewriteCond %{REQUEST_FILENAME} -d
# ...then throw them straight on it
RewriteRule (.*) - [L]
# ...otherwise, redirect to script32.php with the full content of the request in query string
RewriteRule (.*) /welcome/script32.php?$1 [L]
The requested URL is now in $_SERVER['QUERY_STRING'] and you can now do whatever you like with it in PHP
Way 2: catchall
This does not rely on mod_rewrite and may therefore be slightly faster. However, technically, it's a cheap hack. The way around it is as follows:
ErrorDocument 404 /welcome/script32.php
The requested URL can now be found in $_SERVER['REQUEST_URI'] and is available for parsing in PHP. However, with this, you've also disabled "legit" 404 errors from being generated through apache - and should make sure to obey proper behaviour in PHP to compensate.

Apache PHP mod_rewrite not working

I'm trying to test out the mod_rewrite meaning:
I have two files: level1.php and warpzone.php.
In my .htaccess I have the following code:
RewriteEngine On
RewriteRule ^warp-zone.php$ level-1.php
Yet when I go to warpzone.php, nothing happens :/ (the url doesn't change)
Any suggestions? I really don't know what I'm doing wrong.
First of all you have dashes in php file names at your .htaccess file, while your files does not have them.
Rewrite conditions - this changes the content to new one, but URL stays as it was:
RewriteEngine On
RewriteRule ^warpzone\.php$ level1.php [L]
Redirect conditions - this changes both content and URL to new one:
RewriteEngine On
RewriteRule ^warpzone\.php$ /level1.php [R]
Also you can use Redirect condition instead of mod_rewrite:
Redirect 301 /warpzone.php /level1.php
In case if it does not work for you, you can use headers() method at the top of your warpzone.php file:
<?php
header("Location: " . $_SERVER['SERVER_NAME'] . "/level1.php");
?>
check whether warpzone.php or warp-zone.php is the correct filename, you are mixing them in your example.
check the apache error.log file if mod_rewrite is available, if not then enable it (this can be done either with "LoadModule ..." or it is wrapped by your Linux distribution)
check the apache error.log if you are allowed to use mod_rewrite, if not consider setting "AllowOverride All" in global config files httpd.conf/apache2.conf
change your rewrite rule to "RewriteRule ^warp-zone.php$ level-1.php [L]" to issue an http redirect; without L flag, is is handled internally in the web sever; see https://httpd.apache.org/docs/2.4/rewrite/flags.html for all flags
regards

htaccess rewrite rule not passing url vars when script file is same as rewrite directory

I'm trying to create nice urls with .htaccess files and have come across a weird issue.
I want to change portfolio.php?id=2 to /portfolio/2/
seems pretty simple solution
RewriteRule ^portfolio/([0-9]+)/$ /portfolio.php?id=$1 [L]
this does redirect to the correct script but when i try and run <?=$_GET['id'];?> it is undefined. but if change the script to something that does not equal the fake directory it works.
RewriteRule ^portfolio/([0-9]+)/$ /portfolioitem.php?id=$1 [L]
and just to make sure that it wasn't being caught by any other rules I tested this
RewriteRule ^portfolioitem/([0-9]+)/$ /portfolioitem.php?id=$1 [L]
and again it failed to pick up the id paramater!
any ideas?!
Cheers
This sounds suspiciously like a Multiviews related problem coupled with some PATH_INFO. The Multiviews option is part of mod_negotiation and it will try to match a requested URL path to a file path. It sees:
/portfolio/2/
And sees that there's a /portfolio.php file in the filesystem and assumes that this is what you want (which it is, but not in the same way). I'm willing to bet that instead of looking at $_GET['id'], which is blank of course since there are no GET params, if you look at $_SERVER['PATH_INFO'], you'll see it set to /2/. This is equivalent to going to:
/portfolio.php/2/
where the /2/ part gets passed to portfolio.php as part of the PATH_INFO. And since mod_negotiation is further up in the processing pipeline than mod_rewrite, your rewrite rules never get applied.
Try turning off multiviews. You can do this in your htaccess file using the Options directive (assuming your host has allowed Options):
Options -Multiviews

301 redirect in .htaccess for 30,000 errors

I've been tasked to clean up 30,000 or so url errors left behind from an old website as the result of a redesign and development.
I normally use .htaccess to do this, but I doubt it would be wise to have 30,000 301 redirects inside the .htaccess file!
What methods have some of you used to solve this problem?
Thanks in advance.
Here as you can do with apache httpd
RewriteMap escape int:escape
RewriteMap lowercase int:tolower
RewriteMap my_redir_map txt:map_rewrite.txt
RewriteCond ${my_redir_map:${lowercase:${escape:%{HTTP_HOST}%{REQUEST_URI}}}} ^(.+)$
RewriteRule .* http://%1 [R=301,L]
I use this rewrite rules usually directly inside apache httpd configuration.
Inside the map_rewrite.txt file you have a tab delimited file with the list of redirect in the following format:
www.example.it/tag/nozze www.example.it/categoria/matrimonio
www.example.it/tag/pippo www.example.it/pluto
www.example.it/tag/ancora www.google.com
Would be much easier if you can generalize the approach because the redirect have a common pattern. But if not, in this case you only need to add the redirected url into the list.
Take care to study the RewriteMap configuration, because you can also write the list into a different format, for example like a database table.
Please pay attention to this: I have added escape and lowercase only because there are accents into the urls I need to write. If your urls doesn't have accents, you can remove both.
If you want implement these redirects in php, here the code you need:
<?php
$dest_url = "http://example.com/path...";
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$dest_url);
Create a PHP page to operate as a 404 handler. It should inspect the incoming URL, check if it should map from an old page to a new page, then issue a 301. If there is no mapping then present a 404.
Simply set this page as the 404 handler in your .htaccess and there you go. IIRC this is how Wordpress used to handle 'clean' URLs on IIS before IIS7 brought in URL rewriting without needing a 3rd-party dll.
I have made a redirect class that is on the 404 page that will check the database if there is a valid page to 301 redirect to and redirect it instead of giving the 404 page. If it can't figure that out, it marks it in the database as a 404 page, so it can be fixed later.
Thanks for help guys. I've carried out the suggested course of action from freedev but have created a separate config file within Apache.
Within the httpd.conf file I have added:
# Map settings
Include "conf/extra/map.conf"
The map.conf file:
RewriteEngine On
RewriteEngine on
RewriteMap url_rewrite_map txt:conf/map.map
RewriteCond ${url_rewrite_map:$1|NOT_FOUND} !NOT_FOUND
RewriteRule ^(.*) http://website.com/${url_rewrite_map:$1} [R=301]
The map.map file is formatted as:
/oldname/ /newname
I've added quite a few of the urls for the redirection and so far so good, it isn't having a massive impact on the server like it did when added to .htaccess

How to use directory names as options or parameters?

I don't even know how this method is called, I just know the behavior I want to achieve.
My example for this is Facebook. If you go to facebook.com/[username or id] you get to the profile page, but I can't imagine that they're creating a directory in their root folder and putting a index file in there for every user.
So how's the following behavior accomplished; You go to somepage.com/foo/bar/hello but actually you're requesting somepage.com/foo?bar=hello ?
Is this even possible with Apache and PHP?
I don't even know how this method is called, I just know the behavior I want to achieve.
That thing is called URI/URL and the local part of it is passed to a webserver. The webserver then processes the request.
Is this even possible with Apache and PHP?
Yes. Not even even. This is what a webserver is for. What happens on the server is entirely shielded by the HTTP protocol which knows only the URI/URL specification which does not regulate if and how that needs to match to concrete processes or files on the webserver.
For example with the Apache HTTP Server there is a famous module called Mod_Rewrite that does URL-Rewriting. Often in a fashion that the user with her browser does not take any notice of it.
Example configuration with a PHP file (Apache HTTPD):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>
In a PHP script you can obtain the URI/URL by making use of special variables like $_SERVER['REQUEST_URI'] and $_SERVER['QUERY_STRING'].
Commonly this is made with mod rewrite. There you can make a "path" to a variable of a script.
E.g. http://example.com/user/1/edit could be translated with mod rewrite to http://example.com/index.php?function=edit&userid=1
Such a rule would look like this:
RewriteEngine on
RewriteRule ^/user/([0-9]+)/([a-z]+)$ index.php=function=$2&userid=$1 [L]
The first line activated the rewrite module the second line has a regular expression which must match for rewrite the url internally. If you like you can also make that externally with an [R] modifier instad of the [L].
Have a look to the whole documentation to learn more.
The stuff in the breckets are so called flags which are also well documentated.
I hope that helps!

Categories