2 // +-----------------------------------------------------------------------+
3 // | Copyright (c) 2002-2004, Richard Heyes |
4 // | All rights reserved. |
6 // | Redistribution and use in source and binary forms, with or without |
7 // | modification, are permitted provided that the following conditions |
10 // | o Redistributions of source code must retain the above copyright |
11 // | notice, this list of conditions and the following disclaimer. |
12 // | o Redistributions in binary form must reproduce the above copyright |
13 // | notice, this list of conditions and the following disclaimer in the |
14 // | documentation and/or other materials provided with the distribution.|
15 // | o The names of the authors may not be used to endorse or promote |
16 // | products derived from this software without specific prior written |
19 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
20 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
21 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
22 // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
23 // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
24 // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
25 // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
26 // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
27 // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
28 // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
29 // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 // +-----------------------------------------------------------------------+
32 // | Author: Richard Heyes <richard at php net> |
33 // +-----------------------------------------------------------------------+
35 // $Id: URL.php,v 1.49 2007/06/28 14:43:07 davidc Exp $
42 var $options = array('encode_query_keys' => false);
108 function Net_URL($url = null, $useBrackets = true)
110 $this->__construct($url, $useBrackets);
116 * Parses the given url and stores the various parts
117 * Defaults are used in certain cases
119 * @param string $url Optional URL
120 * @param bool $useBrackets Whether to use square brackets when
121 * multiple querystrings with the same name
124 function __construct($url = null, $useBrackets = true)
127 $this->useBrackets = $useBrackets;
132 function initialize()
134 $HTTP_SERVER_VARS = !empty($_SERVER) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
141 $this->querystring = array();
144 // Only use defaults if not an absolute URL given
145 if (!preg_match('/^[a-z0-9]+:\/\//i', $this->url)) {
146 $this->protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
149 * Figure out host/port
151 if (!empty($HTTP_SERVER_VARS['HTTP_HOST']) &&
152 preg_match('/^(.*)(:([0-9]+))?$/U', $HTTP_SERVER_VARS['HTTP_HOST'], $matches))
155 if (!empty($matches[3])) {
158 $port = $this->getStandardPort($this->protocol);
164 $this->host = !empty($host) ? $host : (isset($HTTP_SERVER_VARS['SERVER_NAME']) ? $HTTP_SERVER_VARS['SERVER_NAME'] : 'localhost');
165 $this->port = !empty($port) ? $port : (isset($HTTP_SERVER_VARS['SERVER_PORT']) ? $HTTP_SERVER_VARS['SERVER_PORT'] : $this->getStandardPort($this->protocol));
166 $this->path = !empty($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : '/';
167 $this->querystring = isset($HTTP_SERVER_VARS['QUERY_STRING']) ? $this->_parseRawQuerystring($HTTP_SERVER_VARS['QUERY_STRING']) : null;
171 // Parse the url and store the various parts
172 if (!empty($this->url)) {
173 $urlinfo = parse_url($this->url);
175 // Default querystring
176 $this->querystring = array();
178 foreach ($urlinfo as $key => $value) {
181 $this->protocol = $value;
182 $this->port = $this->getStandardPort($value);
189 $this->$key = $value;
193 if ($value{0} == '/') {
194 $this->path = $value;
196 $path = dirname($this->path) == DIRECTORY_SEPARATOR ? '' : dirname($this->path);
197 $this->path = sprintf('%s/%s', $path, $value);
202 $this->querystring = $this->_parseRawQueryString($value);
206 $this->anchor = $value;
215 * @return string Full url
220 $querystring = $this->getQueryString();
222 $this->url = $this->protocol . '://'
223 . $this->user . (!empty($this->pass) ? ':' : '')
224 . $this->pass . (!empty($this->user) ? '@' : '')
225 . $this->host . ($this->port == $this->getStandardPort($this->protocol) ? '' : ':' . $this->port)
227 . (!empty($querystring) ? '?' . $querystring : '')
228 . (!empty($this->anchor) ? '#' . $this->anchor : '');
234 * Adds or updates a querystring item (URL parameter).
235 * Automatically encodes parameters with rawurlencode() if $preencoded
237 * You can pass an array to $value, it gets mapped via [] in the URL if
238 * $this->useBrackets is activated.
240 * @param string $name Name of item
241 * @param string $value Value of item
242 * @param bool $preencoded Whether value is urlencoded or not, default = not
245 function addQueryString($name, $value, $preencoded = false)
247 if ($this->getOption('encode_query_keys')) {
248 $name = rawurlencode($name);
252 $this->querystring[$name] = $value;
254 $this->querystring[$name] = is_array($value) ? array_map('rawurlencode', $value): rawurlencode($value);
259 * Removes a querystring item
261 * @param string $name Name of item
264 function removeQueryString($name)
266 if ($this->getOption('encode_query_keys')) {
267 $name = rawurlencode($name);
270 if (isset($this->querystring[$name])) {
271 unset($this->querystring[$name]);
276 * Sets the querystring to literally what you supply
278 * @param string $querystring The querystring data. Should be of the format foo=bar&x=y etc
281 function addRawQueryString($querystring)
283 $this->querystring = $this->_parseRawQueryString($querystring);
287 * Returns flat querystring
289 * @return string Querystring
292 function getQueryString()
294 if (!empty($this->querystring)) {
295 foreach ($this->querystring as $name => $value) {
297 $name = rawurlencode($name);
299 if (is_array($value)) {
300 foreach ($value as $k => $v) {
301 $querystring[] = $this->useBrackets ? sprintf('%s[%s]=%s', $name, $k, $v) : ($name . '=' . $v);
303 } elseif (!is_null($value)) {
304 $querystring[] = $name . '=' . $value;
306 $querystring[] = $name;
309 $querystring = implode(ini_get('arg_separator.output'), $querystring);
318 * Parses raw querystring and returns an array of it
320 * @param string $querystring The querystring to parse
321 * @return array An array of the querystring data
324 function _parseRawQuerystring($querystring)
326 $parts = preg_split('/[' . preg_quote(ini_get('arg_separator.input'), '/') . ']/', $querystring, -1, PREG_SPLIT_NO_EMPTY);
329 foreach ($parts as $part) {
330 if (strpos($part, '=') !== false) {
331 $value = substr($part, strpos($part, '=') + 1);
332 $key = substr($part, 0, strpos($part, '='));
338 if (!$this->getOption('encode_query_keys')) {
339 $key = rawurldecode($key);
342 if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
346 // Ensure is an array
347 if (empty($return[$key]) || !is_array($return[$key])) {
348 $return[$key] = array();
353 $return[$key][] = $value;
355 $return[$key][$idx] = $value;
357 } elseif (!$this->useBrackets AND !empty($return[$key])) {
358 $return[$key] = (array)$return[$key];
359 $return[$key][] = $value;
361 $return[$key] = $value;
369 * Resolves //, ../ and ./ from a path and returns
372 * /foo/bar/../boo.php => /foo/boo.php
373 * /foo/bar/../../boo.php => /boo.php
374 * /foo/bar/.././/boo.php => /foo/boo.php
376 * This method can also be called statically.
378 * @param string $path URL path to resolve
379 * @return string The result
381 function resolvePath($path)
383 $path = explode('/', str_replace('//', '/', $path));
385 for ($i=0; $i<count($path); $i++) {
386 if ($path[$i] == '.') {
388 $path = array_values($path);
391 } elseif ($path[$i] == '..' AND ($i > 1 OR ($i == 1 AND $path[0] != '') ) ) {
394 $path = array_values($path);
397 } elseif ($path[$i] == '..' AND $i == 1 AND $path[0] == '') {
399 $path = array_values($path);
407 return implode('/', $path);
411 * Returns the standard port number for a protocol
413 * @param string $scheme The protocol to lookup
414 * @return integer Port number or NULL if no scheme matches
416 * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
418 function getStandardPort($scheme)
420 switch (strtolower($scheme)) {
421 case 'http': return 80;
422 case 'https': return 443;
423 case 'ftp': return 21;
424 case 'imap': return 143;
425 case 'imaps': return 993;
426 case 'pop3': return 110;
427 case 'pop3s': return 995;
428 default: return null;
433 * Forces the URL to a particular protocol
435 * @param string $protocol Protocol to force the URL to
436 * @param integer $port Optional port (standard port is used by default)
438 function setProtocol($protocol, $port = null)
440 $this->protocol = $protocol;
441 $this->port = is_null($port) ? $this->getStandardPort($protocol) : $port;
447 * This function set an option
448 * to be used thorough the script.
451 * @param string $optionName The optionname to set
452 * @param string $value The value of this option.
454 function setOption($optionName, $value)
456 if (!array_key_exists($optionName, $this->options)) {
460 $this->options[$optionName] = $value;
467 * This function gets an option
468 * from the $this->options array
469 * and return it's value.
472 * @param string $opionName The name of the option to retrieve
473 * @see $this->options
475 function getOption($optionName)
477 if (!isset($this->options[$optionName])) {
481 return $this->options[$optionName];