如何创建自己的程序(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方法发送表单数据。
我们的表格数据(数据、文本)然后送到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地址和引用,使用的值来创建两个字符串,增加一个页面浏览数,和地方的所有这些值到数据库。
现在只剩下一个任务了。我们必须显示网络统计信息。让我们把以下文件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地址,并从数据库引用。然后,它继续以无序列表格式输出它们。