PHP - Get IP when page calling by htaccess - php

I have a website in PHP and need to know what the IP of the accessing client is. For this I am using the function below:
function get_client_ip() {
$ipaddress = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ipaddress = $_SERVER['REMOTE_ADDR'];
}
return $ipaddress;
}
But when accessing the site by url omenorpreco.com/teste the page returns the server IP.
When access to page the url omenorpreco.com/teste.php, the page returns the client IP.
Possibly this error occurs because when you access the page without the extension ".php", the server interprets the page by .htaccess?
How can I adjust my application for both accesses, return the client's IP, and not the server IP?
above my htaccess code
php_value allow_url_fopen on
php_value allow_url_include 1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ url_amigavel.php
RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
RewriteRule sitemap_index.xml$ sitemap_index.php
and url_amigavel.php code
<?php
$geturl = explode( "/", str_replace( strrchr( $_SERVER["REQUEST_URI"], "?" ), "", $_SERVER["REQUEST_URI"] ) );
array_shift( $geturl );
$tipo = $geturl[0];
if ( is_file( "$tipo.php" ) )
{
include "$tipo.php";
}
else
{
echo "page not found";
}
?>
EDIT: CAN I SET GLOBAL_VAR IN HTACCESS WITH THE CLIENT IP?

I think I just saw it work on your server!
Change .htaccess to;
php_value allow_url_fopen on
php_value allow_url_include 1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ url_amigavel.php
RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
RewriteRule sitemap_index.xml$ sitemap_index.php
SetEnvIfNoCase Remote_Host "(.*)" HTTP_MY_REMOTE_HOST=$1
SetEnvIfNoCase Remote_Addr "(.*)" HTTP_MY_REMOTE_ADDR=$1
An change test.php to;
function get_client_ip() {
if (isset($_SERVER[REDIRECT_HTTP_MY_REMOTE_ADDR])) {
return $_SERVER[REDIRECT_HTTP_MY_REMOTE_ADDR];
} else if (isset($_SERVER[REDIRECT_HTTP_MY_REMOTE_HOST])) {
return $_SERVER[REDIRECT_HTTP_MY_REMOTE_HOST];
} else if (isset($_SERVER[HTTP_MY_REMOTE_ADDR])) {
return $_SERVER[HTTP_MY_REMOTE_ADDR];
} else if (isset($_SERVER[HTTP_MY_REMOTE_HOST])) {
return $_SERVER[HTTP_MY_REMOTE_HOST];
}
}
echo get_client_ip();
Inspiration for setting variables in .htaccess from: http://www.askapache.com/htaccess/setenvif.html
Glad it finally worked!

Put this in a file and run with and without the extension:
<?php
function get_ip_address() {
return $_SERVER['REMOTE_ADDR'];
}
echo get_ip_address();
?>
What error do you get if you run the above?
EDIT:
Can you edit your .htaccess like this and see if the error still occurs:
php_value allow_url_fopen on
php_value allow_url_include 1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ $1.php [L]
RewriteRule sitemap-categoria.xml$ sitemap.php?number=categoria
RewriteRule sitemap-([0-9]+).xml$ sitemap.php?number=$1
RewriteRule sitemap_index.xml$ sitemap_index.php

You have allow_url_include set to 1 on your .htaccess. This is causing problems because as you are telling PHP to include a file, the preprocessor thinks it's a URL, other people have told you this so let's go straight.
My guess is, just disable allow_url_include. It's a bad practice, a security risk and there's nothing you can't do just with file_get_contents for example.
If you are still convinced that including remote files is a good idea, you should try using a full path, using this include with the code Benjy1996 gave you:
include(getcwd().$tipo.".php");
PD: you should probably change your ip function to return $_SERVER['REMOTE_ADDR'] only as well, as it's the one you can trust the most, because it's the most difficult to fake.

Related

htaccess hide file name from url

I need to hide the profile.php from appearing in the URL.
So here's what I have:
The URL I am accessing:
sampleuser.domain.com/profile.php
How I get the user 'sampleuser':
$url = "//".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
/*this will give me $url = '//sampleuser.domain.com/profile.php'; */
function get_user_from_url($url)
{
if (strpos($url , 'www.') !== false) {
preg_match('/\/\/www.(.*?)\.domain/', $url, $val);
}
else
{
preg_match('/\/\/(.*?)\./', $url, $val);
}
return $val[1];
}
$user = get_user_from_url($url);
echo $user;
I just need to hide the profile.php, also the thing to consider is if we hide the profile.php, it might conflict with the index.php.
But luckily we will only access the index.php if the URL is only domain.com (without user).
I'm low on htaccess knowledge, can anyone give me the direct answer, and I would be very appreciative if you can add some explanation, it'll give me a head start on learning htaccess.
So basically, what I was making is a dynamic subdomain. So I added a subdomain on my DNS:
*.domain.com
then added these on my htaccess
<IfModule mod_rewrite.c>
#Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.domain.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).domain.com [NC]
RewriteRule ^/?$ /agent/index.php?user=%2 [L]
</IfModule>

