sirve - php tutorial
anexar cadena de consulta a cualquier forma de URL (6)
Le pido al usuario que ingrese una URL en un cuadro de texto y necesito agregarle una cadena de consulta.
Los valores posibles de las URL pueden ser como:
Ahora necesito agregar una cadena de consulta como "q2 = dos", para que la salida sea como:
¿Cómo puedo lograr lo siguiente usando PHP?
$ url es tu URL. Usa la función de strpos
if(strpos($url,''?'') !== false) {
$url .= ''&q2=two'';
} else {
$url .= ''?q2=two'';
}
Esta es la función que uso:
/**
* @param string $url
* @param $query string|array
* @return string
*/
public function appendQueryStringToURL(string $url, $query): string
{
// the query is empty, return the original url straightaway
if (empty($query)) {
return $url;
}
$parsedUrl = parse_url($url);
if (empty($parsedUrl[''path''])) {
$url .= ''/'';
}
// if the query is array convert it to string
$queryString = is_array($query) ? http_build_query($query) : $query;
// check if there is already any query string in the URL
if (empty($parsedUrl[''query''])) {
// remove duplications
parse_str($queryString, $queryStringArray);
$url .= ''?'' . http_build_query($queryStringArray);
} else {
$queryString = $parsedUrl[''query''] . ''&'' . $queryString;
// remove duplications
parse_str($queryString, $queryStringArray);
// place the updated query in the original query position
$url = substr_replace($url, http_build_query($queryStringArray), strpos($url, $parsedUrl[''query'']), strlen($parsedUrl[''query'']));
}
return $url;
}
Acepta query
como string
o array
. También maneja #
en la URL y elimina las cadenas de consulta duplicadas automáticamente. Aquí está la prueba también. Reemplace CLASS_THAT_CONTAINS_appendQueryStringToURL
con la class
correcta en su proyecto:
public function testAppendQueryStringToURL()
{
$helper = new CLASS_THAT_CONTAINS_appendQueryStringToURL();
$inputsOutputs = [
[
''i'' => ''http://www.example.com'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/?q1=1''
],
[
''i'' => ''http://www.example.com'',
''q'' => ''q1=1&q2=2'',
''o'' => ''http://www.example.com/?q1=1&q2=2''
],
[
''i'' => ''http://www.example.com/a/'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a/?q1=1''
],
[
''i'' => ''http://www.example.com/a.html'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a.html?q1=1''
],
[
''i'' => ''http://www.example.com/a/?q2=2'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a/?q2=2&q1=1''
],
[
''i'' => ''http://www.example.com/a.html?q2=two'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a.html?q2=two&q1=1''
],
[
''i'' => ''http://www.example.com/a.html?q1=1&q2=2'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a.html?q1=1&q2=2''
],
// overwrite the existing
[
''i'' => ''http://www.example.com/a.html?q1=1&q2=2'',
''q'' => ''q1=3'',
''o'' => ''http://www.example.com/a.html?q1=3&q2=2''
],
[
''i'' => ''http://www.example.com/a/#something'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a/#something?q1=1''
],
[
''i'' => ''http://www.example.com/a/?q2=2#soe'',
''q'' => ''q1=1'',
''o'' => ''http://www.example.com/a/?q2=2&q1=1#soe''
],
[
''i'' => ''http://www.example.com'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/?q1=1''
],
[
''i'' => ''http://www.example.com'',
''q'' => [''q1'' => 1, ''q2'' => 2],
''o'' => ''http://www.example.com/?q1=1&q2=2''
],
[
''i'' => ''http://www.example.com/a/'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a/?q1=1''
],
[
''i'' => ''http://www.example.com/a.html'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a.html?q1=1''
],
[
''i'' => ''http://www.example.com/a/?q2=2'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a/?q2=2&q1=1''
],
[
''i'' => ''http://www.example.com/a.html?q2=two'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a.html?q2=two&q1=1''
],
[
''i'' => ''http://www.example.com/a.html?q1=1&q2=2'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a.html?q1=1&q2=2''
],
[
''i'' => ''http://www.example.com/a.html?q1=1&q2=2'',
''q'' => [''q1'' => 3],
''o'' => ''http://www.example.com/a.html?q1=3&q2=2''
],
[
''i'' => ''http://www.example.com/a/#something'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a/#something?q1=1''
],
[
''i'' => ''http://www.example.com/a/?q2=2#soe'',
''q'' => [''q1'' => 1],
''o'' => ''http://www.example.com/a/?q2=2&q1=1#soe''
],
];
foreach ($inputsOutputs as $inputOutput) {
$this->assertEquals($inputOutput[''o''], $helper->appendQueryStringToURL($inputOutput[''i''], $inputOutput[''q'']));
}
}
Mejorando la respuesta de @ alex para tener en cuenta el apéndice infinito de la cadena de consulta
/* Append QueryString to current URL */
function querystring_append($query) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parsedUrl = parse_url($url);
if ($parsedUrl[''path''] == null) {
$url .= ''/'';
}
$separator = ($parsedUrl[''query''] == NULL) ? ''?'' : ''&'';
if(!substr_count($url,$query)) $url .= $separator . $query;
return $url;
}
Uso:
<?=querystring_append("action=logout") ?>
Sé que esto es antiguo, pero mejoré la respuesta de alex para explicar la parte "#" de la cadena.
$urls = array(
''http://www.example.com'',
''http://www.example.com/a/#something'',
''http://www.example.com/a/?q1=one#soe'',
''http://www.example.com/a.html'',
''http://www.example.com/a.html?q1=one''
);
$query = ''q2=two'';
foreach($urls as &$url) {
$pound = "";
$poundPos = -1;
//Is there a #?
if ( ( $poundPos = strpos( $url, "#" ) ) !== false )
{
$pound = substr( $url, $poundPos );
$url = substr( $url, 0, $poundPos );
}
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? ''?'' : ''&'';
$url .= $separator . $query . $pound;
}
var_dump($urls);
Si puede instalar pecl_http, esta es una solución realmente elegante. Puede permitirle verificar si está anulando una variable de obtención que pueden haber establecido.
$urlComps = parse_url($url);
// Get the current query string
$queryString = isset($urlComps[''query'']) ? $urlComps[''query''] : '''';
// Turn it into an array for easy manipulation
parse_str($queryString, $queryVars);
// Make changes to the query vars
$queryVars[''q2''] = ''two'';
// Empty paths return relative URLs.
$urlComps[''path''] = isset($urlComps[''path'']) ? $urlComps[''path''] : ''/'';
// Make the pecl_http call
$newURL = http_build_url($urlComps, array(''query'' => http_build_query($queryVars)));
Nota: si no puede instalar pecl_http, la única función que proviene es la última con la función http_build_url
. Puede crear fácilmente su propia función para reconstruir la URL a partir de sus componentes ...
- parse_url
- parse_str
- http_build_query
- http_build_url * usa pecl_http
<?php
$urls = array(
''http://www.example.com'',
''http://www.example.com/a/'',
''http://www.example.com/a/?q1=one'',
''http://www.example.com/a.html'',
''http://www.example.com/a.html?q1=one''
);
$query = ''q2=two'';
foreach($urls as &$url) {
$parsedUrl = parse_url($url);
if ($parsedUrl[''path''] == null) {
$url .= ''/'';
}
$separator = ($parsedUrl[''query''] == NULL) ? ''?'' : ''&'';
$url .= $separator . $query;
}
var_dump($urls);
Salida
array(5) {
[0]=>
string(29) "http://www.example.com/?q2=two"
[1]=>
string(32) "http://www.example.com/a/?q2=two"
[2]=>
string(39) "http://www.example.com/a/?q1=one&q2=two"
[3]=>
string(36) "http://www.example.com/a.html?q2=two"
[4]=>
&string(43) "http://www.example.com/a.html?q1=one&q2=two"
}
CodePad .