hi guys,

i just want to create a javascript confirm script if the file will overwrite the current file with the same filename or with a file already existing.

if yes: ask to overwrite
if no: back to edit file page

function overwrite()
{
var r=confirm("The same file name existing. Overwrite File?")
if (r==true)
    {
    document.write("<?php 

    // is this possible?

    ?>");
    alert("overwrite done");
  }
else
  {
  alert("You pressed Cancel!")
  }
}

</script>



$target = "files/";
    $target = $target . basename($_FILES['upfile']['name']);
    $vbasename = basename($_FILES['upfile']['name']);

if (empty($vbasename)) {

                $query = "UPDATE tablefile SET 
                                fld_title = '{$file_title}',
                                fld_tags = '{$content}',
                                fld_user = '{$vuser}',
                                fld_datetime = '{$vdatetime}'
                            WHERE ndex_fileid = {$id}";

                $result = mysql_query($query);                                                      

                if (mysql_affected_rows() == 1) {           

                    $message = "<div class=\"alert alert-success\">The File was successfully updated.</div>";

                } else {
                    $message = "<div class=\"alert alert-error\">The File could not be updated.</div>";
                    $message .= "<br />" . mysql_error();
                }
            } 

            if (!empty($vbasename)) {  //  IF THERE IS FILE TO UPLOAD

            /*  this script not working             
                echo "<script type='text/javascript'>test();</script>";
            */    
                $vrow = get_file_filepage($_GET['filepage']);

                $query = "UPDATE tablefile SET
                        fld_title = '{$file_title}',
                        fld_tags = '{$content}',
                        fld_user = '{$vuser}',
                        fld_datetime = '{$vdatetime}',
                        fld_filename = '{$vbasename}',
                        fld_filetype = '{$vfiletype}',
                        fld_filesize = '{$vfilesize}'
                    WHERE ndex_fileid = {$id}"; 

                if(!mysqli_query($con, $query)){
                    printf('Error ' . mysqli_error($con));
                }

                $result = mysql_query($query);

                move_uploaded_file($_FILES["upfile"]["tmp_name"],"server/php/files/" . $_FILES["upfile"]["name"]);

                $message = "<div class=\"alert alert-success\">New File: $vbasename, succesfully updated.</div>";
            }   
Member Avatar for LastMitch

i just want to create a javascript confirm script if the file will overwrite the current file with the same filename or with a file already existing.

@kanoy83

Does your code work meaning does it upload?

yes its working, only i want to use javascript Confirm

if yes, i can make same script to update the file and upload
if no, back to the page

thanks

Can you show the HTML form code?

@paulkd, sorry for delay hope you can help. thanks

Form code:

<form action="edit_filepage.php?filepage=<?php echo $sel_filepage['ndex_fileid']; ?>" method="post" enctype="multipart/form-data">
        <div class="textwrapper" >

        <strong>Title:</strong>

        <textarea name="file_title" rows="1" ><?php echo $sel_filepage['fld_title']; ?></textarea>
        <p><strong>Description:</strong><br />
            <textarea name="content" rows="3" ><?php echo $sel_filepage['fld_tags']; ?></textarea>
        </p>

        </div>
        <div class="box-upload">
            <label for="file">Choose New File to Upload:</label>

            <input type="file" name="upfile" id="upfile" > <br><br>
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            <input type="hidden" name="filepage" value="<?php echo $_GET['filepage']?>">  
            <input type="hidden" name="namecategid" value="<?php echo $sel_filepage['fld_categoryid']; ?> ">
        </div>    

        <br>
        <input type="submit" name="submit" value="Save" class="pure-button pure-button-primary">

        <a href="delete_filepage.php?filepage=<?php echo $sel_filepage['ndex_fileid']; ?>" onclick="return confirm('Are you sure you want to Delete this File?');" class="pure-button pure-button-error">Delete File</a>
    </form>
Member Avatar for LastMitch

@kanoy83

Does line 24 works?

<a href="delete_filepage.php?filepage=<?php echo $sel_filepage['ndex_fileid']; ?>" onclick="return confirm('Are you sure you want to Delete this File?');" class="pure-button pure-button-error">Delete File</a>

If so, then your javacript prompt should work the same?

Does that make sense?

@lastmitch
well my mysql update is same page as the form, i was hoping there will be small lines of code needed more to solve this. anyway, i will try to do the same in delete file as another php file.

thanks.

Member Avatar for LastMitch

i was hoping there will be small lines of code needed more to solve this.

@kanoy83

If you are going to used javascript with php with your code then it has to be inside the php tags.

The reason is once you submit the form, the button will display the prompt at, the same time it will insert the data.

Does that make sense?

You need an ajax call that will perform a php file_exists and return json true or false.

Your form should be prevented from being submitted via the submit button (and users pressing enter in one of the input fields).

The submit button should run the ajax and display the overwrite prompt if the ajax call returns true.

The form can be submitted using JavaScript.

I've added an id="upload-form" to your <form> tag.

upload-check.js

$("#upload-form").on("submit",function(){
    var filename = $("#upfile").val();
    if(filename=="") {
        alert("Please select a file");
        return false;
    } else {
        if ($("#upfile").data("exists")==1) {
            return confirm(filename+" already exists. OVERWRITE?");
        }
    }
});

$("#upfile").on("change",function(){
    checkExists($(this).val());
});

function checkExists(filename)
{
    var result;
    var request = $.ajax({
        type: "GET",
        url: '/ajax/check-file.php',
        dataType: "json",
        data: {filename: filename}
    })

    request.fail(function(jqXHR, textStatus){
        alert( "ajax request failed: " + textStatus );
    });

    request.done(function(data) {
        $("#upfile").data("exists",data);
    });

}

forgot the ajax file:- /ajax/check-file.php. Obviously where you store files is up to you.

<?php 
echo  file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/images/'.$_GET['filename']) ? json_encode(array(1)) : json_encode(array(0));
?>

@paulkd
thanks for the reply but
im a noob in javascript, where should i put id="upload-form"?
and what should i do with 'upload-check.js'?

i placed your code inside <script type="text/javascript">

note: my current code i provide is only 1 page.

please advise.
thanks a lot!

Can you show the whole page?

Hoping to finally close this :D thanks

<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<!-- ### test -->
<script type="text/javascript">
$("#upload-form").on("submit",function(){
    var filename = $("#upfile").val();
    if(filename=="") {
        alert("Please select a file");
        return false;
    } else {
        if ($("#upfile").data("exists")==1) {
            return confirm(filename+" already exists. OVERWRITE?");
        }
    }
});

$("#upfile").on("change",function(){
    checkExists($(this).val());
});

function checkExists(filename)
{
    var result;
    var request = $.ajax({
        type: "GET",
        url: '/ajax/check-file.php',
        dataType: "json",
        data: {filename: filename}
    })
    request.fail(function(jqXHR, textStatus){
        alert( "ajax request failed: " + textStatus );
    });
    request.done(function(data) {
        $("#upfile").data("exists",data);
    });
}
</script>

<script type="text/javascript">

// success
function success(){
    alert("New File UPDATED Successfully.");
}

// overwrite
function overwrite()
{
var r=confirm("The same file name existing. Overwrite File?")
if (r==true)
    {
    alert("overwrite done");
    //window.location = 'overwritefile.php';
    return true;
  }
else
  {
  alert("You pressed Cancel!")
  window.location = 'search.php';
  return false;
  }
}

</script>

<?php
    // make sure the category id sent is an integer
    if (intval($_GET['filepage']) == 0) {
        redirect_to('index.php');
    }

    include_once("includes/form_functions.php");

    // START FORM PROCESSING
    if (isset($_POST['submit'])) {
        // initialize an array to hold our errors
        $errors = array();

        // perform validations on the form data
        $required_fields = array('file_title', 'content');
        $errors = array_merge($errors, check_required_fields($required_fields));
        $fields_with_lengths = array('file_title' => 30);
        $errors = array_merge($errors, check_max_field_lengths($fields_with_lengths));

        // clean up the form data before putting it in the database
        $id = mysql_prep($_GET['filepage']);
        $file_title = trim(mysql_prep($_POST['file_title']));
        $content = mysql_prep($_POST['content']);
        $newdate = date("Y-m-d");
        $vuser = $_SESSION['username'];

    // #from upload_file    
        $target = "assets/files/";
        $target = $target . basename($_FILES['upfile']['name']);
        $vbasename = basename($_FILES['upfile']['name']);

        /* gets info from FORM */
        $currentDate = date("Y-m-d");
        $vdatetime = date("Y-m-d H:i:s",time());
        $upfile = ($_FILES['upfile']['name']); /* what for? */
        $veditfileid = mysql_prep($_POST['filepage']);

        $vfilename = ($_FILES['upfile']['name']);
        $vfiletype = $_FILES['upfile']['type'];
        $vfilesize = ($_FILES['upfile']['size'] / 1024);
        $vuser = $_SESSION['username'];
        $vcategoryid = mysql_prep($_POST['namecategid']);
    // #from upload_file end    

        $con = mysqli_connect("localhost", "username", "password", "database");

        if(mysqli_connect_errno()){
            echo "error connection" . mysqli_connect_error();
        }

        // CHECK IF NO ERRORS
        if(empty($errors)){

            // Database submission only proceeds if there were NO errors.
            if (empty($vbasename)) {
            // if (!isset($vbasename)) {

                //$message = "<div class=\"alert alert-success\">the file is empty, no file to upload.</div>";
                $query = "UPDATE table SET 
                                fld_title = '{$file_title}',
                                fld_tags = '{$content}',
                                fld_user = '{$vuser}',
                                fld_datetime = '{$vdatetime}'
                            WHERE ndex_fileid = {$id}";

                $result = mysql_query($query);

                // test to see if the update occurred
                if (mysql_affected_rows() == 1) {
                    // Success!

                    $message = "<div class=\"alert alert-success\">The File was successfully updated.</div>";
                    // echo "<script type='text/javascript'>success();</script>"; /not working                    
                    //echo "$row[5]";
                } else {
                    $message = "<div class=\"alert alert-error\">The File could not be updated.</div>";
                    $message .= "<br />" . mysql_error();
                }
            } // empty file to upload

            if (!empty($vbasename)) {  //  IF THERE IS FILE TO UPLOAD

                echo "<script type='text/javascript'>overwrite();</script>";  // NOT WORKING          

                $vrow = get_file_filepage($_GET['filepage']);

                $query = "UPDATE table SET
                        fld_title = '{$file_title}',
                        fld_tags = '{$content}',
                        fld_user = '{$vuser}',
                        fld_datetime = '{$vdatetime}',
                        fld_filename = '{$vbasename}',
                        fld_filetype = '{$vfiletype}',
                        fld_filesize = '{$vfilesize}'
                    WHERE ndex_fileid = {$id}"; 

                if(!mysqli_query($con, $query)){
                    printf('Error ' . mysqli_error($con));
                }

                $result = mysql_query($query);

                move_uploaded_file($_FILES["upfile"]["tmp_name"],"assets/files/" . $_FILES["upfile"]["name"]);

                $message = "<div class=\"alert alert-success\">New File: $vbasename, succesfully updated.</div>";

            }           

        } // empty errors

        else {
            if (count($errors) == 1) {
                $message = "<div class=\"alert alert-block\">There was 1 error in the form.</div>";
            } else {
                $message = "There were " . count($errors) . " errors in the form.";
            }
        }
    }// END FORM PROCESSING
?>

<?php find_selected_filepage(); ?>
<?php include("includes/header.php"); ?>

<!-- HEADER -->
<div class="header">
    <h2><strong>File Information</strong></h2>
</div>

<div class="pure-g-r marketing-ribbon">
<div class="pure-u-1-2">
    <div class="l-box" id="filepage">  

  <!-- SHOW MESSAGE  -->
  <?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
  <?php if (!empty($errors)) { display_errors($errors); } ?>

  <div class="form-box-2">
  <aside><strong>TITLE: <?php echo $sel_filepage['fld_title']; ?></strong></aside>
  <?php // SHOWING CURRENT CATEGORY              
      $categoryid = $sel_filepage['fld_categoryid'];      
      $querycat = mysql_query("SELECT cat_name FROM categs WHERE id = $categoryid ", $connection);
      WHILE($datacat = mysql_fetch_array($querycat)){
          $categoryname = $datacat['cat_name'];             
      }
  ?>
    <br>  
    <strong>File No: <?php echo $sel_filepage['ndex_fileid']; ?></strong><br>
    <strong>Category: <?php echo $categoryname; ?></strong>

  <?php
      /* SHOWING DATA FROM TABLE */
      $filepageid = $sel_filepage['ndex_fileid'];
      $queryfileinfo = mysql_query("SELECT * FROM table WHERE ndex_fileid = $filepageid",$connection);                  
          while($datafinfo = mysql_fetch_array($queryfileinfo))
          {
              $file_id = $datafinfo['ndex_fileid'];
              $filetype = $datafinfo['fld_filetype'];
              $filesize = $datafinfo['fld_filesize'];
              $dateuploaded = date("j.F.Y, H:i", strtotime($datafinfo['fld_datetime']));
              $origdateshow = date("j.F.Y, H:i", strtotime($datafinfo['fldorigdate']));
              $vtitle = $datafinfo['fld_title'];
              $origuser = $datafinfo['fldoriguser'];
          }
    ?>

  <!-- GETTING THE UPLOADED FILE LINK -->
  <?php $row = get_file_filepage($_GET['filepage']); ?>

  <p><strong>File Name: </strong>
      <a href="assets/files/<?php /*link of actual file, but [5] maybe means column array [5] is FILENAME*/ echo $row[5]; ?>">
      <?php /*showing filename*/ echo $row[5]; ?></a>
  <br />                             
  <strong>File Type: </strong>
  <?php 
      if(empty($filetype)){     
            echo "(No file)";
      } else{
          echo $filetype; 
      }
  ?>
  <br /> 
  <strong>File Size: </strong>
  <?php
      if(empty($filesize)){
          echo "(No file)";
      } else
      echo "$filesize" . " KB";
  ?>
  <br>
  <strong>Updated By:</strong> <?php echo $_SESSION['username']; ?>
  <br>
  <strong>Date Modified:</strong>
  <?php 
      if(empty($dateuploaded))
      {
          echo "(No file)";
      } else
      {
          echo $dateuploaded . " Hrs";
      }    
  ?>
  </p><hr>

  <br><strong>Created By:</strong> <?php echo $origuser; ?>
  <br><strong>Date Created:</strong> <?php echo $origdateshow . " Hrs"; ?>
  <hr>

    <!-- ####################### F O R M ######################-->
    <form action="edit_filepage.php?filepage=<?php echo $sel_filepage['ndex_fileid']; ?>" method="post" enctype="multipart/form-data">
        <div class="textwrapper" >       

        <strong>Title:</strong>
        <!-- <input type="text" name="file_title" value="<?php echo $sel_filepage['fld_title']; ?>" id="file_title" />-->

        <textarea name="file_title" rows="1" ><?php echo $sel_filepage['fld_title']; ?></textarea>
        <p><strong>Description:</strong><br />
            <textarea name="content" rows="3" ><?php echo $sel_filepage['fld_tags']; ?></textarea>
        </p>

        </div>
        <div class="box-upload">
            <label for="file">Choose New File to Upload:</label>

            <input type="file" name="upfile" id="upfile" > <br><br>
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            <input type="hidden" name="filepage" value="<?php echo $_GET['filepage']?>">  <!-- VALUE IS IMPORTANT -->
            <input type="hidden" name="namecategid" value="<?php echo $sel_filepage['fld_categoryid']; ?> ">
        </div>    
        <!--  <input type="submit" name="upload" value="Upload" class="pure-button pure-button-success"> -->
        <br>
        <input type="submit" name="submit" value="Save" class="pure-button pure-button-primary">

        <a href="delete_filepage.php?filepage=<?php echo $sel_filepage['ndex_fileid']; ?>" onclick="return confirm('Are you sure you want to Delete this File?');" class="pure-button pure-button-error">Delete File</a>
    </form>
</div>
</div> <!-- lbox -->
</div> <!-- pure u12 -->
</div> <!-- marketing -->
<?php include("includes/footer.php"); ?>

Thanks for posting your code, it gives me a better view of your setup.

We'll take it one step at a time. First you need to create a php file that will check for the existence of a specified file in your assets/files folder.

Here is the php code. Place it where you want and test that it works.
I like to have an ajax folder - e.g.
www.website.com/ajax/check-file.php?filename=image25.jpg

<?php 
echo  file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/files/'.$_GET['filename']) ? json_encode(array(1)) : json_encode(array(0));
?>

@paulkd

i have now created the file check-file.php and placed inside ajax folder

what shall i do next?

thanks

have you run it as I described?

i tried to place the the code in my edit_filepage.php, no errors, even if i update the file.

BUT when i run independently the checkfile.php, there is an error:
undefine index filename
even if i add includes of
<?php include 'includes/connection.php'; ?>
<?php include 'includes/functions.php'; ?>

still there is error and a lot more:
Warning: include(includes/connection.php): failed to open stream: No such file or directory in C:\xampp\htdocs\test\fileprogram\ajax\checkfile.php on line 2 Warning: include(): Failed opening 'includes/connection.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\test\fileprogram\ajax\checkfile.php on line 2

my code is:

<?php include 'includes/connection.php'; ?>
<?php include 'includes/functions.php'; ?>

<?php 
    echo file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/files/'.$_GET['filepage']) ? 
    json_encode(array(1)) : json_encode(array(0));
?>

Remove the two includes.

I notice the code you have displayed is using $_GET['filepage'] instead of my $_GET['filename'].
This is not an issue, as obviously you called
www.website.com/ajax/check-file.php?filepage=image25.jpg

After removing the includes, please rerun and copy/paste here the actual error that is displayed.

4 lines of code, testing checkfile.php page only
the error is:

Notice: Undefined index: filepage in C:\xampp\htdocs\test\fileprogram\ajax\checkfile.php on line 2 [0]

Thanks

Did you append the ?filepage=image25.jpg to your checkfile.php ?

hi paulkd, sorry i didnt see this page 2, i thought no reply, i will try now. tnx a lot

localhost/test/fileprogram/ajax/checkfile.php?filepage=image25.jpg

result: (no error)
[0]

Now place an image25.jpg into your /assets/files folder and rerun.

i place a copy of image25.jpg in the same folder in my assets and run, result is: [0]
localhost/test/fileprogram/ajax/checkfile.php?filename=image25.jpg

-i tried fix the edit_file.php with the script of
function checkExists(filename) you gave me before, as shown in my previous post with the whole code.
- change filepage to filename as the same in your function.

do you have localhost/test/fileprogram/assets/files/image25.jpg ?

yes i have

Let's pick one and stick with it:-

  1. filename or
  2. filepage

?

i will stick with your 'filename', is this related to your
function checkExists(filename) ?

and should i add id="upload-form" to my <form> tag ? i tried to add and rerun the checkfile.php still the same output.

I want to get the ajax filechecker working first.

Change localhost/test/fileprogram/ajax/checkfile.php to

<?php echo  $_SERVER['DOCUMENT_ROOT'];  ?>

Run and paste the results here please.

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.