Laravel - Get client IP address - Getting always 127.0.0.1 result - laravel

I'm unable to get the IP address of the client which I need to determine his current location.
I've used request->ip(), $_SERVER['REMOTE_ADDR'] and I always get a 127.0.0.1 result which is not what I want.
What am I doing wrong?

Sometimes your clients use your application through a proxy, so you should not depend on $_SERVER['REMOTE_ADDR'].
Check out this link (with a little concern on securities):
How to get the client IP address in PHP?

request->ip() will give you client IP. You're getting 127.0.0.1 in because you're trying to access your local project from the same machine.

I found a way how to fix it. But beware that you have to change it before going production!!
Read this part: https://laravel.com/docs/5.7/requests#configuring-trusted-proxies
And now just add this:
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array
*/
protected $proxies = '*';
Now request()->ip() gives you the correct ip

You can try this:
function get_ip() {
$keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
foreach ($keys as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
return $ip;
}
}
}
}
}

There is client IP address this code($_SERVER['REMOTE_ADDR']) applied online project then it will work successfully . it will try..

Related

On $request->ip() I get "::1" on localhost and my controller does not work with white list IP give me custom error

I have a controller that should give permission to use a resource for one IP. If the IP is an invalid controller should give a customized error "Not correct IP".
But when executing the controller, I keep getting the customized error "Not correct IP".
When I send $request->ip() I get "::1"
I am using localhost
My controller
class OhDayHiepController extends Controller
{
const ALLOWED = [
"5.5.5.5",
];
public function whiteIP (Request $request)
{
abort_unless(in_array($request->ip(), self::ALLOWED), die("Not correct IP"));
return $request;
}
}
Why my mistake and why I get ::1. Maybe coz localhost and need custom
"::1" stands for "localhost" in IPv6. You seem to be using IPv4 (xxx.xxx.xxx.xxx).
I don't know what you're trying to achieve so I can't give you the solution for sure, but you can try already with "::1" instead of "5.5.5.5" in ALLOWED.
There must also be a way to configure your local server to use IPv4 only.

Dynamic middleware for laravel 5

While building multi-tenancy packages for Laravel 5 I had to find out how to add middleware dynamically from code. In comparison to this question on SO I do not want to touch the Http/Kernel definitions.
During application initialization I check whether the requested hostname is known in the database and whether this hostname requires a redirect to a primary hostname or ssl.
Because you don't want to touch the Http/Kernel as a package, we need to use the service provider.
Requirements:
dynamically add middleware without touching Http/Kernel
use service provider and response object instead of "hacks"
The solution is to dynamically register the middleware in the kernel. First write your middleware, for instance:
<?php namespace HynMe\MultiTenant\Middleware;
use App;
use Closure;
use Illuminate\Contracts\Routing\Middleware;
class HostnameMiddleware implements Middleware
{
public function handle($request, Closure $next)
{
/* #var \HynMe\MultiTenant\Models\Hostname */
$hostname = App::make('HynMe\Tenant\Hostname');
if(!is_null($redirect = $hostname->redirectActionRequired()))
return $redirect;
return $next($request);
}
}
Now in your service provider use the following code in the boot() method to add this middleware to the Kernel:
$this->app->make('Illuminate\Contracts\Http\Kernel')->prependMiddleware('HynMe\MultiTenant\Middleware\HostnameMiddleware');
To answer what redirectActionRequired() method does in the hostname object:
/**
* Identifies whether a redirect is required for this hostname
* #return \Illuminate\Http\RedirectResponse|null
*/
public function redirectActionRequired()
{
// force to new hostname
if($this->redirect_to)
return $this->redirectToHostname->redirectActionRequired();
// #todo also add ssl check once ssl certificates are support
if($this->prefer_https && !Request::secure())
return redirect()->secure(Request::path());
// if default hostname is loaded and this is not the default hostname
if(Request::getHttpHost() != $this->hostname)
return redirect()->away("http://{$this->hostname}/" . (Request::path() == '/' ? null : Request::path()));
return null;
}
If you need to dynamically register routeMiddleware use the following in your service provider;
$this->app['router']->middleware('shortname', Vendor\Some\Class::class);
Please add comments if you have questions about this implementation.

how to make working SMTP_validateEmail on live site using php

