Asked  2 Years ago    Answers:  5   Viewed   170 times

Okay so here's the scenario:

User is presented with form that contains file inputs. User submits form. Form does not pass validation/verification for one reason or another. User is presented form with errors highlighted. File inputs are now blank.

Question:

Is it possible to re-populate the file inputs with the paths to the files the user originally selected. A PHP solution would be ideal, but I'm also open to JavaScript solutions as well.

 Answers

5

I think the short answer here is no. You can't repopulate file upload fields. However, you can work around it.

If a file has been selected and the form submitted, then you've already received the file. What you can do is keep a reference to the file on disk and put that in a hidden field and show a message to indicate to the user you still have their file uploaded so it does not need to be replaced/re-uploaded. When your form gets submitted again without a file, you can check for the hidden field value and use that to get your local copy of the file they uploaded in their last attempt.

The other way to do this is to either submit the form via ajax (using either flash or the iframe method for the file upload) or to do an ajax call to validate the form first, and then only submit as normal if valid (thus no form reload, no loss of file upload field data).

Monday, August 15, 2022
3

move_uploaded_file returns true on success, the remaining elseif are never reached. Try something like this:

$error = false;

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))  
{   
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";  
} else $error = true;

if(move_uploaded_file($_FILES['photo1']['tmp_name'], $target1))  
{   
echo "The 2 file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";  
} else $error = true; 

if(move_uploaded_file($_FILES['photo2']['tmp_name'], $target2))  
{   
echo "The 3 file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";  
} else $error = true;

if($error)
   echo "Sorry, there was a problem uploading your file.";
Friday, November 25, 2022
1

Solved after reading this post: Uploading multiple files asynchronously by blueimp jquery-fileupload

All it was needed was to save the input field name into a 'paramNames' variable to send it alongside the 'filesList' variable.

Updated working code:

var imageUpload = {
init: function (selector, context, options) {

    selector = selector || '.file-upload';
    context = context || $('.entry_form');

    var filesList = [],
        paramNames = [];
    var url = site_url + '/doUpload';

    $(selector, context).fileupload(options || {
        url: url,
        type: 'POST',
        dataType: 'json',
        autoUpload: false,
        singleFileUploads: false,
        add: function (e, data) {
            for (var i = 0; i < data.files.length; i++) {
                filesList.push(data.files[i]);
                paramNames.push(e.delegatedEvent.target.name);
            }

            return false;
        },
        change: function (e, data) {

        },
        done: function (e, data) {

        }

    });
    $('#save_btn').click(function (e) {
        e.preventDefault();

        $(selector, context).fileupload('send', {files:filesList, paramName: paramNames});
    });
}
};
Wednesday, November 16, 2022
 
2

File reads using "file_get_contents" ignore any file locking. In practice, "file_get_contents" reads up to the end of the file (if you're writing to it at that time, it reads what it can get and returns that).

File reads using "fread" or "fgets" would do the same but you can use "flock" first to make sure the file is not locked, but there's still chance for a racing condition.

The biggest problem you're actually facing is that not all linux servers will support it as "flock" uses system calls that are "advisory" and therefore simply ignored (by not locking any file) on some servers. That's where database servers like SQLite or MySQL come in by providing their own locking mechanisms that don't depend on the server and - most of the time - are smarter too when it comes to avoiding racing conditions that might break your flatfile database.

Monday, September 26, 2022
 
5

Martin Brandl's answer provides an elegant and effective solution, but it's worth digging deeper:

PowerShell's -replace operator (... -replace <search>[, <replace>]):

  • Takes a regular expression as its first operand, <search> (the search expression), and invariably matches globally, i.e., it replaces all matches.

  • Specifying a replacement expression, <replace>, is optional, in which case the empty string is substituted for what <search> matched, resulting in its effective removal.

    • 'bar' -replace '[ra]' -> 'b'
  • If <replace> is specified, it supports two forms:

    • v6.1+ (PowerShell Core only): A script block ({ ... }) as the replacement operand, which offers fully dynamic calculation of the replacement string on a per-match basis - see this answer for an example.

      • 'bar' -replace '[ra]', { '{' + $_.Value + '}' } -> 'b{a}{r}'
    • A string containing an expression that can reference what the regular expression captured (and didn't capture) - such as $& to refer to what was matched - explained in detail below.

      • 'bar' -replace '[ra]', '{$&}' -> 'b{a}{r}'
  • -replace matches case-insensitively (and can also be written as -ireplace); to perform case-sensitive matching, use the form -creplace.


The "replacement language" for referencing regex captures in a string-typed <replace> operand is itself not a regular expression - no matching happens there, only references to the results of the regex matching are supported, via $-prefixed placeholders that are not to be confused with PowerShell variables.

  • PowerShell's documentation (now) briefly explains the syntax of replacement strings in its conceptual about_Comparison_Operators help topic.

  • For the full picture, refer to the Substitutions in Regular Expressions .NET framework help topic, which is applicable because PowerShell's -replace uses the Regex.Replace() method behind the scenes.

For convenience, here are the references supported in the <replace> string (excerpted from the page linked above, with emphasis and annotations added):

  • $number (e.g., $1) ... Includes the last substring matched by the capture group that is identified by the 1-based number, where number is a decimal value, in the replacement string.

    • Annotations:
      • Including (...), a parenthesized subexpression, in the regex implicitly creates a capture group (capturing group). By default, such capture groups are unnamed and must be referenced by their 1-based (decimal) index reflecting the order in which they appear in the regex, so that $1 refers to what the 1st group in your regex captured, $2 to what the 2nd captured, ...

      • The form ${number} (e.g., ${1}) for disambiguation of the number is also supported (e.g., to make sure that $1 is recognized even if followed by, say, 000, use ${1}000).

      • Instead of relying on indices to refer to unnamed capture groups, you can name capture groups and refer to them by name - see next point.

      • If you're not interested in what the capture group matched, you can opt to ignore it by turning it into a non-capturing group with (?:...).

  • ${name} ... Includes the last substring matched by the named group that is designated by (?<name>...) in the replacement string.

  • $$ ... Includes a single "$" literal in the replacement string.

  • $& ... Includes a copy of the entire match in the replacement string ($0 works too, even though it isn't directly documented).

  • $` ... Includes all the text of the input string before the match in the replacement string.

  • $' ... Includes all the text of the input string after the match in the replacement string.

  • $+ ... Includes the last group captured in the replacement string. [This relieves you of the need to know the last group's specific index.]

  • $_ ... Includes the entire input string in the replacement string.

Finally, note that:

  • -replace invariably matches globally, so if the input string contains multiple matches, the replacements above apply to each match.

  • It is generally preferable to use '...' (single quotes) for both the regex and the replacement string, because single-quoted strings are non-expanding (non-interpolating), and therefore avoid confusion with PowerShell's own up-front expansions of $-prefixed tokens and interpretation of ` chars.
    If you do need to include a PowerShell variable, you have three options:

  • Use "..." (expanding strings) and `-escape $ instances that are meant for the regex engine; e.g., `$1 in the following example:
    'abc' -replace '(a)', "[`$1]-$HOME-", which yields something like [a]-C:Usersjdoe-bc

  • Build your string from literal pieces and variable references using string concatenation (+); e.g.:
    'abc' -replace '(a)', ('[$1]-' + $HOME + '-')

  • Use -f, the string-formatting operator string concatenation; e.g.:
    'abc' -replace '(a)', ('[$1]-{0}-' -f $HOME)

  • Given that you need to use $$ to escape a literal $ in the replacement string, use the following idiom to use a variable whose value you want to use literally:

    • ... -replace <search>, $var.Replace('$', '$$')
    • This relies on the [string]::Replace() method performing literal substring replacements.
      On a side note, this method is an alternative to -replace in simple cases, but note that it is case-sensitive by default.
    • Alternatively, use a nested -replace call, but the syntax is tricky due to the escaping requirements:
      ... -replace <search>, ($var -replace '$', '$$$$')
Thursday, September 8, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 

Browse Other Code Languages