-2

我在尝试对我网站的某个部分进行密码保护时遇到了困难。我对 php 不太熟悉,所以我使用来自 zubrag.com 的代码作为起点。我遇到的问题是当前代码出现错误,指出:

cannot modify header information - headers already sent by (output started at /var/www/index.php:78) in /var/www/index.php on line 333

我看过 78,我明白了,我的输出从那里开始,因为那是 php 括号所在的第一行。

第 333 行是我的setcookie命令。我也明白,为了设置 cookie,需要在标题中完成。不幸的是,我不确定如何用我的代码做到这一点。我在网上查看过,发现通常解决此问题的最佳方法是使用ob_start()and ob_end_flush()。好吧,我尝试将这些命令放在很多地方,但到目前为止还没有运气。

我已经ob_start在文件的开头设置了,在其他所有内容之前。我也在案件开始时尝试过,但没有运气。

我已经ob_end_flush在文件末尾和案例末尾设置了,我也没有运气。

<html lang="en">
    <head>
        <title>DVR Controls</title>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <link rel="stylesheet" type="text/css" href="css/superfish.css">
        <link rel="stylesheet" media="screen" href="css/superfish-navbar.css" /> 
        <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
        <script type="text/javascript" src="js/hoverIntent.js"></script>
        <script type="text/javascript" src="js/superfish.js"></script>
        <script type="text/javascript">

        // initialise plugins
        jQuery(function(){
            jQuery('ul.sf-menu').superfish();
        });

        </script>
        <script>
        $(document).ready(function(){ 
                $("ul.sf-menu").superfish({ 
                    pathClass:  'current' 
                }); 
        });

        </script>

        <center><b><font size="36">The Radeus DVR Prototype</font></b></center>
    </head>
    <body>
        <ul class="sf-menu sf-navbar">
            <li class="current">
                <a>Configuration</a>
                <ul>

                    <li>
                        <a href="index.php?page=SysConfig">System Configuration</a>
                    </li>

                    <li>
                        <a href="index.php?page=FileConfig">File Configuration</a>
                    </li>

                    <li>
                        <a href="index.php?page=NetworkConfig">Network Configuration</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="index.php?page=Files">Files</a>
            </li>
            <li>
                <a href="index.php?page=Maintenance">Maintenance Mode</a>
            </li>
            <li>
                <a href="index.php?page=IETM">IETM</a>
            </li>   
            <li>
                <a>Power Options</a>
                <ul>
                    <li>
                        <a href="index.php?page=Shutdown">Shutdown</a>
                    </li>

                    <li>
                        <a href="index.php?page=Reboot">Reboot</a>
                    </li>
                </ul>
            </li>
        </ul>


    </body>
<br><br><br><br><br>
<body>
<br>
<?php
ob_start();
$currentdir = '/data/'; //Location of Hard Drive

/**
 * @func: Executes the command passed to it as argument and prints the
 * command console output line by line onto the html output stream hence
* giving the illusion of having the command executing in the html window itself.
 */

function html_exec_cmd($cmd)    {
    $proc = popen("($cmd)2>&1", "r");
    echo '<pre>';
    while(!feof($proc)) {
        $result = fgets($proc, 100);
        echo htmlspecialchars($result);
        flush();
    }
    pclose($proc);
    echo '</pre>';
}