Not working SMTP_validateEmail on live site using php
https://code.google.com/p/php-smtp-email-validation/
<?php
/**
* Example 1
* Validate a single Email via SMTP
*/
// include SMTP Email Validation Class
require_once('smtp_validateEmail.class.php');
// the email to validate
$email = $_POST['name'];
// an optional sender
$sender = $_POST['name'];
// instantiate the class
$SMTP_Validator = new SMTP_validateEmail();
// turn on debugging if you want to view the SMTP transaction
//$SMTP_Validator->debug = true;
// do the validation
$results = $SMTP_Validator->validate(array($email), $sender);
// send email?
if ($results[$email]) {
echo 1;
} else {
echo 0;
}
enter code here
?>
i am having problem on live site but it works fine in localhost.it shows the print_r($results) in the localhost but shows array(0) result in live.i also find $this->sock value in the class smtp_validateEmail.class function validate(email) value empty in live. how to solve this issue any help will be very thankful.
That "Add your web server ip address to var $nameservers = array(‘192.168.0.1’); and if your web server has Port number then update it here var $port = (Port number); Hope you will get the output by making this changes." Only work if you are sending mail with that script but cant tell if that mail checked is good one or not... I have been testing the code, try all changes, but still cant check other mails outside my domain. I can only make it work on my local and webserver host. Still cant call other servers to check if other mails from outside my domain are valid. Working on it.
Complete downloads are here for others to test : https://code.google.com/p/php-smtp-email-validation/downloads/list
Add your web server ip address to var $nameservers = array(‘192.168.0.1’);
and if your web server has Port number then update it here var $port = (Port number);
Hope you will get the output by making this changes.

How to read images from a remote sftp file server

So I'm using CodeIgniter PHP Framework for a website. We have a few servers, a live, a dev, and a file server. We've successfully been able to upload files to our dev server, and then secure copy them to our file server for storage. Our problem now is a way to read/display the images on our dev website from the file server. Our file server uses sftp for it's security. We've been looking into different ways to just pass back an image object from the file server, but not actually the actual file. Any suggestions on how to do this? Thanks.
CodeIgniter PHP Framework
Linux Servers
SFTP on the file server
Thanks...
Well, I have not dealed with sftp so much but at lest I will try to give you some steps to begin.
You need install some apache/php module like ssh2 and enable it with extension=php_ssh2.dll.
You could make your own sftp library, like this:
class Sftp{
protected $connection;
public function __construct($params)
{
}
public function connect()
{
$server = "you-server.com";
$port = "1234";
$username = "admin";
$password = "blabla";
//connect
$ssh2 = ssh2_connect($server, $port);
if(ssh2_auth_password($ssh2, $username, $password))
{
//sftp session
$this->connection = ssh2_sftp($resConnection);
}
else
{
echo "Unable to connect to server";
}
}
public function download($image_name)
{
$image = fopen("ssh2.sftp://{$this->connection}/path/to/{$image_name}", 'r');
fclose($image);
}
}
And then try to use it like:
$this->sftp->connect();
$image = $this->sftp->download('image-name');
I found this Codeigniter library on Github. I haven't used it yet but it seems like you need to do several steps before you could use load the library using Codeigniter. Otherwise this looks promising.
https://github.com/ipolar/CodeIgniter-sFTP-Library

Codeigniter 404 errors - How to tell where they're coming from?

For example in my logs I have many lines that repeat, such as:
ERROR - 2011-07-06 09:19:01 --> 404 Page Not Found --> favicon.ico
Is there any way for me to find out who is calling these errant URLs? The favicon is just an example, there are some URLs that for example show an intent to hack, and others it's just the same error repeated over and over and over again. Basically I'd love to know which IP's to potentially block as well as what sites to contact if they have bad links (or if I should just redirect them on my server with .htaccess).
If you feel the need to do this, just extend the Exceptions class and override the show_404() function:
// v2.x: core/MY_Exceptions.php
// v1.x: libraries/MY_Exceptions.php
class MY_Exceptions extends CI_Exceptions {
/**
* 404 Page Not Found Handler
*
* #access private
* #param string
* #return string
*/
function show_404($page = '', $log_error = TRUE)
{
$heading = "404 Page Not Found";
$message = "The page you requested was not found.";
// By default we log this, but allow a dev to skip it
if ($log_error)
{
// Custom code here, maybe logging some $_SERVER variables
// $_SERVER['HTTP_REFERER'] or $_SERVER['REMOTE_ADDR'] perhaps
// Just add whatever you want to the log message
log_message('error', '404 Page Not Found --> '.$page);
}
echo $this->show_error($heading, $message, 'error_404', 404);
exit;
}
}
If you keep getting stuff like favicon.ico, there's a good chance this is your fault, so you might want to look into that.
Just to clarify:
$_SERVER['HTTP_REFERER'] will give you the URL the page was requested from, so you can see where the request originated, whether it be on your site or elsewhere.
$_SERVER['REMOTE_ADDR'] should give you the IP address the request was made by
http://php.net/manual/en/reserved.variables.server.php
Brief Example:
if ($log_error)
{
$msg = '';
if (isset($_SERVER['HTTP_REFERER']))
{
$msg .= 'Referer was '.$_SERVER['HTTP_REFERER'];
}
else
{
$msg .= 'Referer was not set or empty';
}
if (isset($_SERVER['REMOTE_ADDR']))
{
$msg .= 'IP address was '.$_SERVER['REMOTE_ADDR'];
}
else
{
$msg .= 'Unable to track IP';
}
log_message('error', '404 Page Not Found --> '.$page.' - '.$msg);
}
I believe if you want this, you'd have to log it yourself by creating a custom 404 page and manually logging to the log file. You can access the IP address in PHP via $_SERVER['REMOTE_ADDR'].

Resources