Jump to content

Can I prevent form reset when move_uploaded_file fails??


kristo5747

Recommended Posts

Greetings!

 

PHP noob here. I am self taught so don't bother telling my code is crap. I know ;).

 

I have created a form-based app that allows users to capture data into a mysql db and upload files to my Apache web server.

 

It works pretty good except for one thing.

 

The other day, my sysadmin revoked the permissions on the upload directory. When a user tried to upload a file,  move_uploaded_file() returned false, I poped up a Javascript alert and the form fields got automatically reset. The user's data entry in my form's text boxes got immediately blanked out. Gone.

 

I put a test in case something goes wrong with the upload process but did not code anything to reset the fields.

 

        //////--move_uploaded_file --//////
if(!move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
            echo "<html><body style=\"background-color:#0080c0\">
            <script type=\"text/javascript\" language=\"javascript\">alert(\"Error...please try again!\");</script>
            </body></html>";
        }

 

Is there a way to prevent this from happening??

 

My code is below///

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?php
//Needed to persist session information.
session_start();
?>
<HTML>
    <head>
        <title>Service & Repair</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="../css/webform.css" type="text/css" rel="stylesheet" media="screen">
...
    </head>
    <body><div id="header">
            <table border="0" cellspacing="10" cellpadding="10">
                <tbody><tr>
                        <td align="center" valign="center"><B>SERVICE AND REPAIR: DEVELOPMENT REQUEST</B></td>
                        <td align="center" valign="center"><a class="logout" href="../acc/logout.php">Logout</a></td>
                        <td align="center" valign="center"><a class="smallclass" href="#" onclick="javascript:formhelp();return false;">Help</a></td>
                    </tr></tbody></table>
        </div><hr>
        <form enctype="multipart/form-data" method="post" name="webform"  onsubmit="return validate(this)" 
action="<?php echo $_SERVER['PHP_SELF'];?>">
            <h2>Title of request:</h2>
            <input type="text" tabindex="0" name="request_title" maxlength="255" size="62"><br><br>
            <h2>Please describe your request in detail:</h2><br>
            <textarea tabindex="1"  name="request_description" cols="87" rows="10"></textarea>
            <table border="0" cellspacing="3" cellpadding="3">
                <tbody>
                    <tr><td><fieldset id="output"><legend>Output Options: </legend>
                                <input type="checkbox" tabindex="2" id="chb0" name="check_output[]" value="CSV">CSV<br>
                                <input type="checkbox" tabindex="3" id="chb1" name="check_output[]" value="Excel">Excel<br>
                                <input type="checkbox" tabindex="4" id="chb2" name="check_output[]" value="Email">Email<br>
                                <input type="checkbox" tabindex="5" id="chb3" name="check_output[]" value="HTML">HTML<br>
                                <input type="checkbox" tabindex="6" id="chb4" name="check_output[]" value="None">None<br>
                                <input type="checkbox" tabindex="7" id="chb4" name="check_output[]" value="PDF">PDF<br>
                            </fieldset></td>
                        <td><fieldset> <legend>Frequency: </legend>
                                <input type="radio" id="rad0" tabindex="8" name="Frequency" value="One Time">One Time<br>
                                <input type="radio" id="rad1" tabindex="9" name="Frequency" value="Daily">Daily<br>
                                <input type="radio" id="rad2" tabindex="10" name="Frequency" value="Weekly">Weekly<br>
                                <input type="radio" id="rad3" tabindex="11" name="Frequency" value="Monthly">Monthly<br>
                                <input type="radio" id="rad4" tabindex="12" name="Frequency" value="Ongoing">Ongoing<br>
                            </fieldset></td>
                        <td><fieldset> <legend>Request Type: </legend>
                                <table border="0" cellspacing="3" cellpadding="3">
                                    <tbody>
                                        <tr>
                                            <td><fieldset id="myfieldset"> <legend>Data: </legend>
                                <input type="radio" id="req0" tabindex="13" value="Add Data" name="request_type">Add<br>
                                <input type="radio" id="req1" tabindex="14" value="Extract Data" name="request_type">Extract<br>
                                <input type="radio" id="req5" tabindex="15" value="Update Data" name="request_type">Update<br>
                                <input type="radio" id="req4" tabindex="16" value="Validate Data" name="request_type">Validate<br>
