Hey guys its me again:

Basically everything on this page, at least the parts I'm able to test, are working, problem is addproduct.php is supposed to print errors when error checking the form and repopulate the data fields with the previously submitted data. I'm doing this by populating $_SESSION.

addproduct.php:

<?php require_once('checklogin.php'); 
if(!isset($_SESSION['user']))
{
    die("redirect");
    header('Location:cs4.sunyocc.edu/~j.d.dancks/onestopshop/');
}
$con = mysql_connect('localhost','jddancks','csc255');
mysql_select_db('dancks_db',$con);
//var_dump($_SESSION);
//die();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>List product at the OneStopShop</title>
<style type="text/css">
#errors {
    visibility:hidden;
    color:#FF;
}
</style>
<script type="text/javascript">
function errs()
{
    <?php
    if(isset($_SESSION['prod_errs']))
    {
        echo "document.getElementById(\"errors\").style.visibility=\"visible\"\n";
        echo "document.getElementById(\"errors\").innerHTML=\"".$_SESSION['prod_errs']."\"\n";
    }
    $val = array("prod_name","category","category2","descr","pic","pic2","bid");
    foreach($val as $var)
    {
        if(isset($_SESSION[$var]))
        {
            $str = "document.getElementById(\"".$var."\")"
            .(($var=="descr")?".value=\"":".innerHTML=\"")
            .$_SESSION[$var]."\";\n";
        }
    }
    ?>
}
</script>
</head>
<body onload="errs()">
<p id="errors"></p>
<form method="POST" action="add.php">
<p>Note: every field except picture is required</p>
<p>Product Name:<input type="text" name="prod_name" /></p>
<p>Place in category:
<select name="category">
<?php
    $q = mysql_query("SELECT cat_name FROM Category",$con);
    while($row=mysql_fetch_assoc($q))
    {
        echo "<option value=\"".$row['cat_name']."\">".$row['cat_name']."</option>\n";
    }
?>
</select>
or
Name your own category: <input type="text" name="category2" />
</p>
<p>Product Description:<textarea name="descr" rows="5" cols="80"></textarea>
<p>Picture:<input type="file" id="pic_upload" name="pic" />
or from the web:<input type="text" id="url_upload" name="pic2" />
</p>
<p>Initial starting bid:<input type="text" id="bid" name="bid" /></p>
<input type="submit" />
</form>
</body>
</html>

add.php:

<?php
    require_once('checklogin.php');
    require_once('validate.php');
    require_once('text_encode.php');
    if(!isset($_SESSION['user']))
    {
        header('Location:cs4.sunyocc.edu/~j.d.dancks/onestopshop/');
    }
    $con = mysql_connect('localhost','jddancks','csc255');
    mysql_select_db('dancks_db',$con);
    unset($_SESSION['prod_err']);
    //for addproduct.php functionality. THis is supposed to set $_SESSION['prod_name'] = $_POST['prod_name'], etc.
    $_SESSION = array_merge($_SESSION,$_POST);
    //echo("Session loaded with variables\n\n\n\n");
    //var_dump($_SESSION);
    //die();
    function add_error($text)
    {
        if(isset($_SESSION['prod_err']))
        {
            $_SESSION['prod_err']=$_SESSION['prod_err'].". ".$text;
        }
        else
        {
            $_SESSION['prod_err']=$text;
        }
    }
    if(!safe_isset($_POST['prod_name']))
    {
        add_error("Name is not set");
    }
    else if(validate_text($_POST['prod_name'],10,100))
    {
        add_error("Name is not in required format. Name must be between 10-100 characters, alphanumeric characters, spaces, period and slashes only. No control characters (e.g newline)");
    }
    if(!safe_isset($_POST['descr']))
    {
        add_error("Nothing in description");
    }
    else if(strlen($_POST['descr'])<=15||strlen($_POST['descr'])>=400)
    {
        add_error("Description must be between 15 and 400 characters");
    }
    if(safe_isset($_POST['category2']))
    {
        if(validate_text($_POST['category2'],5,100))
        {
            $q = mysql_query(sprintf("INSERT INTO Category(cat_name) VALUES (\"%s\")",$_POST['category2']));
            if(contains(mysql_error(),"duplicate entry"))
            {
                die("duplicate entry detection worked");
            }
            else
            {
                die("mysql create new category");
            }
            mysql_free_result($q);
            $_POST['category'] = $_POST['category2'];
        }
        else
        {
            add_error("User supplied category type is invalid");
        }
        $_POST['category'] = $_POST['category2'];
    }
    if(isset($_FILES["pic"]))
    {
        if(!$_FILES["pic"]["error"]>0)
        {
            $target = realpath(dirname($_SERVER['PHP_SELF']))."/images/".basename($_FILES["pic"]["name"]);
            $temp = $_FILES["pic"]["name"];
            if(!move_uploaded_file($_FILES["pic"]["tmp_name"],$target))
            {
                add_error("Picture specified did not upload");
            }
        }
        else
        {
            add_error("Picture specified did not upload correctly");
        }
        $_POST['pic']=$temp;
    }
    else if(safe_isset($_POST['pic2']))
    {
        //$check = explode($_POST['pic2'],".");
        if(strlen($_POST['pic2'])>0)
        {
            if(!preg_match("/(.)+(jpg|jpeg|gif|tiff|png)/",$check))
            {
                add_error("Picture specified with URL does not appear to be valid, it should end with the file type extension");
            }
            else
            {
                $_POST['pic'] = $_POST['pic2'];
            }
        }
    }
    if(!safe_isset($_POST['bid']))
    {
        add_error("minimum bid is not set. To accept all bids, simply enter 0");
    }
    else if(!is_numeric($_POST['bid'])||!is_only_numbers($_POST['bid'],8,2,2,true))
    {
        add_error("bid is either not a numeric value, or is not in a proper format");
    }
    //echo("Made it for last if statement\n\n\n");
    //var_dump($_SESSION);
    if(!safe_isset($_SESSION['prod_err']))
    {
        //echo("mysql is about to run\n\n\n");
        //var_dump($_SESSION);
        //die();
        $q = (isset($_POST['pic']))
        ?
        sprintf("INSERT INTO Item(item_name,cat_name,descr,image,min_bid) VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",
        $_POST['prod_name'],
        $_POST['category'],
        text_encode($_POST['descr']),
        $_POST['pic'],
        $_POST['bid']
        )
        :
        sprintf("INSERT INTO Item(item_name,cat_name,descr,min_bid) VALUES (\"%s\",\"%s\",\"%s\",\"%s\")",
        $_POST['prod_name'],
        $_POST['category'],
        text_encode($_POST['descr']),
        $_POST['bid']
        );
        $que = mysql_query($q,$con) or die(mysql_error());
        //cleanup session
        cleanup($_POST);
        mysql_free_result($que);
        header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/userpage.php');
    }
    else
    {
        //echo("mysql didn't run\n\n\n");
        //var_dump($_SESSION);
        //die();
        header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/addproduct.php');
    }
