0

I'm currently learning php and I need to store the product ID (auto incremented) to a cookie, then retrieve the cookie and display to the user on an update page. I am aware cookies are not good for storing form data but this is for educational purposes. I have provided a copy of the form and validation code, this then calls a file called storefile2 to send details to the database and display on an update page to user. I am stuck on this problem and would appreciate any help. Thanks

        $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>

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
zed
  • 1
  • 2

2 Answers2

1

If you want the cookie name to have a literal $ character in it, you need to use just single quotes around the name when calling setcookie().

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

By putting double quotes around it, you're allowing the variable to be expanded, because single quotes inside double quotes have no special meaning, they're just treated as literal characters.

See What is the difference between single-quoted and double-quoted strings in PHP?

Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

I'm sorry that I really don't have time to try to debug your source-code, but please start by using the browser debug features of your browser to observe the actual interaction between your PHP code (whatever it is ...) and an actual browser.

When you "set a cookie," what happens is that an HTTP header is added to the next bundle of data that will be sent to the client, specifying the name of the cookie and the value that it is to take. Once the client has received and processed that header, it will include the cookie and its value in HTTP headers that it thereafter sends to the host ... i.e. "next time."

So – use your browser to check those headers. Did the host actually send the set-cookie request? Did the client thereafter send it? (And, if it did, why didn't your server-side code see it?)

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41