Rewrite URL with .htaccess and HTTPS

I have a web site where I have to use a .htaccess file to redirect all requests to index.php, where redirecting is handled.
I want to rewrite the URL, and at the same time use HTTPS. Without HTTPS it works fine.
Code from working .htaccess without HTTPS. Browser gets this input: alert/create
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]
This works fine, but without HTTPS. Browser URL becomes http://localhost/mypage/alert/create, and that's what I want.
I found a solution that allows me to use HTTPS:
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ https://%{SERVER_NAME}/mypage/index.php?controller=$1&action=$2&id=$3 [NC,L]
Page navigation works like a charm, but browser displays the URL like this:
https://localhost/mypage/index.php?controller=alert&action=create&id=
Requests are handled like this:
public function __construct($urlvalues) {
$this->urlvalues = $urlvalues;
if ($this->urlvalues['controller'] == "") {
$this->controller = "home";
} else {
$this->controller = $this->urlvalues['controller'];
}
if ($this->urlvalues['action'] == "") {
$this->action = "index";
} else {
$this->action = $this->urlvalues['action'];
}
}
I need some hints. I've been looking all over internet without solving my problem...
If I can use .htaccess, but implement HTTPS another way, that'll be perfect too.
Server code written in PHP, running on apache2.
I would have done this in two steps. The first that you already have. And this one :
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]
Solved! Solution: Added this to .htaccess, in that order spesifically:
RewriteEngine on
#force https
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]

PHP Apache mod_rewrite

Here's the basic information:
I'm using WAMP on Windows 8 64 bit. Apache 2.4.2, PHP 5.4+.
My project files are located in http://localhost/test/.
The .htaccess file in this folder is:
RewriteEngine on
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L,QSA]
If I enter a URL like http://localhost/test/some/cool/stuff/, it works fine
i.e. in PHP: $_SERVER['QUERY_STRING'] = index.php&some/cool/stuff/
I wish it stripped the index.php& as well but I'm doing that in PHP.
While if I enter a URL like http://localhost/test/some/cool/stuff
the PHP $_SERVER['QUERY_STRING'] returns index.php&some/cool/stuff/&some/cool/stuff
Where's this &some/cool/stuff/ part coming from?
I use RewriteRule ^(.+)$ index.php [L]
And then get the URL by $_SERVER['REQUEST_URI']
I use this function for PHP to get the request URL with fallback.
private static function get_request_URL() {
if (isset($_SERVER["REDIRECT_URL"])) {
$realURL = $_SERVER["REDIRECT_URL"];
} elseif (isset($_SERVER["REQUEST_URI"])) {
list($realURL) = explode("?", $_SERVER["REQUEST_URI"]);
} else {
return null;
}
$realURL = rtrim(trim(strtolower($realURL)), "/");
if ($realURL == "") {
$realURL = "/";
}
return $realURL;
}

301 redirect for old pages of the website with codeIgniter

I have just now upgraded one of my static website to a codeIgniter enabled website. I need to redirect the exact domain names of the old website to the new ones to avoid the 404 error.
Old pages > http://example.com/pagename.php
New pages > http://example.com/index.php/home/category_images/9(cat_id)
I do not a very high no. of pages so hard coding all the pages directly will not be a problem. I have tried :
RewriteEngine On
RewriteBase /
RewriteRule ^http://www.example.com/pagename.php$ http://example.com/index.php/home/category_images/9 [L,R=301]
Not working, I have no idea why. mod_rewrite is enable on my apache server.
Also, just for the confirmation please also tell me in which folder I should put this file, I am confused between root dir or Application folder.
Thank you.
Version 2 : Now after suggestion from Mr. Michael, I tried to implement it using the redirect function like this :
Default Controller function : home.php
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->model('common_model');
$this->handle_redirects();
}
function handle_redirects ()
{
$redirects = Array(
'gorgeous-girls.php' => 'home/category_images/9'
);
$uri = implode('/', $this->uri->segments);
foreach ($redirects as $from => $to)
{
$from = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $from));
if (preg_match("#^{$from}$#i", $uri))
{
if (strpos($to, '$') !== false and strpos($from, '(') !== false)
$to = preg_replace("#^{$from}$#i", $to, $uri);
redirect($to , 'location', 301);
}
}
}
And my .htaccess looks like :
RewriteEngine On
RewriteBase /
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
PS : I have removed index.php from my domain name structure. It looks like : www.example.com/controller/function/uri/uri
Now I am not getting an error page from my host, but I am getting an error page from the CodeIgniter.
Please help.
Considering that your Hypertext Access file should be routing everything through index.php anyway, it is best to handle your redirects using CodeIgniter's redirect() function.
An example is provided below, based on what I have in my Page controller, in my own framework extensions (it can be used anywhere where the redirect() function is available, as well as $this->uri->segments.
function handle_redirects () {
$redirects = Array(
'pagename.php' => 'home/category_images/9'
);
$uri = implode('/', $this->uri->segments);
foreach ($redirects as $from => $to)
{
$from = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $from));
if (preg_match("#^{$from}$#i", $uri))
{
if (strpos($to, '$') !== false and strpos($from, '(') !== false)
$to = preg_replace("#^{$from}$#i", $to, $uri);
redirect($to , 'location', 301);
}
}
}
If you were to pass a query to your pagename.php file in your framework, you could consider the following (note that I do not know what the intention of your pages are - this is a generic solution):
$redirects = Array(
'pagename.php?q=(:any)' => 'home/category_images/$1'
);
For example:
http://example.com/pagename.php?q=9
would redirect you to:
http://example.com/home/category_images/9
This solution works for me quite well, and is very efficient when it comes to cross-browser compatibility.
Note that your RewriteRules should look like this, or something similar to it:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (xml|txt|css|js|jpg|png|gif)$ - [L]
RewriteRule .* index.php [L,QSA]
Edit: The above has been changed to accommodate for assets. Basically, it tells Apache to route everything through index.php, unless it is a file that exists AND has the extensions specified. (This is good practice for security purposes.)
Edit: Note that you should not include index.php in your URL as it is being stripped by the .htaccess file anyway.
Note that I use PHP 5.3 - though this solution should work for you. Please let me know if there are any problems.
You don't use the whole domain name in the match portion of the rewrite rule. Try this:
RewriteRule ^pagename.php$ /index.php/home/category_images/9 [L,R=301]
Of course you will likely need other rules for the server to understand that index.php is the file that is to be called, not something at /image.php/home/category_images/9
So perhaps a second rule like
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^index.php/(.*) /index.php?q=$1 [L]
I just noticed that in your updated answer you are trying to redirect from www.example.com to example.com. If you do want to force one domain, you should probably add another rule in your .htaccess before either of the other rules mentioned like this:
RewriteCond %{HTTP_HOST} ^www.example.com$
Rewrite Rule ^(.*)$ http://example.com/$1 [L,R=301]
you can open you xampp/apache/conf/httpd.conf
After then check below line
#LoadModule rewrite_module modules/mod_rewrite.so
if Hash (#) exist in above the line. then remove it.
LoadModule rewrite_module modules/mod_rewrite.so
and restart your apache server and check you site.
After then site not working please let me know.

Rewrite Url Parameters - Change http://myweb/?dept=dept&app=app to http://myweb/dept/app

I've currently got a web application that I need optimizing, and one of methods or something I'm trying to achieve is such:
http://myweb/dept/app
from
http://myweb/?dept=dept&app=app
I've currently this as the PHP code for it:
if(empty($_REQUEST['dept'])) {
$folder = "apps/";
} else {
$folder = str_replace("/", "", $_REQUEST['dept']) . "/"; }
if(empty($_REQUEST['n'])) {
include('user/home.php');
} else {
$app = $_REQUEST['n'];
if(file_exists($folder.$app.".php")) {
include($folder.$app.".php");
} else {
include("global/error/404.php");
}
}
How do I do this?
I'm currently half there with:
RewriteRule ^([A-Za-z]+)$ /index.php?app=$1
but that only rewrites part of it.
Thanks
The way many frameworks do this is with one of the following rules:
RewriteRule ^(.*)$ /index.php?q=$1
RewriteRule ^(.*)$ /index.php
In the 1st case you get the query string in $_GET["q"].
In the 2nd case you have to get the query string from $_REQUEST or something. (just do some var_dumps till you find what you need).
Then you explode("/") this and you're all set.
Have a look at how TYPO3, eZPublish, Drupal do this.
You should also add the following conditions to allow the site to open your static files (like images/css/js/etc). They tell apache to not do the rewrite if the URL points to a location that actually matches a file, directoy or symlink. (You must do this before the RewriteRule directive)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
This should work:
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&app=$2 [QSA]
You need the QSA part in order for any GET parameters to be appended to the rewritten URL.
You might find that it can be more flexible to rewrite everything to index.php, and then handle splitting up the url there, e.g.
.htaccess:
#only rewrite paths that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
PHP:
<?php
$parts = explode('/', $_SERVER['PATH_INFO']);
$dept = isset($parts[0]) ? $parts[0] : 'someDefault';
$app = isset($parts[1]) ? $parts[1] : 'anotherDefault';

Categories