• <strike id="mem0a"><s id="mem0a"></s></strike>
    
    
  • <kbd id="mem0a"></kbd>
    <ul id="mem0a"></ul>
     
    深圳網站建設設計

    將想法與焦點和您一起共享

    深圳網站建設設計 深圳網站優化排名 深圳網站設計制作欣賞

    如何創建自己的程序(JavaScript、ajax、PHP)

    2017-07-26  閱讀: 深圳網站建設設計

    如何創建自己的程序(JavaScript、ajax、PHP)
    深圳網站建設創建網站時,一個主要目標是吸引訪問者。交通產生是為了金錢目的,炫耀你的工作,或只是表達你的想法。有很多方法可以為你的網站創建流量。搜索引擎,社會化書簽,口碑只是幾個例子。但是你怎么知道這個交通是不是真的呢?你怎么知道你的客人是否會再次回來?

    這些問題提出了網絡統計的概念。通常情況下,網站管理員使用某些程序,如谷歌Analytics或軟件,來完成他們的工作。這些程序獲取關于站點訪問者的各種信息。他們發現頁面視圖,訪問,獨特的訪問者,瀏覽器,IP地址,等等。但這究竟是如何實現的呢?請跟隨本教程如何創建你自己的網站統計程序使用PHP,JavaScript,Ajax,和SQLite。

    首先,讓我們從一些簡單的HTML標記開始,它將充當我們所跟蹤的頁面:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Web Statistics</title>
    </head>
    <body>

    <h2 id="complete"></h2>

    </body>
    </html>

    H2 #完整的元素將被填充動態JavaScript一旦頁面視圖已成功通過我們的網站統計跟蹤。為了啟動跟蹤,我們可以使用jQuery和Ajax請求:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type='text/javascript'>
    $(function() {
        // Set the data text
        var dataText = 'page=<?php echo $_SERVER['REQUEST_URI']; ?>&referrer=<?php echo $_SERVER['HTTP_REFERER']; ?>';

        // Create the AJAX request
        $.ajax({
            type: "POST",                    // Using the POST method
            url: "/process.php",             // The file to call
            data: dataText,                  // Our data to pass
            success: function() {            // What to do on success
                $('#complete').html( 'Your page view has been added to the statistics!' );
            }
        });
    });
    </script>

    一步一步地考慮上面的代碼:

    當DOM準備好了,我們首先把我們的數據、文本。本文在查詢字符串的格式,將數據發送到process.php,將跟蹤此頁面視圖。

    然后我們創建一個Ajax請求,它使用POST方法發送表單數據。

    如何創建自己的程序(JavaScript、ajax、PHP)

    我們的表格數據(數據、文本)然后送到process.php在我們服務器的根。

    一旦這個請求完成,H2 #完整的元素是充滿成功的通知

    我們下一步的工作是寫process.php。它的主要目標是獲取有關Web統計信息的信息,并將其存儲在數據庫中。由于我們的數據庫尚未作出,我們必須創建一個簡單的文件,安裝,這將為我們做這件事:

    <?php    
        # Open the database
        $handle = sqlite_open( $_SERVER['DOCUMENT_ROOT'].'stats.db', 0666, $sqliteError ) or die(  $sqliteError  );

        # Set the command to create a table
        $sqlCreateTable = "CREATE TABLE stats(page text UNIQUE, ip text, views UNSIGNED int DEFAULT 0, referrer text DEFAULT '')";

        # Execute it
        sqlite_exec( $handle, $sqlCreateTable );
        
        # Print that we are done
        echo 'Finished!';
    ?>

    這段代碼大部分是直截了當的。它在服務器的根目錄中打開一個數據庫,并為它創建一個數據庫。在sqlcreatetable美元的字符串是一個SQLite命令,使我們的統計表。該表包含四列:頁面、IP地址、意見和推薦:

    頁面是一個字符串,其中包含被視為相對鏈接的頁面(即索引PHP)。

    IP地址也是一個字符串,其中包含訪問此頁的IP地址列表。它是在numvisits1格式(IP地址1)numvisits2(IP演說2)numvisits3(IP address3)等。例如,如果我們從74.35.286.15來訪10人次和5 86.31.23.78(假想的IP地址),這個字符串將“10(74.25.286.15)5(86.31.23.78)”。

    視圖是一個包含頁面被瀏覽次數的整數。

    引用在同一格式的字符串作為IP地址。它包含所有引用到這個網頁有多少下線了。

    現在到process.php:

    # Connect to the database
    $handle = sqlite_open( $_SERVER['DOCUMENT_ROOT'].'/stats.db', 0666, $sqliteError ) or die( $sqliteError );

    # Use the same-origin policy to prevent cross-site scripting (XSS) attacks
    # Remember to replace http://yourdomain.com/ with your actual domain
    if( strpos( $_SERVER['HTTP_REFERER'], 'http://yourdomain.com/' ) !== 0 ) {
         die( "Do not call this script manually or from an external source." );
    }

    # Obtain the necessary information, strip HTML tags, and escape the string for backup proetection
    $page = sqlite_escape_string( strip_tags( $_POST['page'] ) );
    $referrer = sqlite_escape_string( strip_tags( $_POST['referrer'] ) );
    $ip = sqlite_escape_string( strip_tags( $_SERVER['REMOTE_ADDR'] ) );


    # Query the database so we can update old information
    $sqlGet = 'SELECT * FROM stats WHERE page = ''.$page.''';
    $result = sqlite_query( $handle, $sqlGet );

    這第一段代碼連接到我們的統計數據庫,并獲取當前訪問所需的信息。它還查詢數據庫并獲取以前存儲的任何信息。我們使用此信息創建更新表。

    下一個工作是查找舊信息:
    # Set up a few variables to hold old information
    $views = 0;
    $ips = '';
    $referrers = '';
        
    # Check if old information exists
    if( $result && ( $info = sqlite_fetch_array( $result ) ) ) {
        # Get this information
        $views = $info['views'];
        $ips = $info['ip'].' ';
        if( $info['referrer'] )
            $referrers = $info['referrer'].' ';

        # Set a flag to state that old information was found
        $flag = true;
    }


    上面的代碼查找表中的所有以前的信息。這是至關重要的,我們需要更新視圖的數量(增加了一個),IP地址,和引薦。
    # Create arrays for all referrers and ip addresses
    $ref_num = array();
    $ip_num = array();

    # Find each referrer
    $values = split( ' ', $referrers );

    # Set a regular expression string to parse the referrer
    $regex = '%(d+)((.*?))%';

    # Loop through each referrer
    foreach( $values as $value ) {
        # Find the number of referrals and the URL of the referrer
        preg_match( $regex, $value, $matches );
            
        # If the two exist
        if( $matches[1] && $matches[2] )
            # Set the corresponding value in the array ( referrer link -> number of referrals )
            $ref_num[$matches[2]] = intval( $matches[1] );
    }
        
    # If there is a referrer on this visit
    if( $referrer )
        # Add it to the array
        $ref_num[$referrer]++;
        
    # Get the IPs
    $values = split( ' ', $ips );

    # Repeat the same process as above
    foreach( $values as $value ) {
        # Find the information
        preg_match( $regex, $value, $matches );
            
        # Make sure it exists
        if( $matches[1] && $matches[2] )
            # Add it to the array
            $ip_num[$matches[2]] = intval( $matches[1] );
    }

    # Update the array with the current IP.
    $ip_num[$ip]++;

    上面的兩個循環非常相似。他們從數據庫中獲取信息并用正則表達式解析它。一旦解析了這個信息,它就存儲在一個數組中。然后使用當前訪問的信息更新每個數組。然后,可以使用此信息創建最終字符串:
    # Reset the $ips string
    $ips = '';

    # Loop through all the information
    foreach( $ip_num as $key => $val ) {
        # Append it to the string (separated by a space)
        $ips .= $val.'('.$key.') ';
    }

    # Trim the String
    $ips = trim( $ips );

    # Reset the $referrers string
    $referrers = '';

    # Loop through all the information
    foreach( $ref_num as $key => $val ) {
        # Append it
        $referrers .= $val.'('.$key.') ';
    }

    # Trim the string
    $referrers = trim( $referrers );

    最后的字符串現在創建。IPS和引薦的形式是:“numvisits1(IP / referrer1)numvisits2(IP / referrer2)等。例如,以下是引用字符串:

    5(https://www.noupe.com) 10(http://css-tricks.com)

    # Update the number of views
    $views++;
        
    # If we did obtain information from the database
    # (the database already contains some information about this page)
    if( $flag )
        # Update it
        $sqlCmd = 'UPDATE stats SET ip=''.$ips.'', views=''.$views.'', referrer=''.$referrers.'' WHERE page=''.$page.''';

    # Otherwise
    else
        # Insert a new value into it
        $sqlCmd = 'INSERT INTO stats(page, ip, views, referrer) VALUES (''.$page.'', ''.$ips.'',''.$views.'',''.$referrers.'')';
            
    # Execute the commands
    sqlite_exec( $handle, $sqlCmd );

    這就是它的process.php。作為一個回顧,發現訪客的IP地址和引用,使用的值來創建兩個字符串,增加一個頁面瀏覽數,和地方的所有這些值到數據庫。

    如何創建自己的程序(JavaScript、ajax、PHP)

    現在只剩下一個任務了。我們必須顯示網絡統計信息。讓我們把以下文件display.php:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Web Statistics Display</title>
    </head>
    <body>

    <?php
        # Open up the database
        $handle = sqlite_open( $_SERVER['DOCUMENT_ROOT'].'/stats.db', 0666, $sqliteError ) or die( $sqliteError );
        
        # Get all the statistics
        $sqlGet = 'SELECT * FROM stats';
        $result = sqlite_query( $handle, $sqlGet );
        
        # Create an unordered list
        echo "<ul>n";
        
        # If there are results
        if( $result ) {
            $page_views = 0;
            $unique_visitors = 0;
            
            # Fetch them
            while( ($info = sqlite_fetch_array( $result ) ) ) {
                # Get the page, views, IPs, and referrers
                $page = $info['page'];
                $views = $info['views'];
                $ips = $info['ip'];
                $referrers = $info['referrer'];
                
                # Print out a list element with the $page/$views information
                if( $views == 1 )
                    echo "t<li>ntt<p>$page was viewed $views time:</p>n";
                else
                    echo "t<li>ntt<p>$page was viewed $views times:</p>n";
                
                # Update the number of page views
                $page_views += $views;
                
                # Parse the data of IPs and Referrers using process.php's code
                preg_match_all( '%(d+)((.*?))%', $ips, $matches );
                
                # Find the size of the data
                $size = count( $matches[1] );
                
                # Create a sub list
                echo "tt<ul>n";
                
                # Loop through all the IPs
                for( $i = 0; $i < $size; $i++ ) {
                    # Find the number of visits
                    $num = $matches[1][$i];

                    # Find the IP address
                    $ip = $matches[2][$i];
                    
                    # Print the info in a list element
                    if( $num == 1 )
                        echo "ttt<li>$num time by $ip</li>n";
                    else
                        echo "ttt<li>$num times by $ip</li>n";
                    
                    # Update the number of unique visitors
                    $unique_visitors++;
                }
                
                # Repeat the whole process for referrers
                preg_match_all( '%(d+)((.*?))%', $referrers, $matches );
                $size = count( $matches[1] );
                
                # Loop through each one
                for( $i = 0; $i < $size; $i++ ) {
                    $num = $matches[1][$i];
                    $referrer = $matches[2][$i];
                    
                    # Print out the info
                    if( $num == 1 )
                        echo "ttt<li>$num referral by $referrer</li>n";
                    else
                        echo "ttt<li>$num referrals by $referrer</li>n";
                }
                
                # End the sub-list
                echo "tt</ul>n";
                
                # End the list element
                echo "t</li>n";
            }
            
            echo "t<li>Total unique visitors: $unique_visitors</li>n";
            echo "t<li>Total page views: $page_views</li>n";
        }
        
        # End the unordered list
        echo "</ul>n";
        
        # Close the database
        sqlite_close($handle);
    ?>

    </body>
    </html>

    它似乎令人生畏,但它是process.php非常相似。它解析頁面視圖,IP地址,并從數據庫引用。然后,它繼續以無序列表格式輸出它們。

    將文章分享到..