Delay execution while file uploading

社会主义新天地 提交于 2019-12-25 02:53:52

问题


My form uploads a file to be added to a mail created with PHPMailer.

Unfortunately, the mail isn't being sent and I think that might be because it's being sent too soon in execution. So what I wanted to do was to add in a small loop to effectively pause further execution until the file has been uploaded:

while (!move_uploaded_file($_FILES['upload'][$first_name.' CV'], $target_path))
{
    sleep(1);

    if (move_uploaded_file($_FILES['upload'][$first_name.' CV'], $target_path))
    {
        echo "The file ".  basename( $_FILES['upload'][$first_name.' CV'])." has been uploaded";
    }
    else
    {
        echo "There was an error uploading the file, please try again!";
    }
}

This is what I've come up with but I'm not exactly sure what it's doing here.

Please clarify on the following for me:

  1. Is the declaration of !move_uploaded_file... uploading the file at the start of the loop?
  2. If yes, is the file being uploaded on every iteration through the loop?
  3. Is the declaration of move_uploaded_file... in the if statement within the loop also uploading the file or is it just checking that the file has been uploaded?
  4. What's the best way to handle this sort of thing? I'm sure this isn't it...

Thanks in advance!


回答1:


The PHP script will not execute before the file upload is finished. You are trying to solve the wrong problem.

The web server handles the request, which includes handling and waiting for the file data to upload. Only after the complete request has been received by the web server will it invoke your PHP script. (That is, unless you're using some unusual web server.) Anything present in $_FILES is guaranteed to be there now.




回答2:


  1. Yes, well it is moving the file anyway. Once it has moved the file I guess it will return false.
  2. Yes it is trying to move the file on every iteration
  3. This is also trying to move the file. You are executing the method not declaring it.
  4. move_uploaded_file is a synchronous call. Just use this code below, it will enter the if statement if the file was uploaded successfully. I am guessing this is a red herring for your issue

code:

if (move_uploaded_file($_FILES['upload'][$first_name.' CV'], $target_path))
{
    echo "The file ".  basename( $_FILES['upload'][$first_name.' CV'])." has been uploaded";
}
else
{
    echo "There was an error uploading the file, please try again!";
}


来源:https://stackoverflow.com/questions/15110103/delay-execution-while-file-uploading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!