search
HomeBackend DevelopmentPHP TutorialShort URL exploration, URL exploration_PHP tutorial

Short URL exploration, URL exploration_PHP tutorial

Jul 13, 2016 am 10:04 AM
httpundercommonplaceintroductionExploreshortURL

Short URL exploration, URL exploration

Introduction

Short URLs are common, such as the following

 http://dwz.cn/CSW6Y => http://www.cnblogs.com/iforever/p/4313704.html,

 http://dwz.cn/CSWuP => http://www.cnblogs.com/iforever/p/4279006.html, etc.

When accessing these URLs, the front and back pairs point to the same page. I am just giving an example. These short URLs are often seen in weibo or similar social networks. Since the original link address is particularly long, this time the short URL is short. The URL will show its power and be short and easy to remember, but it also has its shortcomings. For example, short URLs may not directly see some information in the URL (some information can be seen in long URLs).

I have been exposed to this all day long, so that before I really understand its principle, it has imprinted "nothing" in my mind. This has missed some knowledge. This situation should be called in psychology. I'm thinking, does anyone know that this is the case?

Principle

First of all, I guess this is achieved through redirection. dwz.cn is a server used to receive some short URLs. These short URLs are processed by dwz.cn and have corresponding short URLs in dwz.cn. The record of the long URL, then obtain the long URL corresponding to the short URL from the database, and then redirect with 302. See if this is the case.

Visit http://dwz.cn/CSW6Y through the browser and analyze the request (use Chrome’s debugging tool here, or you can use tools such as wireshark), and you can get the following data:

Short URL exploration, URL exploration_PHP tutorialname: abit version: 1 handle: - rewrite: if (!-d && !-f && path ~ "/(.*)$") goto "do.php?url=$1&act=out"

Handle: The following are the rewrite rules. For the specific detailed rules of Sina Cloud, please see here http://sae.sina.com.cn/doc/php/runtime.html#php-app-config. It is very simple. The configurations of nginx and apache are also similar.

Another thing to note after the redirection is completed is that urlencode must be performed when passing parameters, and urldecode must be used before redirection. When url type parameters are passed without using urlencode, part of the information may be lost when obtained. Therefore, when passing parameters before generating a short link, the URL must be escaped, the special string must be encoded, and the short link must be processed when accessing. It is necessary to urldecode the encoded URL and restore it to a normal link. Otherwise, the link will not be regarded as a normal URL when the header jumps. After the jump, the URL will be appended to the host of the previous page, similar to http://abit.sinaapp.com/www.cnblogs.com, errors may occur, so please pay special attention here.

There will be a problem when sae redirects, double backslashes will be automatically filtered into one, for example from http://abit.sinaapp.com/ to http:/abit.sinaapp.com/, please note , there is a missing backslash here, you should pay special attention to this when processing, otherwise you may encounter unnecessary trouble.

Encoding

Main processing part