switch ($_GET['page'])
{

    case 'SysConfig':
          echo "Welcome to System Config!";
    break;

    case 'FileConfig':
          echo "Welcome to File Config!";
    break;

    case 'NetworkConfig':

?>
<b><fontsize="16">Current Settings:</b></font>



<?php

html_exec_cmd('ifconfig eth0'); 



     break;

     case 'Files':





    $FileCount = 0;
    $dir = opendir($currentdir);
    $array = array();
    echo '<ul>';



echo '<form method = "post" action = "">';

while ($File = readdir($dir)){

echo '<form action="test.php" method = "post">';

//if (is_file($file))

    $ext = pathinfo($File, PATHINFO_EXTENSION);
    if ($ext == '264'){


    $array[] = "$File";

    echo "<INPUT class='radio' type='radio' name='FileName' value='$File' /> <span>$File</span><p>";    

    $FileCount++;   
    }

    }




    echo "<INPUT TYPE = 'Submit' name = 'FormSubmit' value = 'Submit'>";

    echo '</form>';


    if ($_POST['FormSubmit'] == "Submit")
    {
    $FileParameters = $_POST['FileName'];

    $FileExecuteCommand = "cd //; /etc/init.d/matrix-gui-e stop;echo 0 > /sys/devices/platform/vpss/graphics0/enabled;./usr/share/ti/ti-omx/    decode_display_a8host_debug.xv5T -w 1920 -h 1080 -f 60 -c h264 -g 0 -d 0 -i $currentdir$FileParameters;/etc/init.d/matrix-gui-e start";


    echo exec($FileExecuteCommand);



     }




     break;


     case 'Maintenance':


###############################################################
# Page Password Protect 2.13
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
############################################################### 
#
# Usage:
# Set usernames / passwords below between SETTINGS START and SETTINGS END.
# Open it in browser with "help" parameter to get the code
# to add to all files being protected. 
#    Example: password_protect.php?help
# Include protection string which it gave you into every file that needs to be protected
#
# Add following HTML code to your page where you want to have logout link
# <a href="http://www.example.com/path/to/protected/page.php?logout=1">Logout</a>
#
###############################################################

/*
-------------------------------------------------------------------
SAMPLE if you only want to request login and password on login form.
Each row represents different user.

$LOGIN_INFORMATION = array(
  'zubrag' => 'root',
  'test' => 'testpass',
  'admin' => 'passwd'
);

--------------------------------------------------------------------
SAMPLE if you only want to request only password on login form.
Note: only passwords are listed

$LOGIN_INFORMATION = array(
  'root',
  'testpass',
  'passwd'
);

--------------------------------------------------------------------
*/

##################################################################
#  SETTINGS START
##################################################################

// Add login/password pairs below, like described above
// NOTE: all rows except last must have comma "," at the end of line
$LOGIN_INFORMATION = array(
  'admin' => 'adminpass'
);

// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);

// User will be redirected to this page after logout
define('LOGOUT_URL', 'http://www.example.com/');

// time out after NN minutes of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 3);

// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

##################################################################
#  SETTINGS END
##################################################################


///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////

// show usage example
if(isset($_GET['help'])) {
  die('Include following code into every page you would like to protect, at the very beginning (first line):<br>&lt;?php include("' . str_replace('\\','\\\\',__FILE__) . '"); ?&gt;');
}

// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);

// logout?
if(isset($_GET['logout'])) {
  setcookie("verify", '', $timeout, '/'); // clear password;
  header('Location: ' . LOGOUT_URL);
  exit();
}

if(!function_exists('showLoginPasswordProtect')) {

// show login form
function showLoginPasswordProtect($error_msg) {
?>
<html>
<head>
  <title>Please enter password to access this page</title>
  <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
  <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</head>
<body>
  <style>
    input { border: 1px solid black; }
  </style>
  <div style="width:500px; margin-left:auto; margin-right:auto; text-align:center">
  <form method="post">
    <h3>Please enter password to access this page</h3>
    <font color="red"><?php echo $error_msg; ?></font><br />
<?php if (USE_USERNAME) echo 'Login:<br /><input type="input" name="access_login" /><br />Password:<br />'; ?>
    <input type="password" name="access_password" /><p></p><input type="submit" name="Submit" value="Submit" />
  </form>
  <br />
  </div>
</body>
</html>

<?php
  // stop at this point
  die();
}
}

// user provided password

if (isset($_POST['access_password'])) {

  $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  $pass = $_POST['access_password'];
  if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) ) 
  ) {
    showLoginPasswordProtect("Incorrect password.");
  }
  else {
    // set cookie if password was validated
    setcookie("verify", md5($login.'%'.$pass), $timeout, '/');

    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }

}

else {

  // check if password cookie is set
  if (!isset($_COOKIE['verify'])) {
    showLoginPasswordProtect("");
  }

  // check if cookie is good
  $found = false;
  foreach($LOGIN_INFORMATION as $key=>$val) {
    $lp = (USE_USERNAME ? $key : '') .'%'.$val;
    if ($_COOKIE['verify'] == md5($lp)) {
      $found = true;
      // prolong timeout
      if (TIMEOUT_CHECK_ACTIVITY) {
        setcookie("verify", md5($lp), $timeout, '/');
      }
      break;
    }
  }
  if (!$found) {
    showLoginPasswordProtect("");
  }

}





?>

<B><fontsize=16>Are you sure you want to Format the data disk?</b></font><br><br>

<?php
echo '<form method = "post">';

echo "<INPUT TYPE = 'Submit' name = 'FormatSubmit' value = 'Submit'>";

?>
<br><br><br>
Please check the box to verify you want to Format the data disk.

<Input type = 'Checkbox' Name ='FormatCheck' value ="checked">

<?php
echo '</form>';
if (($_POST['FormatSubmit'] == "Submit") & ($_POST['FormatCheck'] == "checked"))
    {
    html_exec_cmd('echo -e "o\nn\np\n1\n\n\nw\n" | fdisk /dev/sda;sleep 1;mkfs.ext3 /dev/sda1;mount /dev/sda1 /data/');
     }

ob_end_flush();
     break;


     case 'IETM':
          echo "Welcome to IETM";
     break;

        case 'Shutdown':
          //echo "Welcome to Shutdown";

?>

<B><fontsize=16>Are you sure you want to shutdown the DVR?</b></font><br><br>

<?php
echo '<form method = "post">';

echo "<INPUT TYPE = 'Submit' name = 'ShutDownSubmit' value = 'Submit'>";

?>
<br><br><br>
Please check the box to verify you want to shutdown the DVR.

<Input type = 'Checkbox' Name ='ShutDownCheck' value ="checked">

<?php
echo '</form>';
if (($_POST['ShutDownSubmit'] == "Submit") & ($_POST['ShutDownCheck'] == "checked"))
    {
    $ShutDownCommand = "init 0";
    echo exec($ShutDownCommand);

     }

     break;

     case 'Reboot':
          //echo "Welcome to Reboot";

?>

<B><fontsize=16>Are you sure you want to reboot the DVR?</b></font><br>
<br>
<?php

echo '<form method = "post">';
echo "<INPUT TYPE = 'Submit' name = 'RebootSubmit' value = 'Submit'>";
?>
<br><br><br>
Please check the box to verify you want to reboot the DVR.

<Input type = 'Checkbox' Name ='RebootCheck' value ="checked">

<?php

if (($_POST['RebootSubmit'] == "Submit")& ($_POST['RebootCheck'] == "checked"))
{
    $RebootCommand = "reboot";
    echo exec($RebootCommand);

     }

echo '</form>';
     break;  

    default :
           echo "The Radeus DVR";

}  
?>
</body>

</html>
<?php ob_end_flush(); ?>
4

2 回答 2

3

如果您要使用 PHP 的header函数,则必须在将任何响应发送给用户之前调用它。在这种情况下,阻止此操作的响应是位于您的 PHP 代码之前的页面顶部的 HTML。

于 2012-08-06T15:35:14.347 回答
0

您可以在 PHP 回显语句中使用一些 javascript 来执行重定向并完全避免 PHP 标头问题。例如:

echo '<script type="text/javascript"> window.location = "login.php"; </script>';
于 2012-08-06T19:56:38.227 回答