php - 页面请求过多

标签 php html mysql

页面chrome有问题,说有太多重定向,该页面终于做了我想要的事情(至少据我所知,功能正常,因为我用紧密连接测试了它,坚持在顶部页面,它显示用户 ID。登录此页面时会进行重定向,我不太确定如何解决此问题,在网上找到了很多不同的帖子,并且每个帖子都与下一个如此不同。

<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="stylesheet" type="text/css" href=".../../../../style.css">
    <title>Home</title>

    <!--[if IE]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
<?php include('../../main/main.php');?>
</head>
  <body>



<div class=containermain>
  <h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">

<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
    <option value="1">1 </option>
    <option value="2">2</option>
    <option value="3">3 </option>
    <option value="4">4</option>
    <option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>



  <h2>graphics card write up................</h2>
  <?php echo "Hello " . $_SESSION['user']; ?>
  <p>&nbsp;</p>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<div
  class="fb-like"
  data-share="true"
  data-width="450"
  data-show-faces="true">
</div>

<!---------------------------------------COMMENT BOX---------------------------------------------------->

<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....


</textarea>
<input type="submit" value="Submit">
</form>


<?php

if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
 $id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){


      header("Location: i5-6600k");

} else {
    echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);

}

}

    // close connection











$sql  = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"

    . "FROM `users`\n"

    . "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"

    . "where dCpuID = 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>"  . $row["timestamp"]. "</td>";
     }
     echo "</table>";
} else {
     echo "0 results";
}


?>  
</div>
<?php include('../../assets/footer.php');?>

<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
  </body>
</html>

最佳答案

我想我明白你在这里做什么,你缺少如何有效地处理一个 Action 。您通过检查某些持久存在的东西是否存在并对其采取行动来触发您的评论。如果它是一个 session 变量,它将持续存在,因此该操作是无限的,直到它停止持续存在。您需要在提交中采取行动。

我将有一个配置页面,您可以将其包含在所有包含可重用变量的页面中。它将存储在站点的根目录中。一般来说,您会遇到一些 HTML 错误和一些不安全的 SQL 注入(inject)问题。我已经为您的页面创建了一个更复杂的版本(没有下半部分,这需要大量工作并且也应该被包装),但它只是为了使 View 不那么复杂......如果这是有道理的。无论如何,如果您有问题请告诉我,我还没有对此进行测试。

/config.php

<?php
# Create some absolute defines for consistent includes
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('VENDOR',ROOT_DIR.DS.'vendor');
define('SITE_URL','http://www.example.com');

# Start session
session_start();
# Autoloads all the classes we intend to use
spl_autoload_register(function($class){
    $path = VENDOR.DS.trim(str_replace('\\',DS,$class),DS).'.php';
    if(is_file($path))
        require_once($path);
});

/vendor/App.php

<?php
# General/base class used for various time-saving actions
class App
    {
        # Store this object for re-use
        protected   static $singleton;
        # Store others (if using getHelper() method)
        protected   static $apps;
        # Create singleton
        public function __construct()
            {
                if(!(self::$singleton instanceof \App))
                    self::$singleton = $this;
                # Return back the same object
                return self::$singleton;
            }
        # Get either the full post or just one key/value
        public function getPost($key=false)
            {
                if(!empty($key))
                    return (isset($_POST[$key]))? $_POST[$key] : false;

                return $_POST;
            }
        # Get session or just one key/value pair
        public function getSession($key=false)
            {
                if(!empty($key))
                    return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
                return $_SESSION;
            }

        # Write and destroy session value
        public function writeError($key)
            {
                $error = $this->getSession($key);
                $this->destroy($key);
                return $error;
            }

        public function destroy($key = false)
            {
                if(!empty($key)) {
                    if(isset($_SESSION[$key]))
                        $_SESSION[$key] = NULL;

                    return;
                }

                session_destroy();
            }
        # Sets a session value
        public function setSession($key,$value)
            {
                $_SESSION[$key] = $value;
            }
        # Consistent way to write the site url (set in the config)
        public function siteUrl($path = false,$ssl=false)
            {
                return ($ssl)? str_replace('http://','https://',SITE_URL).$path : SITE_URL.$path;
            }
        # Creates an instance if this object
        public static function call()
            {
                return new \App();
            }
        # Saves and uses classes
        public function getHelper($class,$inject=NULL)
            {
                $setKey = str_replace('\\','',$class);

                if(isset(self::$apps[$setKey]))
                    return self::$apps[$setKey];

                self::$apps[$setKey] = new $class($inject);

                return self::$apps[$setKey];
            }
    }

/vendor/Router/Model.php

<?php
# Use for redirects, can be expanded out to do other router-type things
namespace Router;

class Model extends \App
    {
        public function addRedirect($path)
            {
                header('Location: '.$path);
                exit;
            }
    }

/vendor/View/Model.php

<?php
# This is a wrapper for the page
namespace View;

class Model extends \App
    {
        public function render($path)
            {
                if(!is_file($path))
                    return;
                # Create a buffer and render contents
                ob_start();
                include($path);
                $data = ob_get_contents();
                ob_end_clean();
                return $data;
            }
    }

/vendor/Commenter/Model.php

<?php
namespace Commenter;

class Observer extends \Router\Model
    {
        # Listen for action name, do action when required
        public function listen($conn)
            {
                if($this->getPost('action') != 'addcomment')
                    return false;

                if(!empty($this->getSession('login_id'))) {
                    $id = $this->getSession('login_id');
                    # You will want to bind parameters on this. This is an opening for SQL Injection (Google it)
                    $sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '".$this->getPost('comment')."', '1')";

                    if(mysqli_query($conn, $sqlinsert))
                        $this->addRedirect("i5-6600k");
                    else
                        $this->setSession('error',"ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn));
                }
            }
    }

无论这个页面叫什么...

<?php
# Create separator
$DS = DIRECTORY_SEPARATOR;
# Include config file
include(realpath(__DIR__.$DS.'..'.$DS.'..').$DS.'config.php');
# Check to see if this file is being wrapped by render class
if(!isset($this)) {
    # Include this file into the renderer
    echo \App::call()->getHelper('\View\Model')->render(__FILE__);
    exit;
}
# Include connection
include(ROOT_DIR.DS.'connection.php');
# Listen for the add comment action
$this->getHelper('\Commenter\Observer')->listen($conn);
?><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="stylesheet" type="text/css" href="<?php echo $this->siteUrl('/style.css') ?>">
    <title>Home</title>

    <!--[if IE]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
<?php include(ROOT_DIR.DS.'main'.DS.'main.php');?>
</head>
<body>
<div class="containermain" style="padding-bottom: 60px;">
    <h1>I5-6600k.php</h1>
    <form action="ratepost.php" method="post">
        <label for="rating">rating:</label>
        <select name="rating" id="rating" value="rating">
            <?php for($i=1; $i<=5;$i++) { ?>
            <option value="<?php echo $i ?>"><?php echo $i ?></option>
            <?php } ?>
        </select>
        <input type="submit" value="Submit">
    </form>
    <h2>graphics card write up................</h2>
    Hello <?php echo $this->getSession('user') ?>
</div>
<div class="fb-like" data-share="true" data-width="450" data-show-faces="true"></div>

<!--- COMMENT BOX --->

<div class="comments" align="center">
    <?php echo $this->writeError('error') ?>
    <form action="" method="post" >
        <!-- YOU NEED TO SEND AN ACTION WORD HERE AND CHECK FOR IT
             TO PROCESS POST -->
        <input type="hidden" name="action" value="addcomment" />
        <textarea rows="4" cols="50" name="comment">Please type a comment if you are logged in...</textarea>
        <input type="submit" value="Submit">
    </form>

...etc.

关于php - 页面请求过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43533737/

相关文章:

mysql - 我可以在 mySQL 中以 "DD-Mon-YY"格式插入日期吗?

php - 从根目录中带有 Wordpress 的子文件夹中的 Codeigniter URL 中删除 index.php

php - PHP 持续检查数据库更改的最佳做法是什么?

html - 将文本对齐到 div 的中间

javascript - 带有单选按钮的 html 表复制粘贴到 xls 中

html - 修复了使用 Phonegap 和 Bootstrap 单击链接时 div 闪烁的问题

php图像处理帮助或类?

php - 是否可以使用 php pdo 连接到 ec2 实例上的远程数据库?

mysql - 将数据库导入本地主机时,出现错误 #1064 - 您的 SQL 语法有误;

php - 避免在注册表单 php 中注入(inject) SQL