Skip to content
Advertisement

append query string to any form of URL

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement