Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the server IP with Laravel?
In Laravel, you can get the server IP address using the global $_SERVER['SERVER_ADDR'] variable or Laravel's builtin request methods. The server IP represents the IP address of the server hosting your application.
The $_SERVER superglobal variable contains information about headers, paths, and script locations, including server details.
Using $_SERVER['SERVER_ADDR']
The simplest method is to access the server IP directly from the $_SERVER superglobal ?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ServerController extends Controller {
public function getServerIP() {
echo $_SERVER['SERVER_ADDR'];
}
}
?>
127.0.0.1
Using Laravel's Request Object
Laravel provides the request() helper function with a server() method to access server variables ?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ServerController extends Controller {
public function getServerIP() {
echo request()->server('SERVER_ADDR');
}
}
?>
127.0.0.1
Client IP vs Server IP
Note that request()->ip() returns the client's IP address, not the server IP ?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ServerController extends Controller {
public function compareIPs() {
echo "Server IP: " . $_SERVER['SERVER_ADDR'] . "<br>";
echo "Client IP: " . request()->ip();
}
}
?>
Server IP: 127.0.0.1 Client IP: 127.0.0.1
Conclusion
Use $_SERVER['SERVER_ADDR'] or request()->server('SERVER_ADDR') to get the server IP in Laravel. Remember that request()->ip() returns the client IP, not the server IP.
