问题描述:

I have a problem where everytime I refresh the browser, I want the array which contians a $_SESSION variable to go back to being blank. At moment lets say I uploaded 2 files and then refresh browser, when I upload another file, it shows the name of the previous files uploaded when it shouldn't. How can I get the array and session variable to go back to being blank if browser is refreshed?

Below is code:

 function stopImageUpload(success){

var imageNameArray = new Array();

// WHEN PAGE IS REFRESH, ARRAY SHOULD GO BACK TO BEING BLANK

imageNameArray = <?php echo json_encode(isset($_FILES ['fileImage']['name']) ? $_FILES ['fileImage']['name'] : null); ?>;

//RETRIEVES THE SESSION VARIABLE FROM THE PHP SCRIPT OF THE FILE NAMES WHICH HAVE BEEN UPLOADED

var result = '';

if (success == 1){

result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';

for(var i=0;i<imageNameArray.length;i++) //LOOP THROUGH ALL UPLOADED FILE NAMES

{

$('.listImage').append(imageNameArray[i]+ '<br/>');//APPEND FILE NAME

}

}

else {

result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';

}

return true;

}

Below is the php script where it uploads a file which is on another page from the javascript function above:

<?php

session_start();

$result = 0;

$errors = array ();

$dirImage = "ImageFiles/";

if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {

$fileName = $_FILES ['fileImage'] ['name'];

$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );

$fileExt = strtolower ( $fileExt );

$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;

if (count ( $errors ) == 0) {

if (move_uploaded_file ( $fileTemp, $fileDst )) {

$result = 1;

}

}

}

?>

<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>

网友答案:

Although I agree with the comment of @Reza Sanaie, you can solve your particular problem by unsetting the variable after a successful upload:

     if (success == 1)
     {
         result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';

         for(var i=0;i<imageNameArray.length;i++)  //LOOP THROUGH ALL UPLOADED FILE NAMES
         {
             $('.listImage').append(imageNameArray[i]+ '<br/>');//APPEND FILE NAME

         }

         $_SESSION ['fileImage'] = NULL; // or use unset()
     }
网友答案:

After the form is submitted and your PHP has done its work you need to do a 303 redirect to the page you wish to display. Then when a user refreshes the page you won't a second form submission.

For example:

header('Location: ' . $_SERVER['PHP_SELF'], true, 303);
网友答案:

Just do your error checking in PHP, and pass an array to your HTML page to display the list of uploaded files in the page. You don't need javascript.

Have a look at How to upload files in PHP

相关阅读:
Top