CoderJoe
CoderJoe

Reputation: 447

PHP keep executing script but redirect client somewhere else

In combination with using

ignore_user_abort(true);
set_time_limit(0);

Is it possible to send the client to another page since the data is already being processed by the server. Since the user could simply close their browser after hitting submit instead of them waiting on the page I would like to send them to another page and then send them an email once the script finishes.

Imagine the user has just submitted a long form and now several operations happen

First the data is validated Upon failure the user is sent an email of why it failed Upon success we move to the next step

Now the video that was submitted into the form is sent to our video server Upon failure email is sent Upon success move to next step

Now the user is added as a contact into our CRM Upon failure email is sent Upon success move to next step

Now user data is all entered into the database Upon failure email is sent Upon success email is sent and user is redirected to next page

What I would like to do is upon user submission the user is redirected to the next page immediately while the server handles everything

Upvotes: 1

Views: 78

Answers (2)

Akash Sharma
Akash Sharma

Reputation: 757

For long processes use asynchronous method. Use any Queue RabbitMQ/Kafka, add your request to queue and redirect user to another page. Now on server side, consumer can fetch request from queue and process the request and notify the user. This can be achieved by MySql also, using MySql as queue but its highly unrecommended as of locks and periodic scanning for requests.

Upvotes: 0

Tim Morton
Tim Morton

Reputation: 2644

Use AJAX to submit the request, but instead of waiting for the reply, use javascript to redirect to next page.

Assuming you have JQuery:

<script>

$('#submitButtonId').click( function() {
    $.ajax({
        url: 'some-url',
        type: 'post',
        // dataType: 'json', 
        data: $('form#myForm').serialize(),
        success: function(data) {
          // do nothing      
        }
    });

    // redirect
    window.location.href = "http://your_redirect";
});

</script>

Upvotes: 1

Related Questions