Come posso ottenere l'URL di base con PHP?


139

Sto usando XAMPP su Windows Vista. Nel mio sviluppo, ho http://127.0.0.1/test_website/.

Come posso ottenere http://127.0.0.1/test_website/con PHP?

Ho provato qualcosa del genere, ma nessuno di loro ha funzionato.

echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.

1
Come non hanno funzionato? Cosa sono tornati?
animuson

6
@animuson Quelle costanti restituiscono percorsi di filesystem locali, non URL.
Ceejayoz,

possibile duplicato di Ottieni l'URL completo in PHP
T.Todua

Risposte:


251

Prova questo:

<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>

Ulteriori informazioni sulla $_SERVERvariabile predefinita .

Se prevedi di utilizzare https, puoi utilizzare questo:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

echo url();
#=> http://127.0.0.1/foo

Per questa risposta , assicurati di configurare correttamente Apache in modo da poter contare in sicurezza SERVER_NAME.

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>

NOTA : se si dipende dalla HTTP_HOSTchiave (che contiene l'input dell'utente), è comunque necessario effettuare alcune operazioni di pulizia, rimuovere spazi, virgole, ritorno a capo, ecc. Tutto ciò che non è un carattere valido per un dominio. Controlla la funzione integrata parse_url di PHP per un esempio.


2
Dovrebbe controllare $_SERVER['HTTPS']e scambiare https://invece che http://in quei casi.
Ceejayoz,

2
Grazie a te, avevo bisogno di questa funzione.
Brice Favre,

2
che dire di $ _SERVER ['REQUEST_SCHEME']? non è più semplice?
frostymarvelous,

2
Questo non funziona se si utilizza una porta diversa da 80. :(
M'sieur Toph '10

1
@admdrew grazie. Ho ricontrollato che REQUEST_URIinclude già un /; lo fa. @swarnendu, per favore, stai più attento quando modifichi le risposte degli altri. Invece avrebbe dovuto essere un commento.
maček,

28

Funzione regolata per l'esecuzione senza avvisi:

function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

1
Sapevo di averlo fatto prima, ma non riuscivo a ricordare come per qualche motivo. Grazie!
Kyle Coots,

Devo impostare l'URL home sull'immagine dell'intestazione. quando l'utente si trova su una pagina diversa da quella di casa, dovrebbe essere reindirizzato alla homepage facendo clic sull'immagine dell'intestazione. Come lo posso fare?
Joey,

21

Divertente frammento "base_url"!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

Usa semplice come:

//  url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php

echo base_url();    //  will produce something like: http://stackoverflow.com/questions/2820723/
echo base_url(TRUE);    //  will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE);    //  will produce something like: http://stackoverflow.com/questions/
//  and finally
echo base_url(NULL, NULL, TRUE);
//  will produce something like: 
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/2820723/"
//      }

15
   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

Uso:

print "<script src='{$base_url}js/jquery.min.js'/>";

13
$modifyUrl = parse_url($url);
print_r($modifyUrl)

È semplicemente semplice da usare
Output:

Array
(
    [scheme] => http
    [host] => aaa.bbb.com
    [path] => /
)

1
non è il modo migliore per ottenere l'URL di base.
Anjani Barnwal il

@AnjaniBarnwal puoi spiegare perché? Penso che questo è il modo migliore se si dispone di una stringa con un URL e vuole ottenere l'URL di base come https://example.comda https://example.com/category2/page2.html?q=2#lorem-ipsum- che non ha nulla a che fare con la pagina corrente ci si trova.
OZZIE

7

Penso che il $_SERVERsuperglobal abbia le informazioni che stai cercando. Potrebbe essere qualcosa del genere:

echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']

Puoi consultare la relativa documentazione PHP qui .


questo continua a reindirizzare alla stessa pagina dell'utente è ora. come posso risolvere questo problema per reindirizzare alla home page? Sono su Apache, localhost. php7
Joey,

5

Prova il seguente codice:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];

4

Il codice seguente ridurrà il problema per verificare il protocollo. $ _SERVER ['APP_URL'] visualizzerà il nome di dominio con il protocollo

$ _SERVER ['APP_URL'] restituirà il protocollo: // domain (es: - http: // localhost )

$ _SERVER ['REQUEST_URI'] per le parti rimanenti dell'URL come / directory / sottodirectory / qualcos'altro

 $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];

L'output sarebbe così

http: // localhost / directory / sottodirectory / qualcosa / altro


1
Piuttosto che semplicemente incollare un gruppo casuale di codice, spiega cosa hai fatto e perché. In questo modo, l'OP e tutti i futuri lettori con lo stesso problema possono effettivamente imparare qualcosa dalla tua risposta, piuttosto che semplicemente copiarlo / incollarlo e porre di nuovo la stessa domanda domani.
Oldskool

3

L'ho trovato su http://webcheatsheet.com/php/get_current_page_url.php

Aggiungi il seguente codice a una pagina:

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>

Ora puoi ottenere l'URL della pagina corrente usando la riga:

<?php
  echo curPageURL();
?>

A volte è necessario ottenere solo il nome della pagina. L'esempio seguente mostra come farlo:

<?php
function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}

echo "The current page name is ".curPageName();
?>

2
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";

$url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];

2

Prova questo. Per me funziona.

/*url.php file*/

trait URL {
    private $url = '';
    private $current_url = '';
    public $get = '';