<?<span>php
</span><span>class</span><span> snapshotUrl{
    </span><span>//</span><span>进行编码的数据库,没6位二进制数对应一个字符,一共需要64位,因此选取
    //52+10+2个特殊字符</span>
    <span>private</span> <span>static</span> <span>$basedb</span> = <span>array</span><span>(
        </span>'(',')','a','b','c','d',
        'e','f','g','h','i','j',
        'k','l','m','n','o','p',
        'q','r','s','t','u','v',
        'w','x','y','z','A','B',
        'C','D','E','F','G','H',
        'I','J','K','L','M','N',
        'O','P','Q','R','S','T',
        'U','V','W','X','Y','Z',
        '0','1','2','3','4','5',
        '6','7','8','9',<span>
    );

    </span><span>private</span> <span>function</span> long2short(<span>$url</span><span>){
        </span><span>$hex</span> = <span>md5</span>(<span>$url</span><span>);
        </span><span>$out</span> = ''<span>;
        </span><span>$hex</span> = 0x7FFFFFFF & (1 * ('0x'.<span>substr</span>(<span>$hex</span>, 0, 8<span>)));
        </span><span>for</span>(<span>$i</span>=0; <span>$i</span><5; <span>$i</span>++<span>){
            </span><span>$index</span> = 0x3f & <span>$hex</span><span>;
            </span><span>$out</span> .= self::<span>$basedb</span>[<span>$index</span><span>];
            </span><span>$hex</span> = <span>$hex</span>>>6<span>;
        }
        </span><span>return</span> <span>$out</span><span>;
    }

    </span><span>public</span> <span>function</span> retJson(<span>$arr</span><span>){
        </span><span>return</span> json_encode(<span>$arr</span><span>);
    }

    </span><span>//</span><span>对url进行映射保存</span>
    <span>public</span> <span>function</span> dispose(<span>$url</span>, <span>$act</span><span>){
        </span><span>$mysql</span> = <span>new</span><span> SaeMysql();
        </span><span>switch</span> (<span>$act</span><span>) {
            </span><span>case</span> 'in':
                <span>$short</span> = <span>$this</span>->long2short(<span>$url</span><span>);
                </span><span>$url</span> = <span>addslashes</span>(<span>$url</span><span>);
                </span><span>$sql</span> = "insert into `tiny_url`(`short`,`long`) values ('{<span>$short</span>}','{<span>$url</span>}')"<span>;
                </span><span>$mysql</span>->runSql(<span>$sql</span><span>);
                </span><span>if</span>(<span>$mysql</span>->errno() != 0<span>){
                    </span><span>echo</span> "生成失败"<span>;
                }</span><span>else</span><span>{
                    </span><span>echo</span> "http://abit.sinaapp.com/{<span>$short</span>}"<span>;
                }
                </span><span>break</span><span>;
            </span><span>case</span> 'out':
                <span>if</span>(<span>strlen</span>(<span>$url</span>) > 5<span>)
                    </span><span>echo</span> <span>$this</span>->retJson(<span>array</span>("code"=>"-1","msg"=>"没有这条记录"<span>));
                </span><span>$sql</span> = "select * from `tiny_url` where `short`='{<span>$url</span>}' limit 1"<span>;
                </span><span>$data</span> = <span>$mysql</span>->getData(<span>$sql</span><span>);
                </span><span>if</span>(!<span>$data</span><span>) {
                    </span><span>echo</span> <span>$this</span>->retJson(<span>array</span>("code"=>"-1","msg"=>"没有这条记录"<span>));
                }</span><span>else</span><span>{
                    </span><span>$location</span> = <span>urldecode</span>(<span>$data</span>[0]['long'<span>]);
                    </span><span>header</span>("Location: {<span>$location</span>}"<span>);
                    </span><span>exit</span><span>();
                }
                </span><span>break</span><span>;
            
            </span><span>default</span>:
                <span>#</span><span> code...</span>
                <span>break</span><span>;
        }
    }    
}

</span><span>$url</span> = <span>isset</span>(<span>$_GET</span>['url']) ? <span>$_GET</span>['url'] : <span>null</span><span>;
</span><span>$act</span> = <span>isset</span>(<span>$_GET</span>['act']) ? <span>$_GET</span>['act'] : <span>null</span><span>;
</span><span>$snapshotUrl</span> = <span>new</span><span> snapshotUrl();
</span><span>if</span>(<span>$url</span> === <span>null</span> || <span>$act</span> === <span>null</span><span>)
    </span><span>echo</span> <span>$snapshotUrl</span>->retJson(<span>array</span>("code"=>"-1","msg"=>"参数错误"<span>));

</span><span>$snapshotUrl</span>->dispose(<span>$url</span>, <span>$act</span>);

Results

I made a small webpage that can be tested:

 http://abit.sinaapp.com/ If you are interested, you can try it

The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author’s consent. After reprinting the article, the author and the original text link must be given in an obvious position on the article page. Otherwise, we reserve the right to pursue legal liability.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/965023.htmlTechArticleShort URL Research, URL Research Introduction Short URLs are common, such as the following http://dwz.cn/CSW6Y =http://www.cnblogs.com/iforever/p/4313704.html, http://dwz.cn/CSWuP=http:/...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment