A lot of code here. Basically I'm making an auction type site. This segment of code is for a user to upload a product:

I'm pretty sure there isn't anything wrong with addproduct.php but for completeness I feel like I should post it.

addproduct.php:

<?php require_once('checklogin.php');
require_once('validate.php');
if(!isset($_SESSION['user']))
{
    //die("redirect");
    header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/');
}
$con = mysql_connect('localhost','jddancks','csc255');
mysql_select_db('dancks_db',$con);
?>
<!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:#060606;
    background-color:#F00;
}
</style>
<script type="text/javascript">
function month()
{
    var theMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var i = 0;
var monthNumber;
document.writeln ("<option value=\"\">Select Month");
for (i=0; i<12; i++) {
monthNumber = i+1;
    if(monthNumber==<?php if(check_ses('month')){echo $_SESSION['month'];}else{echo "-1";}?>)
    {
        document.write("<option value=\"" +monthNumber+"\" selected=\"selected\" >" + theMonths[i]+"");
    }
    else
    {
        document.write("<option value=\"" +monthNumber+"\">" + theMonths[i]+"");
    }
}
}
function day()
{
var i = 0;
document.writeln ("<option value=\"\">Select Day");
for (i=1; i<32; i++) {
    if(i==<?php if(check_ses('day')){echo $_SESSION['day'];}else{echo "-1";}?>)
    {
        document.write("<option value=\"" +i+"\" selected=\"selected\" >" + i +"");
    }
    else
    {
        document.write("<option value=\"" +i+"\">" + i +"");
    }
}
}
function year()
{
var time = new Date();
var year = time.getYear();
var date = (year<2000)?(year+1900):year;
document.writeln ("<option value=\"\">Select Year");
for(var i=0;i<2;i++)
{
    if(date==<?php if(check_ses('year')){echo $_SESSION['year'];}else{echo "-1";}?>)
    {
        document.write ("<option value=\"" +date+"\" selected=\"selected\" >" +date+ "");
    }
    else
    {
        document.write ("<option value=\"" +date+"\">" +date+ "");
    }
date++;
}
} 
function errs()
{
<?php
if(check_ses('prod_err'))
{
    echo "document.getElementById(\"errors\").style.visibility=\"visible\"\n";
}
$val = array('prod_name','category','descr','pic2','bid','day','month','year');
foreach($val as $var)
{
    if(check_ses($var))
    {
        echo "document.getElementById(\"".$var."\").innerHTML=\"visible\"\n";
    }
}
?>
}
</script>
</head>
<body onload="errs()">
<p id="errors"><?php if(isset($_SESSION['prod_err'])) {echo $_SESSION['prod_err'];}?></p>
<form method="POST" action="add.php" enctype="multipart/form-data">
<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))
    {
        if(!isset($_SESSION['category']))
        {
            echo "<option value=\"".$row['cat_name']."\">".$row['cat_name']."</option>\n";
        }
        else if($row['cat_name']==$_SESSION['category'])
        {
            echo "<option value=\"".$row['cat_name']."\" checked=\"checked\">".$row['cat_name']."</option>\n";
        }
    }
?>
</select>
</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>
<p>Date: 
Month:  
<select name="month" id="month">
<script type="text/javascript">
month();
</script>
</select>
Day:  
<select name="day" id="day">
<script type="text/javascript">
day();
</script>
</select>
Year:  
<select name="year" id="year">
<script type="text/javascript">
year();
</script>
</select>
</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']);
    $val = array('prod_name','category','descr','pic','pic2','bid','day','month','year');
    foreach($val as $var)
    {
        if(check_post('var'))
        {
            $_SESSION[$var]=$_POST[$var];
        }
    }
    function add_error($text)
    {
        if(array_key_exists('prod_err',$_SESSION))
        {
            $_SESSION['prod_err']=$_SESSION['prod_err'].". ".$text;
        }
        else
        {
            $_SESSION['prod_err']=$text;
        }
    }
    if(!check_post('prod_name'))
    {
        add_error("Name is not set");
    }
    if(!check_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(check_file("pic"))
    {
        //var_dump($_FILES["pic"]);
        if($_FILES["pic"]["error"]==0)
        {
            $name = explode(".",basename($_FILES["pic"]["name"]));
            $target = realpath(dirname(__FILE__))."/images/".$name[0].session_id().".".$name[1];
            $temp = $name[0].session_id().".".$name[1];
            if(!move_uploaded_file($_FILES["pic"]["tmp_name"],$target))
            {
                add_error("Picture specified did not upload");
            }
            $_POST['pic']=$temp;
        }
        else
        {
            add_error("Picture specified did not upload correctly");
        }
    }
    else if(check_post('pic2'))
    {
        if(strlen($_POST['pic2'])>0)
        {
            if(preg_match("/.(jpg|jpeg|gif|tiff|png)/",$_POST['pic2'])==0)
            {
                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(!check_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");
    }
    if(check_post('day')&&check_post('month')&&check_post('year'))
    {
        //die("day: ".$_POST['day']." month: ".$_POST['month']." year: ".$_POST['year']);
        if(!check_post('day',"Select Day")&&!check_post('month',"Select Month")&&!check_post('year',"Select Year"))
        {
            $days = array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
            $today = explode("-",date("d-m-Y"));
            if(checkdate($_POST['month'],$_POST['day'],$_POST['year']))
            {
                $c_y = ($_POST['year']==$today[2]);
                $c_m = ($_POST['month']==$today[1]);
                $p_d = ($today[2]>$_POST['day']);
                $p_m = ($today[1]>$_POST['month']);
                if(!($c_y&&(($c_m&&$p_d)||$p_m)))
                {
                    $_POST['date']=$_POST['year']."-".(($_POST['month']>9)?$_POST['month']:"0".$_POST['month'])."-".(($_POST['day']>9)?$_POST['day']:"0".$_POST['day']);
                    //die($_POST['date']);
                }
                else
                {
                    add_error("Date must be current");
                }
            }
            else
            {
                add_error("Invalid expiration date");
            }
        }
        else 
        {
            add_error("Pick an expiration date");
        }
    }
    else
    {
        add_error("Date not set");
    }
    //die("date: ".$_POST['date']);
    //die("prod_err: ".$_SESSION['prod_err']);
    if(!check_ses('prod_err')&&check_post('date'))
    {
        $q = (check_post('pic'))
        ?
        sprintf("INSERT INTO Item(item_name,cat_name,descr,image,min_bid,date) VALUES ('%s','%s','%s','%s','%s','%s')",
        mysql_real_escape_string($_POST['prod_name']),
        mysql_real_escape_string($_POST['category']),
        mysql_real_escape_string($_POST['descr']),
        mysql_real_escape_string($_POST['pic']),
        mysql_real_escape_string($_POST['bid']),
        mysql_real_escape_string($_POST['date'])
        )
        :
        sprintf("INSERT INTO Item(item_name,cat_name,descr,min_bid,date) VALUES ('%s','%s','%s','%s','%s')",
        mysql_real_escape_string($_POST['prod_name']),
        mysql_real_escape_string($_POST['category']),
        mysql_real_escape_string($_POST['descr']),
        mysql_real_escape_string($_POST['bid']),
        mysql_real_escape_string($_POST['date'])
        );
        $que = mysql_query($q,$con) or die(mysql_error());
        unset($_SESSION['prod_err']);
        cleanup($_POST);
        header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/userpage.php');
    }
    else
    {
        die($_POST['date']);
        header('Location:http://cs4.sunyocc.edu/~j.d.dancks/onestopshop/addproduct.php');
    }
?>

Relevant code: 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."{%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)==$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;
}
function safe_check($text,$value)
{
    $good=safe_isset($text);
    $good=($good&&($text==$value));
    return $good;
}
function check_post()
{
    $num = func_num_args();
    $args = func_get_args();
    $good = false;
    if(array_key_exists($args[0],$_POST))
    {
        if($num>1)
        {
            $good = safe_check($_POST[$args[0]],$args[1]);
        }
        else
        {
            $good = safe_isset($_POST[$args[0]]);
        }
    }
    return $good;
}
function check_get()
{
    $num = func_num_args();
    $args = func_get_args();
    $good = false;
    if(array_key_exists($args[0],$_GET))
    {
        if($num>1)
        {
            $good = safe_check($_GET[$args[0]],$args[1]);
        }
        else
        {
            $good = safe_isset($_GET[$args[0]]);
        }
    }
    return $good;
}
function check_ses()
{
    $num = func_num_args();
    $args = func_get_args();
    $good = false;
    if(array_key_exists($args[0],$_SESSION))
    {
        if($num>1)
        {
            $good = safe_check($_SESSION[$args[0]],$args[1]);
        }
        else
        {
            $good = safe_isset($_SESSION[$args[0]]);
        }
    }
    return $good;
}
//preg_match("/[0-1]{1,1}/",$_GET['type'],$match2);
//num_check($_GET['id'],0,9,1,5)
function num_check($var,$min,$max,$minw,$maxw)
{
    $q = sprintf("/[%d-%d]{%d,%d}/",$min,$max,$minw,$maxw);
    $match = array();
    preg_match($q,$var,$match);
    //die("var: ".$var." regex: ".$q."boolean read: ".(implode($match)==$var));
    return (implode($match)==$var);
}
function confirm_date($date,&$today)
{
    $good = true;
    $the_date = explode("/",$date);
    $good = (count($the_date[0])==3);
    if($good)
    {
        $days = array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
        if(is_numeric($the_date[0])&&is_numeric($the_date[1])&&is_numeric($the_date[2]))
        {
            $a = $the_date[0]-1; $b = $the_date[1]+0; $c = $the_date[2]+0;
            if($b<14) {$b=$b+2000;}
            if($a>-1&&$a<12)
            {
                if(($b>0)&&($days[$a]<$b))
                {
                    if(($c==2012)&&($c==2013))
                    {
                        $today= $c."-".$a."-".$b." 23:59:59";
                    }
                    else {$good=false;}
                }
                else {$good=false;}
            }
            else {$good=false;}
        }
        else {$good=false;}
    }
    return $good;
}
function check_file($name)
{
    $good = false;
    if(array_key_exists($name,$_FILES))
    {
        if(isset($_FILES[$name]))
        {
            $good = ((
                (strlen($_FILES[$name]['name'])>0)
                &&(strlen($_FILES[$name]['type'])>0)
                &&(strlen($_FILES[$name]['tmp_name'])>0)
                &&$_FILES[$name]['size']>0));
        }
    }
    return $good;
}
?>

Since it doesn't die I know that add_error wasn't called, therefore $_SESSION['prod_err'] wasn't set and as far as I know everything is OK. So it executes, no noise. but no mysql query. What the hell. I appreciate anyone willing to read all that code I know its a lot.

Recommended Answers

All 8 Replies

Something I'm curious about: I did a couple of var_dumps, and this is what the mysql query looks like:

INSERT INTO Item(item_name,cat_name,descr,image,min_bid,date) VALUES ('Adult Bobcat','Pets and Pet Supplies','Adult Bobcat. Fully domesticated.','Adult_Bobcat09c053b603e31a3ad1500326ed6d2152.jpg','15.00','2013-01-12')

array(10) { ["prod_name"]=> string(12) "Adult Bobcat" ["category"]=> string(21) "Pets and Pet Supplies" ["descr"]=> string(33) "Adult Bobcat. Fully domesticated." ["pic2"]=> string(0) "" ["bid"]=> string(5) "15.00" ["month"]=> string(1) "1" ["day"]=> string(2) "12" ["year"]=> string(4) "2013" ["pic"]=> string(48) "Adult_Bobcat09c053b603e31a3ad1500326ed6d2152.jpg" ["date"]=> string(10) "2013-01-12" }
space

array(6) { ["name"]=> string(4) "SHOP" ["user"]=> string(6) "dancks" ["ID"]=> string(1) "2" ["email"]=> string(20) "jddancks@sunyocc.edu" ["date"]=> string(10) "12//12//12" ["time"]=> int(1355374566) }

Do I have to worry about mysql or linux with really long file names?

Hi,

Copy, paste to notepad, save as info.php, upload to your server.

    <?php
        phpinfo();

    ?>

Direct your browser to this file..

Look for the following setting values

        max_execution_time
        max_file_uploads
        max_input_time
        post_max_size

Let us know what you have..also what do you see on the

        Server API 

is it apache module or CGI/FastCGI?

OK its not the name. It worked before I don't know what happened. I did have to change some code because the secondary pic upload (wher you input a URL instead) didn't work.

also, the sql table:

mysql> describe Item;
+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| item_name   | varchar(100) | NO   |     |                   |                | 
| ItemID      | mediumint(9) | NO   | PRI | NULL              | auto_increment | 
| cat_name    | varchar(45)  | NO   |     |                   |                | 
| userID      | mediumint(9) | NO   |     |                   |                | 
| descr       | text         | NO   |     |                   |                | 
| image       | tinytext     | YES  |     | NULL              |                | 
| date        | timestamp    | NO   |     | CURRENT_TIMESTAMP |                | 
| min_bid     | decimal(6,2) | NO   |     | 0.00              |                | 
| highest_bid | decimal(6,2) | NO   |     | 0.00              |                | 
| bidderID    | mediumint(9) | YES  |     | NULL              |                | 
| time_expire | date         | NO   |     |                   |                | 
| expired     | tinyint(4)   | NO   |     | 0                 |                | 
+-------------+--------------+------+-----+-------------------+----------------+

Server is Apache 2.0

I don't know exactly what the problem is, but I think the code I originally posted is OK. The issue is with this php script that is supposed to update the items listed and delist them if their auction expired:

<?php
function check_items()
{
$con = mysql_connect('localhost','jddancks','csc255');
mysql_select_db('dancks_db',$con);
$q = mysql_query("select last_check from ran_last",$con) or die("Check ran_last 1");
$r = mysql_fetch_assoc($q);
//if((time()-strtotime($r['last_check'])) >(60*60*17))//check only once every 17 hours
if(true)
{
    $q2 = mysql_query("select * from Item");
    $remove = array(); $count=0;
    while($row = mysql_fetch_assoc($q2))
    {
        if(strtotime($row['time_expire'])<time())
        {
            echo("strtotime: ".strtotime($row['time_expire'])." time: ".time());
            $remove[$count] = $row['ItemID'];
            $count++;
        }
    }
    mysql_free_result($q2);
    foreach($remove as $next)
    {
        echo($next);
        $q3 = mysql_query(sprintf("select * from Item where ItemID='%s'",$next)) or die("check items outer query foreach");
        $r3 = mysql_fetch_assoc($q3);
        $q4 = mysql_query(sprintf("update Item set expired='1' where ItemID='%s'",$r3['ItemID']));
        if(isset($r3['bidderID']))
        {
            $f1 = mysql_query(
                sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
                $r3['bidderID'],
                $r3['item_name'],
                $r3['ItemID'],
                "BUY",
                sprintf("You have won the bidding for this item. Contact the <a href=\"pm.php?ID=%s&&expired_item=%s\">seller</a> for details",
                    $r3['userID'],
                    $r3['ItemID'])
                ),$con
            );
            $f2 = mysql_query(
                sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
                $r3['userID'],
                $r3['item_name'],
                $r3['ItemID'],
                "SELL",
                sprintf("<a href=\"pm.php?ID=%s&&expired_item=%s\">User</a> has won the bidding for your item. You are encouraged to contact each other",$r3['bidderID'],
                    $r3['ItemID'])
                ),$con
            );
        }
        else
        {
            $f1 = mysql_query(
                sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
                $r3['userID'],
                $r3['item_name'],
                $r3['ItemID'],
                "SELL",
                sprintf("Unfortunately no one bid on your item. You can view expired items from your userpage and re-upload",
                    $r3['userID'])
                ),$con
            );
        }
        mysql_free_result($q3);
    }
    $done = mysql_query("insert into ran_last values()");
}
mysql_free_result($q);
}
?>

I have it set up so that when you visit certain pages it will run immediately. Thing is it marks the items as expired before their time is up.

I dont thin its the strtotime function I ran this test program:

<!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>Test Time() strtotime()</title>
</head>
<body>
<?php
echo "<p>Now: ".time()."</p>\n";


echo "<p>Now: ".strtotime("now"), "</p>\n";
echo "<p>9/10/2000: ".strtotime("10 September 2000"), "</p>\n";
echo "<p>+1 day: ".strtotime("+1 day"), "</p>\n";
echo "<p>+1 week: ".strtotime("+1 week"), "\n";
echo "<p>+1 week 2 days 4 hours 2 seconds: ".strtotime("+1 week 2 days 4 hours 2 seconds"), "</p>\n";
echo "<p>next thursday: ".strtotime("next Thursday"), "</p>\n";
echo "<p>last monday: ".strtotime("last Monday"), "</p>\n";

echo "<p>space</p><p>space</p><p>space</p>\n";
echo "<p>2012-12-21: ".strtotime("2012-12-21")."</p>\n";
echo "<p>2013-1-1: ".strtotime("2013-01-01")."</p>\n";
echo "<p>2013-1-15: ".strtotime("2013-01-15")."</p>\n";
echo "<p>2013-1-15 without quotes: ".strtotime(2013-01-15)."</p>\n";
?>

</body>
</html>

and the result is:

Now: 1355416432

Now: 1355416432

9/10/2000: 968558400

+1 day: 1355502832

+1 week: 1356021232

+1 week 2 days 4 hours 2 seconds: 1356208434

next thursday: 1355979600

last monday: 1355115600

space

space

space

2012-12-21: 1356066000

2013-1-1: 1357016400

2013-1-15: 1358226000

2013-1-15 without quotes: 1355449020

looks ok from here.

I think I may have figured out the issue here, I'm waiting on a response from my other thread. Update: The code above works, but the date is reverting to 0000-00-00 which my check-items.php script picks up and marks expired, and delisting it making it appear as though nothing was entered.

Member Avatar for diafol

Looks like an 'I'll have a conversation with myself' thread.

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.