问题
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:
- Is the declaration of
!move_uploaded_file...
uploading the file at the start of the loop? - If yes, is the file being uploaded on every iteration through the loop?
- Is the declaration of
move_uploaded_file...
in theif
statement within the loop also uploading the file or is it just checking that the file has been uploaded? - 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:
- Yes, well it is moving the file anyway. Once it has moved the file I guess it will return false.
- Yes it is trying to move the file on every iteration
- This is also trying to move the file. You are executing the method not declaring it.
- 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