将书签应用程序与社交网站集成

发布于 2024-12-07 16:35:39 字数 7647 浏览 0 评论 0原文

我有一个功能完善的书签应用程序。到目前为止,它是非排他性的;当我按“保存”书签时,它会将 url 发送到数据库中的通用表。我需要弄清楚如何将其与在线社区集成,因此它是特定于用户的,并且每次用户“保存”故事时,它都会将网址发送到数据库中该用户的行并输出回来到该用户的个人资料。

代码如下。 这是一个演示: http://demo.tutorialzine.com /2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php

Bookmark.php

 <?php

 // Error reporting:
 error_reporting(E_ALL^E_NOTICE);

 require "connect.php";
 require "functions.php";

 // Setting the content-type header to javascript:
header('Content-type: application/javascript');

 // Validating the input data
if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();

// Sanitizing the variables
$_GET['url'] = sanitize($_GET['url']);
$_GET['title'] = sanitize($_GET['title']);

// Inserting, notice the use of the hash field and the md5 function:
mysql_query("   INSERT INTO bookmark_app (hash,url,title)
            VALUES (
                '".md5($_GET['url'])."',
                '".$_GET['url']."',
                '".$_GET['title']."'
            )");

$message = '';
if(mysql_affected_rows($link)!=1)
{
$message = 'You have already saved this Headline';
}
else
$message = 'The URL was shared!';


 ?>

 /* JavaScript Code */

  function displayMessage(str)
   {
// Using pure JavaScript to create and style a div element

var d = document.createElement('div');

with(d.style)
{
    // Applying styles:

    position='fixed';
    width = '350px';
    height = '20px';
    top = '50%';
    left = '50%';
    margin = '-30px 0 0 -195px';
    backgroundColor = '#f7f7f7';
    border = '1px solid #ccc';
    color = '#777';
    padding = '20px';
    fontSize = '18px';
    fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
    textAlign = 'center';
    zIndex = 100000;

    textShadow = '1px 1px 0 white';

    MozBorderRadius = "12px";
    webkitBorderRadius = "12px";
    borderRadius = "12px";

    MozBoxShadow = '0 0 6px #ccc';
    webkitBoxShadow = '0 0 6px #ccc';
    boxShadow = '0 0 6px #ccc';
 }

 d.setAttribute('onclick','document.body.removeChild(this)');

   // Adding the message passed to the function as text:
 d.appendChild(document.createTextNode(str));

   // Appending the div to document
 document.body.appendChild(d);

   // The message will auto-hide in 3 seconds:

 setTimeout(function(){
    try{
        document.body.removeChild(d);
    }   catch(error){}
 },3000);
     }

   <?php 

 // Adding a line that will call the JavaScript function:
 echo 'displayMessage("'.$message.'");';

 ?>

Connect.php

/* Database config */

$db_host        = 'xxxxx';
$db_user        = 'xxxxx';
$db_pass        = 'xxxxx';
$db_database    = 'xxxxx'; 

/* End config */


$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_set_charset('utf8');
mysql_select_db($db_database,$link);

?>

演示.php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

require "connect.php";
require "functions.php";

$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bookmarking App With PHP, JavaScript &amp; MySQL | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<h1>Bookmarking App...</h1>
<h2><a href="http://google.com">Return to the homepage &raquo;</a></h2>

<div id="main">

<div class="bookmarkHolder">

    <!--    The link contains javascript functionallity which is preserved
            when the user drops it to their bookmark/favorites bar  -->

      <a href="javascript:(function(){var jsScript=document.createElement('script');
   jsScript.setAttribute('type','text/javascript');
   jsScript.setAttribute('src', '<?php echo  $url?>/bookmark.php?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title));
  document.getElementsByTagName('head')[0].appendChild(jsScript);
  })();" class="bookmarkButton">Bookmark this!</a>

    <em>Drag this button to your bookmarks bar and click it when visiting a web site. The title and URL of the page will be saved below.</em>
   </div>

  <ul class="latestSharesUL">
    <?php

    $shares = mysql_query("SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6");

    while($row=mysql_fetch_assoc($shares))
    {
        // Shortening the title if it is too long:
        if(mb_strlen($row['title'],'utf-8')>80)
            $row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';

        // Outputting the list elements:
        echo '
        <li>
            <div class="title"><a href="'.$row['url'].'" class="bookmrk">'.$row['title'].'</a></div>
            <div class="dt">'.relativeTime($row['dt']).'</div>
        </li>';
    }

        ?>
    </ul>

 </div>

 </body>
 </html>

函数.php

 /* Helper functions */

 function validateURL($str)
 {
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]* [\w\-\@?^=%&amp;\/~\+#])?/i',$str);
 }

 function sanitize($str)
 {
if(ini_get('magic_quotes_gpc'))
    $str = stripslashes($str);

$str = strip_tags($str);
$str = trim($str);
$str = htmlspecialchars($str);
$str = mysql_real_escape_string($str);

return $str;
 }


 function relativeTime($dt,$precision=2)
 {
if(is_string($dt)) $dt = strtotime($dt);

$times=array(   365*24*60*60    => "year",
                30*24*60*60     => "month",
                7*24*60*60      => "week",
                24*60*60        => "day",
                60*60           => "hour",
                60              => "minute",
                1               => "second");

$passed=time()-$dt;

if($passed<5)
{
    $output='less than 5 seconds ago';
}
else
{
    $output=array();
    $exit=0;

    foreach($times as $period=>$name)
    {
        if($exit>=$precision || ($exit>0 && $period<60)) break;

        $result = floor($passed/$period);
        if($result>0)
        {
            $output[]=$result.' '.$name.($result==1?'':'s');
            $passed-=$result*$period;
            $exit++;
        }
        else if($exit>0) $exit++;
    }

    $output=implode(' and ',$output).' ago';
  }

  return $output;
  }

 // Defining fallback functions for mb_substr and 
 // mb_strlen if the mb extension is not installed:

 if(!function_exists('mb_substr'))
 {
function mb_substr($str,$start,$length,$encoding)
{
    return substr($str,$start,$length);
}
 }

 if(!function_exists('mb_strlen'))
 {
function mb_strlen($str,$encoding)
{
    return strlen($str);
}
 }
 ?>

表.sql