?>

Tangential code that's being called:

validate.php:

<?php
function validate_text($text,$min,$max,$include_spaces=true)
{
    $match = array();
    $regex = ($include_spaces)?"/[a-zA-Z0-9 .-_]":"/[a-zA-Z0-9.]";
    if($max<=0)
    {
        $regex = sprintf($regex."{%i,}/",$min);
    }
    else
    {
        $regex = sprintf($regex."{%i,%i}/",$min,$max);
    }
    if($include_spaces)
    {
        preg_match($regex,$text,$match);
    }
    else
    {
        preg_match($regex,$text,$match);
    }
    return (implode($match)==$text);
}
function sanitize($text,$min,$max,$include_spaces=true)
{
    $match = array();
    $regex = ($include_spaces)?"/[a-zA-Z0-9 .-_]":"/[a-zA-Z0-9.-_]";
    if($max<=0)
    {
        $regex = sprintf($regex."{%d,}/",$min);
    }
    else
    {
        $regex = sprintf($regex."{%d,%d}/",$min,$max);
    }
    if($include_spaces)
    {
        preg_match($regex,$text,$match);
    }
    else
    {
        preg_match($regex,$text,$match);
    }
    return implode($match);
}
function is_only_numbers($text,$max_chars=22,$min_chars=1,$accuracy=2,$is_float=false)
{
    $regex=($is_float)?sprintf("/[0-9]{%d,%d}+.[0-9]{%d,%d}/",$min_chars,$max_chars,$min_chars,$accuracy):sprintf("/[0-9]{%d,%d}/",$min_chars,$max_chars);
    return (preg_match($regex,$text)==1);
}
function contains($text,$match)
{
    return (preg_match("/".$match."/",$text)==1);
}
function safe_isset($text)
{
    $good = false;
    if(isset($text))
    {
        if(strlen($text)>0)
        {
            $good = true;
        }
    }
    return $good;
}
?>

and checklogin.php:

<?php
session_start();
$good = true;
function redir()
{
    die("redir is called");
    if(isset($_SERVER['HTTP_REFERER']))
    {
        header('Location:'.$_SERVER['HTTP_REFERER']);
    }
    else
    {
        header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/index.php');
    }
}
function logout()
{
        $_SESSION = array();
        session_destroy();
        //header('Location:http://cs4.sunyocc.edu/~j.d.dancks/index.php');
}
if(isset($_SESSION['attempts']))
{
    if($_SESSION['attempts']>=5)
    {
        $good=false;
    }
}
if($good)
{
    if(!isset($_SESSION['time']) || !isset($_SESSION['user']))
    {
        logout();
    }
    else if($_SESSION['time'] < time())
    {
        logout();
    }
}
function cleanup($junk)
{
    /*$ref = array();
    $ref = $_SESSION;
    $_SESSION = array();
    foreach($var as $ref)
    {
        if(!isset($_POST[array_keys($ref,$var)]))
        {
            $_SESSION[$var] = $ref[$var];
        }
    }*/
    die("cleanup called\n");
    foreach($var as $junk)
    {
        $k = array_keys($junk,$var);
        if(isset($junk[$k[0]]))
        {
            unset($_SESSION[$k[0]]);
        }
    }
}
?>

Also I find it helps to view my code when its full screen like on daniweb.

You need to include session_start(); at the top of your PHP pages.

Take joshmac's advice and include session_start() at the top of your pages.

Also, you are not outputting the line:

$str = "document.getElementById(\"".$var."\")"
            .(($var=="descr")?".value=\"":".innerHTML=\"")
            .$_SESSION[$var]."\";\n";

You never use the variable $str as far as I can see. The line should be:

echo "document.getElementById(\"".$var."\")"
            .(($var=="descr")?".value=\"":".innerHTML=\"")
            .$_SESSION[$var]."\";\n";

checklogin.php has session_start at the top, which is why I do require_once for my main pages. I thought that was good enough?

ahh. see. Sometimes you (I mean I) really need a second pair of eyes on things. I spent too much time on this. Thank you Gavinflud.

Yeah, once it's included in checklogin.php then the session will be started.

No problem, the simple things are the easiest to overlook.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.