    function __construct()
    {
        $this->url = $_SERVER['SERVER_NAME'];
        $this->current_url = $_SERVER['REQUEST_URI'];

        $clean_server = str_replace('', $this->url, $this->current_url);
        $clean_server = explode('/', $clean_server);

        $this->get = array('base_url' => "/".$clean_server[1]);
    }
}

Usa così:

<?php
/*
Test file

Tested for links:

http://localhost/index.php
http://localhost/
http://localhost/index.php/
http://localhost/url/index.php    
http://localhost/url/index.php/  
http://localhost/url/ab
http://localhost/url/ab/c
*/

require_once 'sys/url.php';

class Home
{
    use URL;
}

$h = new Home();

?>

<a href="<?=$h->get['base_url']?>">Base</a>

2

Trucco semplice e facile:

$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";

L'URL è simile al seguente: http://example.com/folder/


2

Puoi farlo in questo modo, ma mi dispiace che il mio inglese non sia abbastanza buono.

Per prima cosa, ottieni l'URL di base con questo semplice codice.

Ho testato questo codice sul mio server locale e pubblico e il risultato è buono.

<?php

function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}

?>

// and test it

echo home_base_url();

l'output gradirà questo:

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

usare la home_base_urlfunzione aindex.php tuo sito web e definiscila

e quindi è possibile utilizzare questa funzione per caricare script, CSS e contenuto tramite URL come

<?php

echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";

?>

creerà output in questo modo:

<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>

e se questo script funziona bene ,,!


2
Si prega di non includere collegamenti ai siti Web nelle risposte
ChrisF

1

Eccone uno che ho appena messo insieme che funziona per me. Restituirà un array con 2 elementi. Il primo elemento è tutto prima del? e il secondo è un array che contiene tutte le variabili della stringa di query in un array associativo.

function disectURL()
{
    $arr = array();
    $a = explode('?',sprintf(
        "%s://%s%s",
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME'],
        $_SERVER['REQUEST_URI']
    ));

    $arr['base_url']     = $a[0];
    $arr['query_string'] = [];

    if(sizeof($a) == 2)
    {
        $b = explode('&', $a[1]);
        $qs = array();

        foreach ($b as $c)
        {
            $d = explode('=', $c);
            $qs[$d[0]] = $d[1];
        }
        $arr['query_string'] = (count($qs)) ? $qs : '';
    }

    return $arr;

}

Nota: questa è un'espansione della risposta fornita da maček sopra. (Credito dove è dovuto il credito.)



0
function server_url(){
    $server ="";

    if(isset($_SERVER['SERVER_NAME'])){
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/');
    }
    else{
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/');
    }
    print $server;

}

0

Prova a usare: $_SERVER['SERVER_NAME'];

L'ho usato per fare eco all'URL di base del mio sito per collegare il mio CSS.

<link href="https://stackoverflow.com//<?php echo $_SERVER['SERVER_NAME']; ?>/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css">

Spero che questo ti aiuti!


0

Ho avuto la stessa domanda del PO, ma forse un requisito diverso. Ho creato questa funzione ...

/**
 * Get the base URL of the current page. For example, if the current page URL is
 * "https://example.com/dir/example.php?whatever" this function will return
 * "https://example.com/dir/" .
 *
 * @return string The base URL of the current page.
 */
function get_base_url() {

    $protocol = filter_input(INPUT_SERVER, 'HTTPS');
    if (empty($protocol)) {
        $protocol = "http";
    }

    $host = filter_input(INPUT_SERVER, 'HTTP_HOST');

    $request_uri_full = filter_input(INPUT_SERVER, 'REQUEST_URI');
    $last_slash_pos = strrpos($request_uri_full, "/");
    if ($last_slash_pos === FALSE) {
        $request_uri_sub = $request_uri_full;
    }
    else {
        $request_uri_sub = substr($request_uri_full, 0, $last_slash_pos + 1);
    }

    return $protocol . "://" . $host . $request_uri_sub;

}

... che, per inciso, utilizzo per aiutare a creare URL assoluti da utilizzare per il reindirizzamento.


0
$some_variable =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);

e ottieni qualcosa del genere

lalala/tralala/something/

C'è molto codice su questa voce di domande e risposte che appartiene alla zona di pericolo, anche a causa dell'uso di PHP_SELF.
Hacre,

0

Basta testare e ottenere il risultato.

// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
echo $protocol.$hostName.$pathInfo['dirname']."/";

0

Nel mio caso avevo bisogno dell'URL di base simile a quello RewriteBasecontenuto nel file.htaccess file.

Sfortunatamente il semplice recupero del file RewriteBasedal .htaccessfile è impossibile con PHP. Ma è possibile impostare una variabile di ambiente nel file .htaccess e quindi recuperare quella variabile in PHP. Dai un'occhiata a questi bit di codice:

.htaccess

SetEnv BASE_PATH /

index.php

Ora lo uso nel tag di base del modello (nella sezione head della pagina):

<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>

Quindi se la variabile non era vuota, la usiamo. Altrimenti fallback /come percorso base predefinito.

In base all'ambiente, l'URL di base sarà sempre corretto. Uso /come URL di base su siti Web locali e di produzione. Ma /foldername/per l'ambiente di messa in scena.

Avevano tutti il ​​loro .htaccessin primo luogo perché RewriteBase era diverso. Quindi questa soluzione funziona per me.


0

Dai un'occhiata a $ _SERVER ['REQUEST_URI'], ad es

$current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Se si desidera supportare sia HTTP che HTTPS, è possibile utilizzare questa soluzione

$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Questo ha funzionato per me. Spero che questo ti possa aiutare. Grazie per aver posto questa domanda.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.