search
HomeBackend DevelopmentPHP Tutorial2 ways to parse URLs in php

2 ways to parse URLs in php

Jun 13, 2018 am 10:57 AM
parse_strparse_urlphp

This article mainly introduces you to two methods of parsing URLs in PHP (parse_url and parse_str), as well as the introduction and usage of these two methods. It is very comprehensive and recommended to friends in need.

There are two methods in PHP that can be used to parse URLs, namely parse_url and parse_str.

parse_urlParse the URL and return its components

mixed parse_url ( string $url [, int $component = -1 ] )

This function Parses a URL and returns an associative array containing the various components that appear in the URL.

This function is not used to verify the validity of the given URL, but to break it down into the parts listed below. Incomplete URLs are also accepted and parse_url() will try to parse them as correctly as possible.

Parameters

url The URL to be parsed. Invalid characters will be replaced with _.

component Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to get the string of the specified part of the URL. (Except when specified as PHP_URL_PORT, an integer value will be returned).

Return value

For severely unqualified URLs, parse_url() may return FALSE.

If the component parameter is omitted, an associative array array will be returned, and at least one element will currently be in the array. Possible keys in the array are:

scheme - like http
host
port
user
pass
path
query - after the question mark?
fragment - after the hash symbol
#If the component parameter is specified, parse_url() returns a string (or an integer when specified as PHP_URL_PORT) instead of an array. If the specified component in the URL does not exist, NULL will be returned.

Example

The code is as follows:

<?php
$url = &#39;http://username:password@hostname/path?arg=value#anchor&#39;;
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>

The above routine will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

parse_str

will The string is parsed into multiple variables

void parse_str ( string $str [, array &$arr ] )

If str is the query string passed in by the URL, then It is resolved to a variable and set to the current scope.

To get the current QUERY_STRING, you can use the $_SERVER['QUERY_STRING'] variable.

Parameters

str Input string.

arr If the second variable arr is set, the variable will be stored in this array as an array element instead. ,

Example

The code is as follows:

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output[&#39;first&#39;];  // value
echo $output[&#39;arr&#39;][0]; // foo bar
echo $output[&#39;arr&#39;][1]; // baz
?>

I was reading the source code of php-resque some time ago and saw the application of these two methods in it. I feel that it is useful. Very good, settings used to parse redis links.

The format of the redis link is: redis://user:pass@host:port/db?option1=val1&option2=val2. Is it the same as the URL, so it is easy to parse using the above two methods.

Address: https://github.com/chrisboulton/php-resque/blob/master/lib/Resque/Redis.php

The code is as follows:

 /**
     * Parse a DSN string, which can have one of the following formats:
     *
     * - host:port
     * - redis://user:pass@host:port/db?option1=val1&option2=val2
     * - tcp://user:pass@host:port/db?option1=val1&option2=val2
     *
     * Note: the &#39;user&#39; part of the DSN is not used.
     *
     * @param string $dsn A DSN string
     * @return array An array of DSN compotnents, with &#39;false&#39; values for any unknown components. e.g.
     *               [host, port, db, user, pass, options]
     */
    public static function parseDsn($dsn)
    {
        if ($dsn == &#39;&#39;) {
            // Use a sensible default for an empty DNS string
            $dsn = &#39;redis://&#39; . self::DEFAULT_HOST;
        }
        $parts = parse_url($dsn);
        // Check the URI scheme
        $validSchemes = array(&#39;redis&#39;, &#39;tcp&#39;);
        if (isset($parts[&#39;scheme&#39;]) && ! in_array($parts[&#39;scheme&#39;], $validSchemes)) {
            throw new \InvalidArgumentException("Invalid DSN. Supported schemes are " . implode(&#39;, &#39;, $validSchemes));
        }
        // Allow simple &#39;hostname&#39; format, which `parse_url` treats as a path, not host.
        if ( ! isset($parts[&#39;host&#39;]) && isset($parts[&#39;path&#39;])) {
            $parts[&#39;host&#39;] = $parts[&#39;path&#39;];
            unset($parts[&#39;path&#39;]);
        }
        // Extract the port number as an integer
        $port = isset($parts[&#39;port&#39;]) ? intval($parts[&#39;port&#39;]) : self::DEFAULT_PORT;
        // Get the database from the &#39;path&#39; part of the URI
        $database = false;
        if (isset($parts[&#39;path&#39;])) {
            // Strip non-digit chars from path
            $database = intval(preg_replace(&#39;/[^0-9]/&#39;, &#39;&#39;, $parts[&#39;path&#39;]));
        }
        // Extract any &#39;user&#39; and &#39;pass&#39; values
        $user = isset($parts[&#39;user&#39;]) ? $parts[&#39;user&#39;] : false;
        $pass = isset($parts[&#39;pass&#39;]) ? $parts[&#39;pass&#39;] : false;
        // Convert the query string into an associative array
        $options = array();
        if (isset($parts[&#39;query&#39;])) {
            // Parse the query string into an array
            parse_str($parts[&#39;query&#39;], $options);
        }
        return array(
            $parts[&#39;host&#39;],
            $port,
            $database,
            $user,
            $pass,
            $options,
        );
    }

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

How to use array_merge() function in php to merge two arrays

PHP realizes batch generation of logos of various sizes Method

PHP method of using pcntl function to operate multiple processes

The above is the detailed content of 2 ways to parse URLs in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment