wp_title template_directory name home_url get_bloginfo bloginfo blog php

template_directory - ¿Cómo obtener una URL base con PHP?



wordpress home_url (18)

Estoy usando XAMPP en Windows Vista. En mi desarrollo, tengo http://127.0.0.1/test_website/ .

¿Cómo obtengo http://127.0.0.1/test_website/ con PHP?

Intenté algo como esto, pero ninguno de ellos funcionó.

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


Aquí hay uno que acabo de armar que funciona para mí. Devolverá una matriz con 2 elementos. El primer elemento es todo antes del? y el segundo es una matriz que contiene todas las variables de cadena de consulta en una matriz asociativa.

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: Esta es una expansión de la respuesta proporcionada por maček arriba. (Crédito a quien crédito merece.)


Creo que $_SERVER superglobal tiene la información que estás buscando. Puede ser algo como esto:

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

Puede ver la documentación PHP relevante here .


Editado en la respuesta de @ user3832931 para incluir el puerto del servidor.

para formar URL como '' https://localhost:8000/folder/ ''

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


El siguiente código reducirá el problema para verificar el protocolo. $ _SERVER [''APP_URL''] mostrará el nombre de dominio con el protocolo

$ _SERVER [''APP_URL''] devolverá el protocolo: // dominio (por ejemplo: - http: // localhost )

$ _SERVER [''REQUEST_URI''] para las partes restantes de la url, como / directory / subdirectory / something / else

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

La salida sería así

http://localhost/directory/subdirectory/something/else


Encontré esto en http://webcheatsheet.com/php/get_current_page_url.php

Agregue el siguiente código a una página:

<?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; } ?>

Ahora puede obtener la URL de la página actual usando la línea:

<?php echo curPageURL(); ?>

Algunas veces es necesario obtener solo el nombre de la página. El siguiente ejemplo muestra cómo hacerlo:

<?php function curPageName() { return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); } echo "The current page name is ".curPageName(); ?>


Fun ''base_url'' snippet!

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; } }

Use tan simple como:

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


Función ajustada para ejecutarse sin advertencias:

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'']; }


Intenta usar: $_SERVER[''SERVER_NAME''];

Lo usé para hacer eco de la url base de mi sitio para vincular mi CSS.

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

¡Espero que esto ayude!


Prueba esto. Esto funciona para mi.

/*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]); } }

Use esto:

<?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>


Prueba esto:

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

Obtenga más información sobre la variable predefinida $_SERVER

Si planea usar https, puede usar esto:

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

Según esta respuesta , asegúrese de configurar su Apache correctamente para que pueda confiar de forma segura en SERVER_NAME .

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

NOTA : Si depende de la clave HTTP_HOST (que contiene la entrada del usuario), igual debe realizar una limpieza, eliminar espacios, comas, retorno de carro, cualquier cosa que no sea un carácter válido para un dominio. Compruebe las funciones parse_url integradas de php por ejemplo.


Tenía la misma pregunta que el OP, pero tal vez un requisito diferente. Creé esta función ...

/** * 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; }

... que, dicho sea de paso, utilizo para ayudar a crear URL absolutas que deberían usarse para redirigir.


Truco simple y fácil:

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

La URL se ve así: http://example.com/folder/


puedes hacer esto

pero lo siento, mi inglés no es lo suficientemente bueno,

Primero, obtenga la URL de la base con este código simple.

He probado este código por servidor local y público y el resultado es bueno.

<?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();

A la salida le gustará esto:

local machine : http://localhost/my_website/ or https://myhost/my_website public : http://www.my_website.com/ or https://www.my_website.com/

utiliza la función home_base_url en index.php de tu sitio web y defínala

y luego puedes usar esta función para cargar script, css y contenido a través de la URL como

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

creará un resultado como este:

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

y si este script funciona bien ,,!


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

Uso:

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


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


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

Es simplemente fácil de usar
Salida:

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


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

y obtienes algo como

lalala/tralala/something/


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; }