- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个 friend 系统,当用户访问另一个用户的个人资料时,他们会看到一个添加 friend 选项,当他们访问自己的个人资料时,他们可以看到其他东西而不是添加 friend 选项,如 TOTAL FRIENDS(或类似选项),当 guest 访问(未登录)时,他们也会看到不同的页面。总而言之,我需要在一个页面上显示三个 View :
user != user_id
user == user_id
就我现在而言,我设置脚本的方式出了点问题。 session 似乎无法在适当的实例下工作。
header.php:
<?php
include ( "./inc/connect.inc.php" );
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION['user_login'];
}
else {
$user = "";
}
?>
配置文件.php:
<?php include ( "./inc/header.inc.php" );
if (isset($_GET['u'])) {
$username = mysql_real_escape_string($_GET['u']);
if (ctype_alnum($username)) {
//check user exists
$check = mysql_query("SELECT username, first_name FROM users WHERE username='$username'");
if (mysql_num_rows($check)===1) {
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else {
echo "<meta http-equiv=\"refresh\" content=\"0; url=http://localhost/tutorials/index.php\">";
exit();
}
}
}
$optionbox = "";
if (isset($_SESSION['user_login']) != $user){
$optionbox = '<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;">
<a href="#">Add friend</a>
</div>';
}
else if (isset($_SESSION['user_login']) == $user){
$optionbox = '<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;">
<a href="#">friend list</a>
</div>';
}
else {
$optionbox = '<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;">
</div';
}
?>
还尝试使用 ['u']
而不是 user_login
,前两种情况都在选项框中显示添加好友或好友列表。
最佳答案
有几件事可以帮助您。为了清楚起见,我做了注释:
<?php
// Add connection here...(should be a PDO or mysqli_)
session_start();
// Add a simple true/false function to test for logged in
// Would be better included on this page rather than written (like connection)
function is_loggedin()
{
return (!empty($_SESSION['user_login']));
}
// Make a function to test if the logged-in user is currently viewing own profile
// Would be better included on this page rather than written (like connection)
function is_profile($user = false)
{
if(!$user)
return false;
return (is_loggedin() && ($_SESSION['user_login'] == $user));
}
// Presumably you would have profile.php?u=23432 or similar
// If no user requested just assign false
$user = (!empty($_GET['u']) && ctype_alnum($_GET['u']))? $_GET['u'] : false;
// If the user is valid (not empty)
// Would be better included on this page if condition is met otherwise
// It just kind of loads extra lines for nothing
if($user != false) {
// You should not be using mysql_ anymore, PDO or mysqli_ with prepared/bound statements
$username = mysql_real_escape_string($user);
//check user exists
$check = mysql_query("SELECT username, first_name FROM users WHERE username='$username'");
if (mysql_num_rows($check) === 1) {
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else {
echo "<meta http-equiv=\"refresh\" content=\"0; url=http://localhost/tutorials/index.php\">";
exit;
}
}
// Just do one wrapper
$optionbox[] = '<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;">';
// Check if a user is logged in
if(is_loggedin())
// If the logged in user matches the $_GET user
$optionbox[] = (!is_profile($user))? '<a href="#">Add friend</a>' : '<a href="#">friend list</a>';
// If user is not logged in
else
$optionbox[] = '<h3>You must be logged in to view stuff and things</h3>';
// Finish wrapper
$optionbox[] = '</div>';
// Write to page
echo implode(PHP_EOL,$optionbox);
?>
编辑:
自从最初发布这个答案以来,我有几个赞成票,我不想引用诸如在此处添加连接...(应该是 PDO 或 mysqli_)之类的东西 没有实际显示,所以这里用适当的连接等进行了一些重写。 function.PDOConnect.php
是填充数据库凭证的地方:
/classes/class.DBDriver.php
<?php
// Have a general driver interface incase you need different database
// connection interfaces (MSSQL, etc)
interface DBDriver
{
public static function connect($user,$pass,$host,$dbname);
}
/classes/class.Database.php
<?php
// Create MySQL PDO Connection based on the DBDriver preferences
class Database implements DBDriver
{
// This will store our connection for reuse
private static $singleton;
// This will store the connection options
protected static $dbOpts;
// This is the actual connecting to database
public static function connect($user,$pass,$host,$dbname)
{
if(isset(self::$singleton))
return self::$singleton;
if(!isset(self::$dbOpts))
self::SetDatabaseAttr();
try {
self::$singleton = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass, self::$dbOpts);
self::$singleton->exec('SET NAMES "utf8"');
}
catch(PDOException $e){
echo "unable to connect to server";
exit;
}
return self::$singleton;
}
// This sets the options for your database.
public static function SetDatabaseAttr($value = false,$refresh = false)
{
if(!is_array($value) || empty($value)) {
self::$dbOpts[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$dbOpts[PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;
self::$dbOpts[PDO::ATTR_EMULATE_PREPARES] = false;
}
else {
if(empty(self::$dbOpts) || $refresh)
self::$dbOpts = array();
foreach($value as $DBKey => $DBValue)
self::$dbOpts[$DBKey] = $DBValue;
}
return self::$dbOpts;
}
}
/classes/class.QueryEngine.php
<?php
// This class can be expanded out to do a lot more than just fetch from the database
class QueryEngine
{
protected $query;
private static $singleton;
// Create and Return instance of itself
public function __construct()
{
if(!empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
// Basic query method
public function query($sql = false, $bind = false)
{
AutoloadFunction("PDOConnect");
$con = PDOConnect();
$this->query = $con->prepare($sql);
if(!empty($bind)) {
foreach($bind as $key => $val) {
$bindVals[":{$key}"] = $val;
}
$this->query->execute($bindVals);
}
else
$this->query->execute();
return $this;
}
// This function is what returns the array in conjunction with
// the query method
public function Fetch()
{
if($this->query) {
while($row = $this->query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
}
return (!empty($result))? $result : 0;
}
}
/functions/function.AutoLoadClasses.php
<?php
// This function is what is used to autoload classes on the fly
// There is no need to include class files, so long as they are in the
// /classes/ folder
function AutoLoadClasses($className) {
if(class_exists($className)) {
return;
}
if(is_file(CLASSES_DIR."/class.".$className.'.php')) {
include_once(CLASSES_DIR."/class.".$className.'.php');
}
}
/functions/function.AutoloadFunction.php
<?php
// This will attempt to load the required file to run a specified function
// Similar to the autoloader for the classes, only this is required to be
// manually called like: AutoloadFunction("myfunction"); before function use
function AutoloadFunction($function = false,$loaddir = false)
{
if($function == false)
return false;
if(strpos($function,","))
$functions = explode(",",$function);
$function_dir = ($loaddir != false && !is_array($loaddir))? $loaddir.'/function.': FUNCTIONS_DIR.'/function.';
if(!isset($functions)) {
$functions[] = $function;
}
for($i = 0; $i < count($functions); $i++) {
// Function name
$addfunction = $functions[$i];
// See if function exists
if(!function_exists($addfunction)) {
$dir = $function_dir.$addfunction.'.php';
if(is_file($dir)) {
include_once($dir);
}
}
}
}
/functions/function.PDOConnect.php
<?php
// Just make a quick PDO function to return your PDO Connection
// populate the arguements with your database credentials
function PDOConnect($user = "username",$pass = "password",$host = "hostname",$data = "databasename")
{
return Database::connect($user,$pass,$host,$data);
}
/functions/function.query_fetch.php
<?php
// Here is a quick array fetching function using the query engine class
function query_fetch($sql = false,$bind = false)
{
$qEngine = new QueryEngine();
return $qEngine ->query($sql,$bind)
->Fetch();
}
/functions/function.is_loggedin.php
<?php
// Add a simple true/false function to test for logged in
function is_loggedin()
{
return (!empty($_SESSION['username']));
}
/functions/function.is_profile.php
<?php
// Make a function to test if the logged-in user is currently viewing own profile
function is_profile($user = false)
{
if(!$user)
return false;
AutoloadFunction("is_loggedin");
return (is_loggedin() && ($_SESSION['username'] == $user));
}
/functions/function.get_profile.php
<?php
// This will fetch the user based on a get variable
function get_profile($username = false)
{
// Presumably you would have profile.php?u=23432 or similar
// If no user requested just assign false
$user = (!empty($_GET['u']) && ctype_alnum($_GET['u']))? $_GET['u'] : false;
$array['username'] = false;
$array['first_name'] = false;
// If the user is valid (not empty)
// Would be better included on this page if condition is met otherwise
// It just kind of loads extra lines for nothing
if($user != false) {
AutoloadFunction("query_fetch");
//check user exists
$get = query_fetch("SELECT `username`, `first_name`,`ID` FROM `users` WHERE `username` = :0",array($user));
if ($get != 0) {
$array['username'] = $get[0]['username'];
$array['ID'] = $get[0]['ID'];
$array['first_name'] = $get[0]['first_name'];
return ($username)? $array['username'] : $array;
}
else {
header("location: http://localhost/tutorials/index.php");
exit;
}
}
return $array;
}
config.php
<?php
// Define some basic locational constants
define("ROOT_DIR",__DIR__);
define("CLASSES_DIR",ROOT_DIR."/classes");
define("FUNCTIONS_DIR",ROOT_DIR."/functions");
// Load up the functions autoloader
include_once(FUNCTIONS_DIR."/function.AutoloadFunction.php");
// Load up the function for class autoloading
AutoloadFunction("AutoLoadClasses");
// Apply the autoloader for classes
spl_autoload_register('AutoLoadClasses');
profile.php
<?php
session_start();
// Load all the settings to make things work.
include(__DIR__."/config.php");
?>
<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;">
<?php
// Using the "AutoloadFunction" should save execution time because
// it will only load functions it needs instead of loading all the functions
// it could "potentially" need.
AutoloadFunction("is_loggedin");
// Check if a user is logged in
if(is_loggedin()) {
AutoloadFunction("get_profile,is_profile");
// Fetch the profile of current user query
$user = get_profile();
// If the logged in user matches the $_GET user
echo (!is_profile($user['username']))? '<a href="?action=add&u='.$user['ID'].'">Add '.ucwords($user['first_name']).'</a>' : '<a href="#">friend list</a>';
}
// If user is not logged in
else {
?>
<h3>You must be logged in to view stuff and things</h3>
<?php }
?>
</div>
关于php - 如何在配置文件页面上显示不同的 session 状态(访客 View 与用户配置文件 View ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32450076/
我正在通读 Windows Phone 7.5 Unleashed,有很多代码看起来像这样(在页面的代码隐藏中): bool loaded; protected override void OnNav
在cgi服务器中,我这样返回 print ('Status: 201 Created') print ('Content-Type: text/html') print ('Location: htt
我正在查看 esh(easy shell)的实现,无法理解在这种情况下什么是 22 和 9 信号。理想情况下,有一个更具描述性的常量,但我找不到列表。 最佳答案 信号列表及其编号(包括您看到的这两个)
我的Oozie Hive Action 永远处于运行模式。 oozie.log文件中没有显示错误。
我正在编写一个使用 RFCOMM 通过蓝牙连接到设备的 Android 应用程序。我使用 BluetoothChat 示例作为建立连接的基础,大部分时间一切正常。 但是,有时由于出现套接字已打开的消息
我有一个云调度程序作业,它应该每小时访问我的 API 以更新一些价格。这些作业大约需要 80 秒才能运行。 这是它的作用: POST https://www.example.com/api/jobs/
我正在 Tomcat 上访问一个简单的 JSP 页面: 但是当我使用 curl 测试此页面时,我得到了 200 响应代码而不是预期的 202: $ curl -i "http://localhos
有时 JAR-RS 客户端会发送错误的语法请求正文。服务器应响应 HTTP status 400 (Bad Request) , 但它以 HTTP status 500 (Internal Serve
我正在尝试通过 response.send() 发送一个整数,但我不断收到此错误 express deprecated res.send(status): Use res.sendStatus(sta
我已经用 Excel 和 Java 做过很多次了……这次我需要用 Stata 来做,因为保存变量更方便'labels .如何将 dataset_1 重组为下面的 dataset_2? 我需要转换以下
我正在创建一个应用程序,其中的对象具有状态查找功能。为了提供一些上下文,让我们使用以下示例。 帮助台应用程序,其中创建作业并通过以下工作流程移动: 新 - 工作已创建但未分配 进行中 - 分配给工作人
我想在 Keras 中运行 LSTM 并获得输出和状态。在 TF 中有这样的事情 with tf.variable_scope("RNN"): for time_step in range
有谁知道 Scala-GWT 的当前状态 项目? 那里的主要作者 Grzegorz Kossakowski 似乎退出了这个项目,在 Spring 中从事 scalac 的工作。 但是,在 interv
我正在尝试编写一个 super 简单的 applescript 来启动 OneDrive App , 或确保打开,当机器的电源设置为插入时,将退出,或确保关闭,当电源设置为电池时。 我无法找到如何访问
目前我正在做这样的事情 link.on('click', function () { if (link.attr('href') !== $route.current.originalPath
是否可以仅通过查看用户代理来检测浏览器上是否启用/禁用 Javascript。 如果是,我应该寻找什么。如果否,检测用户浏览器是否启用/禁用 JavaScript 的最佳方法是什么 最佳答案 不,没有
Spring 和 OSGi 目前的开发状况如何? 最近好像有点安静了。 文档的最新版本 ( http://docs.spring.io/osgi/ ) 来自 2009 年。 我看到一些声明 Sprin
我正在从主函数为此类创建一个线程,但即使使用 Thread.currentThread().interrupt() 中断它,输出仍然包含“Still Here”行。 public class Writ
为了满足并发要求,我想知道如何在 Godog 中的多个步骤之间传递参数或状态。 func FeatureContext(s *godog.Suite) { // This step is ca
我有一个UIButton子类,它不使用UIImage背景,仅使用背景色。我注意到的一件事是,当您设置按钮的背景图像时,有一个默认的突出显示状态,当按下按钮时,该按钮会稍微变暗。 这是我当前的代码。
我是一名优秀的程序员,十分优秀!