Execute function x minutes after submitting form

Asked

Viewed 135 times

4

Good afternoon guys, appeared a problem to solve on a site, something that had not yet moved.

The following is, on the page I have a form where the person can register. When making the registration, I send an email to her confirming this registration.

Now, we will start using SMS also, ie the person sign up, receive an email and a SMS confirming (company rules). But my manager wants the SMS to arrive after about 5 min that the person made the registration on the site.

Right now, I’m sending the text right away, but he wants it done the way he said it.

Can someone help me ?

Note: I submit the form on the same page that I do.

function sendSms(){

            $nome = explode(" ",$_POST['txtNome']); // pega o nome via post , e joga cada palavra em um array

            $corrigir = array(' ','-','(',')','{','}','/','  ');// array que elimina caractres do telefone ,deixando somente os numeros 

            $corpoSMS = 'SKY HDTV:Caro(a).'$nome[0].',informamos que seus dados foram enviados para nosso dpt de cadastros.Dentro de 24h,entraremos em contato com maiores informacoes'; //monta o corpo do sms , mantendo o limite de 160 caracteres.

            $tel = str_replace($corrir,'',$_POST['txtCel']);

            $msg = str_replace(' ','+',$corpoSMS);

            //código da página enviapost.php
                $dados_post = array(
                        "" => $tel,
                        "?message=" => $msg,
                        );

                $context = stream_context_create(array(
                    'http' => array(
                    'method' => 'GET',
                    'header' => array(
                    'Content-Type: application/x-www-form-urlencoded'),
                    'content' => http_build_query($dados_post)
                    )
                )
            );

        $host = 'https://meuservidordesms.com.br/'.$tel.'?message='.$msg;
            $result = file_get_contents($host,false,$context);

            if(preg_match("/SUCESSO/", $result)){
                    echo '  <script type="text/javascript">
                                alert("SMS enviado com sucesso!");
                            </script>';
                        } else {
                            echo '<script type="text/javascript">alert("Erro enviar o SMS.<br>");</script>';
                    }

        }// FUNCAO QUE ENVIA O SMS AO CLIENTE.
  • 1

    Have you ever tested the impact it would have on getting these text messages stacked? Doesn’t it create a bottleneck in the system? There would be some problem if you saved it in file or database and then ran a task every time you read this data and sent it. Example of a scheduled task? Roughly as if using an Observer?

  • Good evening, Voce would have some example or link showing how it could do ? Grateful

  • A thread that queries in the database every 5 seconds which are the next SMS to send, I never used Thread in PHP, but in other languages like Delphi and Java. The following is documentation: http://php.net/manual/en/class.thread.php.

  • This might help you http://www.phpclasses.org/package/9047-PHP-Execute-asynchronous-tasks-in-the-background.html

  • You can use a queue service like: Amazon SQS, Beanstalkd, Ironmq, ...

1 answer

2

As Israel said, maybe you should have a service running on the server, checking the new records in the database and sending the SMS at the scheduled time.

Anyway, I was interested in your question and did some research. It seems it’s possible to contact one "script son" from the script which is accessed by the customer, using socket. That one script responds quickly to "script father" which then disconnects - from there, the "script son" continues its work, in background.

Here comes the "script father":

<?php

echo "Teste de Socket para Script Filho";

// Data para diferenciar o momento do acesso ao da criação do arquivo .txt
date_default_timezone_set('America/Sao_Paulo');
$current_date = date('d/m/Y == H:i:s');

// Criando a conexao socket
$socketParaFilho = fsockopen("www.example.com", 80);

// Criando pacote HTTP
$paraScriptFilho = "POST /script.php?&param=value HTTP/1.0\n";
$paraScriptFilho .= "Host: www.example.com\n";

// A mensagem que sera enviada ao script filho
$dados = "Script Pai: pagina acessada em " . $current_date;
$paraScriptFilho .= "Content-Length: ".strlen($dados)."\n\n";

// Incluindo mensagem com a data em que a pagina foi visitada
$paraScriptFilho .= $dados;

// enviando pacote
fwrite($socketParaFilho, $paraScriptFilho);

// Esperando resposta do script "filho"
$resposta = fread($socketParaFilho, $dataSize);

// Fechando conexao
fclose($socketParaFilho);

?>

Now the "script child", note that it should only be called "script.php":

<?php

date_default_timezone_set('America/Sao_Paulo');
$post = file_get_contents('php://input');

// Aqui que acontece a "mágica"
ob_start();
ignore_user_abort(1);
set_time_limit(0);

$resposta = "OK";
echo $resposta;

ob_flush();

// A partir deste ponto, o "script pai" desconecta, e o script filho
// se mantêm em execução

sleep(60);
$arquivo = 'teste.txt';
$data = date('d/m/Y == H:i:s');
$texto = $post . "\r\nScript Filho: texto salvo em " . $data;
file_put_contents($arquivo, $texto);

?>

After accessing the "script father", it is even possible to close the browser window. 60 seconds later, a. txt document will be created on the server, showing the date the page was accessed and the date the "script son" saved the document.

Here’s my test results:

Script Pai: pagina acessada em 20/07/2015 == 05:00:03
Script Filho: texto salvo em 20/07/2015 == 05:01:03

I found this example here.

PS. I don’t understand PHP. I saw this example and thought it might help with your question.

  • Good morning @Daniel, man , I had forgotten the sockets. I will try to apply to my case , because I’m only making the registration control page ,the site was an agency who developed. But I believe the sockets will supply my needs. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.