</fieldset></td>
                                            <td><fieldset id="myfieldset"> <legend>Report: </legend>
                                <input type="radio" id="req3" tabindex="17" value="New Report" name="request_type">New<br>
                                <input type="radio" id="req2" tabindex="18" value="Modify Report" name="request_type">Modify<br>
</fieldset></td>
                                            <td><fieldset id="myfieldset"> <legend>Table: </legend>
                                <input type="radio" id="req3" tabindex="19" value="New Table" name="request_type">New<br>
                                <input type="radio" id="req3" tabindex="19" value="Modify Table" name="request_type">Modify<br>
</fieldset></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </fieldset></td>
                        <td><fieldset>
                                <legend>Datasource Name</legend>
                                <select tabindex="19" name="DBrequestor" >
                                    <?php
                                     ...
                                    $result = mysql_query($sqlconf["data_sources"]);
                                    while($row = mysql_fetch_array($result)) {
                                        ?>
                                    <option value="<?php echo $row['ds_name']; ?>"><?php echo $row['ds_name'];?></option>
                                        <?php
                                    }
                                    mysql_close($con);
                                    ?>
                                </select></fieldset></td>
                        <td>
                            <fieldset><legend>Due by: (use mm/dd/yyyy format)</legend>
                                <input tabindex="21" type="text" name="due_by" value="" size=25>
                                <a href="#"
                                   onClick="cal.select(document.forms['webform'].due_by,'anchor1','MM/dd/yyyy'); return false;"
                                   name="anchor1" id="anchor1">
                                    <img src="http://c....com/images/calendar.gif" alt="Click here to pick a due by date"/>
                                </a>
                            </fieldset>
                            <fieldset><legend>File Attachment (1 MB Maximum size): </legend>
                                <input tabindex="22" type="file" name="myfile"><br>
                            </fieldset></td></tr>
                </tbody>
            </table>
            <br>
            <input type="hidden" value="Created" name="status">
            <input type="submit" id="sd" tabindex="23" value="submit" name="submit">
            <input type="reset" id="rs"  tabindex="24"  name="reset" value="reset">
        </form>
    </body>
</HTML>

<?php

//Includes the db, email config files
$dbconf = include '../config/dbConfig.php';
$mailheader = include '../config/emailConfig.php';

//Needed to persist session information.
session_start();

//if no user, send back to index page.
if (empty($_SESSION['user']) || empty($_SESSION['pass'])) {
    header( "Location: ../index.html" );
}

//checks if fields are set.
if(isset($_POST['submit'])) {

    if(
    !empty($_POST['request_title'])
            && !empty($_POST['request_description'])
            && !empty($_POST['request_type'])
            && !empty($_POST['Frequency'])
            && !empty($_POST['DBrequestor'])
            && !empty($_POST['due_by'])
    ) {
        submit();
    } else {
        echo "<html><body style=\"background-color:#0080c0\">
            <script type=\"text/javascript\" language=\"javascript\">alert(
            'Nothing to do.'
            + '\\n\\n' + 'Please see Online Help (top right corner) for more information'
            + '.');</script> </body></html>";
    }
}



