使用php将数据存储到cookie

时间:2018-11-05 22:30:46

标签: php cookies

我目前正在学习php,我需要将产品ID(自动递增)存储到cookie中,然后检索该cookie并在更新页面上显示给用户。我知道Cookie不适用于存储表单数据,但这是出于教育目的。我提供了表单和验证代码的副本,然后调用了一个名为storefile2的文件以将详细信息发送到数据库并在更新页面上显示给用户。我在这个问题上陷入困境,将不胜感激。谢谢

    

        $prodID = 0;

        if (isset($_COOKIE['$prodID'])) {
            $prodID = ++$_COOKIE['$prodID'];
        }
        else {
            $productID = 1;
        }
        setcookie("'$prodID'", $prodID, time()+ (86400 * 365));

?>                      
<html lang="en">  
<head>   
    <meta charset="UTF-8">  
    <title>Assessment 4</title> 
    <link rel="stylesheet" type="text/css" href="css/lever.css"> 
</head>

<style>    
    .error { color: #FF0000; }   
    .container {width:700px;margin:0 auto;}
    .center {text-align:center;}

</style> 
<body>  

<?php        
    $errMessageName ="required field"; 
    $errMessageFinish="required field";
    $errMessageUsage = "required field";
    $errMessageCost="required field";
    $errMessageImage="required field";
    $prodName="";
    $prodFinish="";
    $prodUsage="";
    $prodCost="";
    $prodID="";
    $invalidData = false; 

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        if(isset($_POST["reset"])){    
                header("Refresh:0");   
                exit();    
        } 

        //validate fields   
        $prodName = checkinput($_POST["Name"]);
        $prodFinish = checkinput($_POST["Finish"]);
        $prodUsage = checkinput($_POST["Usage"]);
        $prodCost = checkinput($_POST["Cost"]);

        $fileupload = $_FILES['userfile']['name'];
        $filetype = $_FILES['userfile']['type']; 
        $filesize = $_FILES['userfile']['size'];
        $tempname = $_FILES['userfile']['tmp_name'];

        $filelocation = "images/$fileupload"; 

            if($prodName == "") { 
                $errMessageName = "Product name must not be blank";
                $invalidData = true;
            }     
            elseif ($prodFinish == "") { 
                $errMessageFinish = "Product finish must not be blank";  
                $invalidData = true;
            }     
            elseif ($prodUsage == ""){    
                $errMessageUsage = "Product Usage must not be blank";
                $invalidData = true;
            }     
            elseif (!filter_var($prodCost, FILTER_VALIDATE_FLOAT)) { 
                $errMessageCost = "Please enter a number only in decimal format eg: 1.00"; 
                $invalidData = true;
            }                                                   
            //make sure a file has been entered   
            elseif($fileupload == "") { 
                $errMessageImage = "Please enter an image";
                $invalidData = true;    
            } 
            //check file type
            elseif (($_FILES['userfile']['type'] != "image/jpg") && ($_FILES['userfile']['type'] != "image/png")  
            && ($_FILES['userfile']['type'] != "image/jpeg"))
            {   
                $errMessageImage = "Only JPG & PNG files are allowed.";
                $invalidData = true;            
            }                                                               
            elseif (!move_uploaded_file($tempname,$filelocation)) {   
                    switch ($_FILES['userfile']['error'])    
                    {     
                        case UPLOAD_ERR_INI_SIZE:    
                            echo "<p>Error: File exceeds the maximum size limit set by the server</p>" ;   
                        break;   

                         case UPLOAD_ERR_FORM_SIZE:  
                            echo "<p>Error: File exceeds the maximum size limit set by the browser</p>" ;    
                        break;       

                        case UPLOAD_ERR_NO_FILE:    
                            echo "<p>Error: No file uploaded</p>" ;   
                        break; 

                        default:    
                            echo "<p>File could not be uploaded </p>" ; 
                    }   
                }
                else
                {               

                $conn = mysqli_connect("localhost:3306","root",""); 
                // Check connection  
                if (mysqli_connect_errno())   
                {   
                    echo "<p>Failed to connect to MySQL: " . mysqli_connect_error() . "</p>";   
                }  

        }               

            if ($invalidData == false) {   
            include('storefile2.php');
            //Show thank you page    
            //header('Location: update.php');                                   
            exit();
            }       
        }


        function checkInput($inputData) {    
            $inputData = trim($inputData);    
            $inputData = stripslashes($inputData);    
            $inputData = htmlspecialchars($inputData);  
            return $inputData;   
            }

    ?>

        <div class="container">
        <h1>Acme Hardware</h1>
        <h2>Door Levers - Product Entry Form</h2>
        <h3>Enter the Door Lever Product Details into the form and and click the Submit button</h3>

        <p>NOTE: * denotes required entry</p></br>  

        <form id="Form1" name="Form" method="post" enctype='multipart/form-data' action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>   

            <label for="Name">Product Name: </label><input type="text" name="Name" id="Name" size="20" value="<?php echo
            $prodName;?>"><span class="error">* <?php echo $errMessageName;?></span><br /><br /> 

            <label for="Finish">Product Finish: </label> <input type="text" name="Finish" id="Finish" size="20" value="<?php echo   
            $prodFinish;?>"><span class="error">* <?php echo $errMessageFinish;?></span><br /><br />

            <label for="Usage">Product Usage: </label><input type="text" name="Usage" id="Usage" size="20" value="<?php echo
            $prodUsage;?>"><span class="error">* <?php echo $errMessageUsage;?></span><br /><br />

            <label for="Cost">Product Cost: </label><input type="text" name="Cost" id="Cost" size="20" value="<?php echo
            $prodCost;?>"><span class="error">* <?php echo $errMessageCost;?></span><br /><br />

            <a href="ProductCost.php">Update product cost</a> <br/><br/>
            <a href="deleteProduct.php">Delete product</a> <br/><br/>

            <input type='hidden' name='MAX_FILE_SIZE' value='4000000'/>   
            <label for="userfile">Product image: </label><input type='file' id='userfile' name='userfile'><span class="error">* <?php echo $errMessageImage;?></span></br>

             <input type="submit" name="submit" value="Submit"/>  
             <input type ="reset" name="reset" value ="Reset" title="Reset Form"/>  

        </form>   
        </div>

  

2 个答案:

答案 0 :(得分:1)

如果您希望cookie名称中包含一个文字$字符,则在调用setcookie()时只需在名称周围使用单引号即可。

setcookie('$prodID', $prodID, time()+ (86400 * 365));

通过在双引号周围加上双引号,可以扩展该变量,因为双引号内的单引号没有特殊含义,因此它们被视为文字字符。

请参见What is the difference between single-quoted and double-quoted strings in PHP?

答案 1 :(得分:-1)

很抱歉,我真的没有时间尝试调试您的源代码,但是请先使用浏览器的浏览器调试功能来观察您之间的实际交互PHP代码(无论是什么)和实际的浏览器。

“设置Cookie”时,会发生 HTTP标头添加到将发送到客户端的下一个数据包中,并指定cookie的名称和值这是要采取的。客户端收到并处理了该标头后,它将在 HTTP标头中包含该cookie及其值,然后将其发送给主机... 。 “ 下一个时间。”

所以–使用浏览器检查那些标题。 是否主机实际上发送了设置cookie请求?此后客户端发送 吗? (而且,如果可以,为什么您的服务器端代码看不到它?)