如何創(chuàng)建自己的程序(JavaScript、ajax、PHP)
深圳網(wǎng)站建設(shè)創(chuàng)建網(wǎng)站時(shí),一個(gè)主要目標(biāo)是吸引訪問者。交通產(chǎn)生是為了金錢目的,炫耀你的工作,或只是表達(dá)你的想法。有很多方法可以為你的網(wǎng)站創(chuàng)建流量。搜索引擎,社會(huì)化書簽,口碑只是幾個(gè)例子。但是你怎么知道這個(gè)交通是不是真的呢?你怎么知道你的客人是否會(huì)再次回來?
這些問題提出了網(wǎng)絡(luò)統(tǒng)計(jì)的概念。通常情況下,網(wǎng)站管理員使用某些程序,如谷歌Analytics或軟件,來完成他們的工作。這些程序獲取關(guān)于站點(diǎn)訪問者的各種信息。他們發(fā)現(xiàn)頁(yè)面視圖,訪問,獨(dú)特的訪問者,瀏覽器,IP地址,等等。但這究竟是如何實(shí)現(xiàn)的呢?請(qǐng)跟隨本教程如何創(chuàng)建你自己的網(wǎng)站統(tǒng)計(jì)程序使用PHP,JavaScript,Ajax,和SQLite。
首先,讓我們從一些簡(jiǎn)單的HTML標(biāo)記開始,它將充當(dāng)我們所跟蹤的頁(yè)面:
<!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 #完整的元素將被填充動(dòng)態(tài)JavaScript一旦頁(yè)面視圖已成功通過我們的網(wǎng)站統(tǒng)計(jì)跟蹤。為了啟動(dòng)跟蹤,我們可以使用jQuery和Ajax請(qǐng)求:
<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>
一步一步地考慮上面的代碼:
當(dāng)DOM準(zhǔn)備好了,我們首先把我們的數(shù)據(jù)、文本。本文在查詢字符串的格式,將數(shù)據(jù)發(fā)送到process.php,將跟蹤此頁(yè)面視圖。
然后我們創(chuàng)建一個(gè)Ajax請(qǐng)求,它使用POST方法發(fā)送表單數(shù)據(jù)。
我們的表格數(shù)據(jù)(數(shù)據(jù)、文本)然后送到process.php在我們服務(wù)器的根。
一旦這個(gè)請(qǐng)求完成,H2 #完整的元素是充滿成功的通知
我們下一步的工作是寫process.php。它的主要目標(biāo)是獲取有關(guān)Web統(tǒng)計(jì)信息的信息,并將其存儲(chǔ)在數(shù)據(jù)庫(kù)中。由于我們的數(shù)據(jù)庫(kù)尚未作出,我們必須創(chuàng)建一個(gè)簡(jiǎn)單的文件,安裝,這將為我們做這件事:
<?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!';
?>
這段代碼大部分是直截了當(dāng)?shù)?。它在服?wù)器的根目錄中打開一個(gè)數(shù)據(jù)庫(kù),并為它創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)。在sqlcreatetable美元的字符串是一個(gè)SQLite命令,使我們的統(tǒng)計(jì)表。該表包含四列:頁(yè)面、IP地址、意見和推薦:
頁(yè)面是一個(gè)字符串,其中包含被視為相對(duì)鏈接的頁(yè)面(即索引PHP)。
IP地址也是一個(gè)字符串,其中包含訪問此頁(yè)的IP地址列表。它是在numvisits1格式(IP地址1)numvisits2(IP演說2)numvisits3(IP address3)等。例如,如果我們從74.35.286.15來訪10人次和5 86.31.23.78(假想的IP地址),這個(gè)字符串將“10(74.25.286.15)5(86.31.23.78)”。
視圖是一個(gè)包含頁(yè)面被瀏覽次數(shù)的整數(shù)。
引用在同一格式的字符串作為IP地址。它包含所有引用到這個(gè)網(wǎng)頁(yè)有多少下線了。
現(xiàn)在到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 );
這第一段代碼連接到我們的統(tǒng)計(jì)數(shù)據(jù)庫(kù),并獲取當(dāng)前訪問所需的信息。它還查詢數(shù)據(jù)庫(kù)并獲取以前存儲(chǔ)的任何信息。我們使用此信息創(chuàng)建更新表。
下一個(gè)工作是查找舊信息:
# 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;
}
上面的代碼查找表中的所有以前的信息。這是至關(guān)重要的,我們需要更新視圖的數(shù)量(增加了一個(gè)),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]++;
上面的兩個(gè)循環(huán)非常相似。他們從數(shù)據(jù)庫(kù)中獲取信息并用正則表達(dá)式解析它。一旦解析了這個(gè)信息,它就存儲(chǔ)在一個(gè)數(shù)組中。然后使用當(dāng)前訪問的信息更新每個(gè)數(shù)組。然后,可以使用此信息創(chuàng)建最終字符串:
# 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 );
最后的字符串現(xiàn)在創(chuàng)建。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。作為一個(gè)回顧,發(fā)現(xiàn)訪客的IP地址和引用,使用的值來創(chuàng)建兩個(gè)字符串,增加一個(gè)頁(yè)面瀏覽數(shù),和地方的所有這些值到數(shù)據(jù)庫(kù)。
現(xiàn)在只剩下一個(gè)任務(wù)了。我們必須顯示網(wǎng)絡(luò)統(tǒng)計(jì)信息。讓我們把以下文件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非常相似。它解析頁(yè)面視圖,IP地址,并從數(shù)據(jù)庫(kù)引用。然后,它繼續(xù)以無序列表格式輸出它們。