function submit() {

    /*
* Grabs $dbconf and declares variables.
    */
    global $dbconf;
    global $mailheader;


    $request_title_field = $_POST['request_title'];
    $request_description = $_POST['request_description'];
    $request_type = $_POST['request_type'];
    $frequency  = $_POST['Frequency'];
    $DBrequestor = $_POST['DBrequestor'];
    $created_date = date(DATE_RFC822);
    $due_by = validateDueBy($_POST['due_by']);
    $status = $_POST['status'];

    //nulls out attachment field
    $pic = "";

    //checks if attachment field is set -- optional entry
    if(isset($_FILES['myfile']['name']) && !empty($_FILES['myfile']['name'])) {
        //where attchments are going
        $target_path = "upload/";

        $target_path = $target_path . basename( $_FILES['myfile']['name']);

        //////--move_uploaded_file --//////
if(!move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
            echo "<html><body style=\"background-color:#0080c0\">
            <script type=\"text/javascript\" language=\"javascript\">alert(\"There was an error uploading the file, please try again!\");</script>
            </body></html>";
        }

        //sets attached file name to target directory
        $pic = basename( $_FILES['myfile']['name']);
    }

    //sets output options
    foreach($_POST['check_output'] as $value_output) {
        $check_output_msg .= "$value_output\n";
    }

    /*
* connect to database
    */
    $con = mysql_connect($dbconf["host"], $dbconf["user"],$dbconf["password"]) ;
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db($dbconf["db"], $con) or die ("Couldn't select the database.");


    /*
* Get request author
    */
    $getrequestor = mysql_query("select wu.username requester from webusers wu,users u
        where wu.email=u.email and u.username='" . $_SESSION['user'] ."'");

    while($row = mysql_fetch_array($getrequestor)) {
        $requestor= $row['requester'];
    }


    /*
     * Cleanup - remove double quotes & singles quotes
    */

    $request_title_field = addslashes($request_title_field);
    $_POST[request_title] = addslashes($_POST[request_title]);

    $request_description = addslashes($request_description);
    $_POST[request_description] = addslashes($_POST[request_description]);

    //The MySQL date format is actually YYYY-MM-DD ;
    //STR_TO_DATE function is used to morph UI date format into that of RDBMS.
    $sql = "INSERT INTO webcases
(caseid,request_title, request_description, output_options, frequency, request_type,
requestor,assigned_to,datasource,created_on,due_by,status,file_name)
VALUES(
'',
'$_POST[request_title]',
'$_POST[request_description]',
'$check_output_msg',
'$_POST[Frequency]',
'$_POST[request_type]',
'$requestor',
'',
'$_POST[DBrequestor]',
CURDATE( ),
STR_TO_DATE('$_POST[due_by]','%m/%d/%Y'),
'$_POST[status]',
'$pic'
)";

    if (!mysql_query($sql,$con)) {
        die('Error: ' . mysql_error());
    }
    /*
* Notification message to user with request number.
    */
    echo "<html><body style=\"background-color:#0080c0\">
            <script type=\"text/javascript\" language=\"javascript\">alert(\"The request number is: " . mysql_insert_id() . ".\");</script>
            </body></html>";

    ///////////////////// EMAIL CODE /////////////////////
    $fileatt = $target_path;
    $fileatt_type = $_FILES['myfile']['type'];
    $fileatt_name = $fileatt. ($_FILES['myfile']['name']);

    /*
* Body of email message to be sent out
    */
    if(empty($pic)) {
        $body =
                "Request Title:\n $request_title_field "."<br><br>"."
Request Description:\n $request_description "."<br><br>"."
Output Options:\n $check_output_msg "."<br><br>"."
Frequency:\n $frequency "."<br><br>"."
Request Type:\n $request_type "."<br><br>"."
Requester:\n $requestor "."<br><br>"."
Datasource Name:\n $DBrequestor "."<br><br>"."
Created On:\n $created_date "."<br><br>";
    } else {
        $body =
                "Request Title:\n $request_title_field "."<br><br>"."
Request Description:\n $request_description "."<br><br>"."
Output Options:\n $check_output_msg "."<br><br>"."
Frequency:\n $frequency "."<br><br>"."
Request Type:\n $request_type "."<br><br>"."
Requester:\n $requestor "."<br><br>"."
Datasource Name:\n $DBrequestor "."<br><br>"."
Created On:\n $created_date "."<br><br>"."
Attachment:\n $pic"."<br><br>" ;
    }

    //Creates header for email message
    $headers =
            $mailheader["from"] . "\r\n" .
            $mailheader["reply"] . "\r\n" .
            $mailheader["carboncopy"] . "\r\n" .
            $mailheader["blindccopy"] . "\r\n" .
            $mailheader["version"] ;

    //Loads the file before chunking it
    $file = fopen($fileatt,'rb');
    $data = fread($file,filesize($fileatt));
    fclose($file);

    //Gets the file name to attach
    $fileatt_name = substr($fileatt_name, strlen($fileatt));

    //create a boundary string. It must be unique
    //so we use the MD5 algorithm to generate a random hash
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    //add boundary string
    $headers .= "\nMIME-Version: 1.0\n" .
            "Content-Type: multipart/mixed;\n" .
            " boundary=\"{$mime_boundary}\"";

    //add mime type specification
    $email_message .= "This is a multi-part message in MIME format.\n\n" .
            "--{$mime_boundary}\n" .
            "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
            "Content-Transfer-Encoding: 7bit\n\n" .
            $email_message . "\n\n";

    //read the atachment file contents into a string,
    //encode it with MIME base64,
    //and split it into smaller chunks
    $data = chunk_split(base64_encode($data));

    //add form data to email message
    $email_message .= $body. "\n\r";

    //attaches file name (& file type) to email message
    $email_message .= "--{$mime_boundary}\n" .
            "Content-Type: {$fileatt_type};\n" .
            " name=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
            $data . "\n\n" .
            "--{$mime_boundary}--\n";


    /*
* Get requestor's email address to cc development request.
    */
    $getemail = mysql_query("select email from users where username='" . $_SESSION['user'] ."'");

    while($row = mysql_fetch_array($getemail)) {
        $email= $row['email'];
    }

    $to = $email;
    $subject = "Service & Repair: Development Request" . " " . mysql_insert_id();

    $ok = @mail($to, $subject, $email_message, $headers);

    if (!$ok) {
        echo "<html>
<body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Mail could not be sent!\");</script>
</body>
</html>";
    }

    /*
* Notification page
    */
    echo "<html>
<body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Your development request has been submitted. Click BACK on your browser or Exit.\");</script>
</body>
</html>";

    mysql_close($con);

}

function validateDueBy($due_by) {
    //Regex verification for mm/dd/yyyy pattern.
    if(ereg('^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$', $due_by)) {
        //return true;
        $due_by = date("m/d/Y", strtotime($due_by));
        return $due_by;
    }
    else
    //return false;
        echo "<html>
<body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Invalid date format! Use mm/dd/yyyy format. Your request could not be submitted. Click the BACK arrow & try again!\");</script>
</body>
</html>";
    exit;
}
?>

Link to comment
Share on other sites

Can you please elaborate? Are you saying that I should echo the whole page with the POST values back into their respective form fields like so

 

echo 
'
<HTML>
    <head>
...
        <link href="../css/webform.css" type="text/css" rel="stylesheet" media="screen">
        <script type="text/javascript" language="javascript" ...</script>
    </head>
    <body>...
        <form enctype="multipart/form-data" method="post" name="webform"  onsubmit="return validate(this)" 
action="<?php echo $_SERVER['PHP_SELF'];?>">
...
            <input type="text" tabindex="0" name="request_title" maxlength="255" size="62" value=' 
. $_POST['request_title'] .'><br><br>
...
            <textarea tabindex="1"  name="request_description" cols="87" rows="10" 
value='
. $_POST['request_description'] '. </textarea>
...
            <br>...
            <input type="submit" id="sd" tabindex="23" value="submit" name="submit">
            <input type="reset" id="rs"  tabindex="24"  name="reset" value="reset">
        </form>
    </body>
</HTML>
';

???

Link to comment
Share on other sites

Not the whole page. Just the form vars.

 

<HTML>
    <head>
...
        <link href="../css/webform.css" type="text/css" rel="stylesheet" media="screen">
        <script type="text/javascript" language="javascript" ...</script>
    </head>
    <body>...
        <form enctype="multipart/form-data" method="post" name="webform"  onsubmit="return validate(this)" 
action="<?php echo $_SERVER['PHP_SELF'];?>">
...
            <input type="text" tabindex="0" name="request_title" maxlength="255" size="62" value='<?php echo $_POST['request_title'];?>' ><br><br>
...
            <textarea tabindex="1"  name="request_description" cols="87" rows="10"><?php echo $_POST['request_description']; ?></textarea>
...
            <br>...
            <input type="submit" id="sd" tabindex="23" value="submit" name="submit">
            <input type="reset" id="rs"  tabindex="24"  name="reset" value="reset">
        </form>
    </body>
</HTML>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.