Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append query string to any form of URL

Tags:

php

I ask user to input a URL in a text-box and need to append a query string to it.

Possible values of URLs can be like:

  1. http://www.example.com

  2. http://www.example.com/a/

  3. http://www.example.com/a/?q1=one

  4. http://www.example.com/a.html

  5. http://www.example.com/a.html?q1=one

Now I need to add query string to it like "q2=two", so that output would be like:

  1. http://www.example.com/?q2=two

  2. http://www.example.com/a/?q2=two

  3. http://www.example.com/a/?q1=one&q2=two

  4. http://www.example.com/a.html?q2=two

  5. http://www.example.com/a.html?q1=one&q2=two

How can I achieve the following using PHP?

like image 500
I-M-JM Avatar asked Mar 07 '11 04:03

I-M-JM


People also ask

How can I append a query parameter to an existing URL?

This can be done by using the java. net. URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax. The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

Which HTTP method can append query string to URL?

You can append values to the destination URL of an exit in the standard form of a query string by using Enabler.

How do you add a string to a URL?

To append a param onto the current URL with JavaScript, we can create a new URL instance from the URL string. Then we can call the searchParams. append method on the URL instance to append a new URL parameter into it. to create a new URL instance with "http://foo.bar/?x=1&y=2" .

Does URL include query string?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.


2 Answers

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

Output

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.

like image 196
alex Avatar answered Sep 23 '22 03:09

alex


$url is your URL. Use strpos function

if(strpos($url,'?') !== false) {    $url .= '&q2=two'; } else {    $url .= '?q2=two'; } 
like image 33
Raptor Avatar answered Sep 24 '22 03:09

Raptor