CREATE TABLE `bookmark_app` (
`id` int(10) unsigned NOT NULL auto_increment,
`hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`url` text collate utf8_unicode_ci NOT NULL,
`title` text collate utf8_unicode_ci NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY  (`id`),
UNIQUE KEY `hash` (`hash`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I have a perfectly functional bookmarking app. As of now, it's non-exclusive; when I press "save" bookmark it sends the url to a general table in the DB. I need to figure out how to integrate this with an online community, so its user specific and each time a user "saves" a story, it sends the url to that user's row in the DB and outputs back to that user's profile.

Code is below.
Here's a demo:
http://demo.tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php

Bookmark.php

 <?php

 // Error reporting:
 error_reporting(E_ALL^E_NOTICE);

 require "connect.php";
 require "functions.php";

 // Setting the content-type header to javascript:
header('Content-type: application/javascript');

 // Validating the input data
if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();

// Sanitizing the variables
$_GET['url'] = sanitize($_GET['url']);
$_GET['title'] = sanitize($_GET['title']);

// Inserting, notice the use of the hash field and the md5 function:
mysql_query("   INSERT INTO bookmark_app (hash,url,title)
            VALUES (
                '".md5($_GET['url'])."',
                '".$_GET['url']."',
                '".$_GET['title']."'
            )");

$message = '';
if(mysql_affected_rows($link)!=1)
{
$message = 'You have already saved this Headline';
}
else
$message = 'The URL was shared!';


 ?>

 /* JavaScript Code */

  function displayMessage(str)
   {
// Using pure JavaScript to create and style a div element

var d = document.createElement('div');

with(d.style)
{
    // Applying styles:

    position='fixed';
    width = '350px';
    height = '20px';
    top = '50%';
    left = '50%';
    margin = '-30px 0 0 -195px';
    backgroundColor = '#f7f7f7';
    border = '1px solid #ccc';
    color = '#777';
    padding = '20px';
    fontSize = '18px';
    fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
    textAlign = 'center';
    zIndex = 100000;

    textShadow = '1px 1px 0 white';

    MozBorderRadius = "12px";
    webkitBorderRadius = "12px";
    borderRadius = "12px";

    MozBoxShadow = '0 0 6px #ccc';
    webkitBoxShadow = '0 0 6px #ccc';
    boxShadow = '0 0 6px #ccc';
 }

 d.setAttribute('onclick','document.body.removeChild(this)');

   // Adding the message passed to the function as text:
 d.appendChild(document.createTextNode(str));

   // Appending the div to document
 document.body.appendChild(d);

   // The message will auto-hide in 3 seconds:

 setTimeout(function(){
    try{
        document.body.removeChild(d);
    }   catch(error){}
 },3000);
     }

   <?php 

 // Adding a line that will call the JavaScript function:
 echo 'displayMessage("'.$message.'");';

 ?>

Connect.php

/* Database config */

$db_host        = 'xxxxx';
$db_user        = 'xxxxx';
$db_pass        = 'xxxxx';
$db_database    = 'xxxxx'; 

/* End config */


$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_set_charset('utf8');
mysql_select_db($db_database,$link);

?>

Demo.php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

require "connect.php";
require "functions.php";

$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bookmarking App With PHP, JavaScript & MySQL | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<h1>Bookmarking App...</h1>
<h2><a href="http://google.com">Return to the homepage »</a></h2>

<div id="main">

<div class="bookmarkHolder">

    <!--    The link contains javascript functionallity which is preserved
            when the user drops it to their bookmark/favorites bar  -->

      <a href="javascript:(function(){var jsScript=document.createElement('script');
   jsScript.setAttribute('type','text/javascript');
   jsScript.setAttribute('src', '<?php echo  $url?>/bookmark.php?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title));
  document.getElementsByTagName('head')[0].appendChild(jsScript);
  })();" class="bookmarkButton">Bookmark this!</a>

    <em>Drag this button to your bookmarks bar and click it when visiting a web site. The title and URL of the page will be saved below.</em>
   </div>

  <ul class="latestSharesUL">
    <?php

    $shares = mysql_query("SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6");

    while($row=mysql_fetch_assoc($shares))
    {
        // Shortening the title if it is too long:
        if(mb_strlen($row['title'],'utf-8')>80)
            $row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';

        // Outputting the list elements:
        echo '
        <li>
            <div class="title"><a href="'.$row['url'].'" class="bookmrk">'.$row['title'].'</a></div>
            <div class="dt">'.relativeTime($row['dt']).'</div>
        </li>';
    }

        ?>
    </ul>

 </div>

 </body>
 </html>

Functions.php

 /* Helper functions */

 function validateURL($str)
 {
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]* [\w\-\@?^=%&\/~\+#])?/i',$str);
 }

 function sanitize($str)
 {
if(ini_get('magic_quotes_gpc'))
    $str = stripslashes($str);

$str = strip_tags($str);
$str = trim($str);
$str = htmlspecialchars($str);
$str = mysql_real_escape_string($str);

return $str;
 }


 function relativeTime($dt,$precision=2)
 {
if(is_string($dt)) $dt = strtotime($dt);

$times=array(   365*24*60*60    => "year",
                30*24*60*60     => "month",
                7*24*60*60      => "week",
                24*60*60        => "day",
                60*60           => "hour",
                60              => "minute",
                1               => "second");

$passed=time()-$dt;

if($passed<5)
{
    $output='less than 5 seconds ago';
}
else
{
    $output=array();
    $exit=0;

    foreach($times as $period=>$name)
    {
        if($exit>=$precision || ($exit>0 && $period<60)) break;

        $result = floor($passed/$period);
        if($result>0)
        {
            $output[]=$result.' '.$name.($result==1?'':'s');
            $passed-=$result*$period;
            $exit++;
        }
        else if($exit>0) $exit++;
    }

    $output=implode(' and ',$output).' ago';
  }

  return $output;
  }

 // Defining fallback functions for mb_substr and 
 // mb_strlen if the mb extension is not installed:

 if(!function_exists('mb_substr'))
 {
function mb_substr($str,$start,$length,$encoding)
{
    return substr($str,$start,$length);
}
 }

 if(!function_exists('mb_strlen'))
 {
function mb_strlen($str,$encoding)
{
    return strlen($str);
}
 }
 ?>

Table.sql

CREATE TABLE `bookmark_app` (
`id` int(10) unsigned NOT NULL auto_increment,
`hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`url` text collate utf8_unicode_ci NOT NULL,
`title` text collate utf8_unicode_ci NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY  (`id`),
UNIQUE KEY `hash` (`hash`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文