4

Preciso que no final do código ele apague os download que foi feito e baixe novamente, que fique se repetindo isso a cada 4 min. A cada 4 min ele executa esse script de "baixar, apagar e baixar novamente".
Como fazer?! Agradeço de coração a quem ajudar, já foi muito trabalhoso esse código.

O código ele:

  • Acessa o site
  • Procura os arquivos .CSV e baixa tudo pra pasta downloads que fica junto ao script
<?php

$x = new Nulogy();
$retorno = $x->iniciar();
echo $retorno;

class Nulogy{

public $u;
public $s;
public $url;
public $post;
public $resposta;
public $cookie;
public $token;
public $urlDownload;
public $dir;
public $nome;
public $ds;
public $arquivo;
public function __construct(){

  $this->u = 'login aqui';
  $this->s = 'senha aqui';
  $this->dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'download'.DIRECTORY_SEPARATOR;
  $this->cookie = dirname(__FILE__).DIRECTORY_SEPARATOR. '/cookie/' .'NULOGY[COOKIE]' . rand(0, 999999) . '.txt';
}
public function iniciar(){
  $this->url = 'https://packmanager.nulogy.net/sign_in';
  $this->loginPlayLoad();
  $this->post();
  $validarLogin = $this->validarLogin();
  if($validarLogin === 'logado'){
  return $this->linkDownload();
  }else{
    return $validarLogin;
  }
}
public function loginPlayLoad(){
  $this->getTokenLogin();
  if($this->token){
    $data['utf8'] = '✓';
    $data['authenticity_token'] = $this->token;
    $data['return'] = '';
    $data['uv_login'] = '';
    $data['user[login]'] = $this->u;
    $data['user[password']= $this->s;
    $data['commit'] = 'Sign in';
    $data['authenticity_token'] = $this->token;
    $data['authenticity_token'] =$this->token;
  }else{
    return false;
  }
  $this->post = http_build_query($data);
  return true;
}
public function getTokenLogin(){
  $this->url = 'https://packmanager.nulogy.net/sign_in';
  $this->get();
  preg_match_all('/meta content="(.*?)" name="csrf-token"/', $this->resposta, $matches, PREG_SET_ORDER, 0);
  $token = $matches[0][1];
  if($token){
    return $this->token = $token;
  }else{
    return array('status' => false,'resposta' => 'Não foi possível encontrar CSRF-TOKEN' );
  }
  return false;
}
public function validarLogin(){
  if(preg_match_all('/title>(.*?)<.title>/', $this->resposta, $matches, PREG_SET_ORDER, 0)){
    $titlo = $matches[0][1];
  }else{
  $titlo = false;
  }

  if((isset($titlo) && ($titlo === 'Sign in to PackManager') )) {
    return $titlo . ' Login ou senha inválidos.';
  }else{
    return 'logado';
  }
}
public function linkDownload(){
  $url = [
  'https://packmanager.nulogy.net/canned_reports/job_productivity?utf8=%E2%9C%93&generate_flag=true&filter_choice=project_customer&query%5B0%5D%5Bactual_job_start_at%5D%5Boperator%5D=between&query%5B0%5D%5Bactual_job_start_at%5D%5Bfrom_threshold%5D=2017-Jul-2+9%3A00+PM&query%5B0%5D%5Bactual_job_start_at%5D%5Bto_threshold%5D=2017-Jul-3+11%3A46+PM&columns%5B0%5D=project_code&columns%5B1%5D=item_code&columns%5B2%5D=actual_job_start_at&columns%5B3%5D=actual_job_end_at&columns%5B4%5D=line_name&columns%5B5%5D=performance&columns%5B6%5D=availability&columns%5B7%5D=line_efficiency&columns%5B8%5D=units_produced&columns%5B9%5D=units_expected&columns%5B10%5D=unit_of_measure&columns%5B11%5D=standard_units_per_hour&columns%5B12%5D=duration&order_by=actual_job_start_at&order_direction=desc&authenticity_token='.urlencode($this->token).'&authenticity_token='.urlencode($this->token).'&format=csv',
  'https://packmanager.nulogy.net/jobs.csv?authenticity_token='.urlencode($this->token).'&customer_name=&from_scheduled_start_at=2017-Jul-2+00%3A00&has_production=all&item_code=&line_leader=all&line_leader_id=all&line_name=&page=1&project_code=&reconciliation_status=all&signed_off=no&status=all&to_scheduled_end_at=2017-Jul-3+23%3A59&utf8=%E2%9C%93',
  'https://packmanager.nulogy.net/canned_reports/job_downtime?utf8=%E2%9C%93&generate_flag=true&filter_choice=item_class_name&query%5B0%5D%5Bactual_job_start_at%5D%5Boperator%5D=between&query%5B0%5D%5Bactual_job_start_at%5D%5Bfrom_threshold%5D=2017-Jul-2+9%3A00+PM&query%5B0%5D%5Bactual_job_start_at%5D%5Bto_threshold%5D=2017-Jul-3+11%3A55+PM&columns%5B0%5D=job_id&columns%5B1%5D=line_name&columns%5B2%5D=downtime_reason_code&columns%5B3%5D=downtime_reason_name&columns%5B4%5D=downtime_duration&columns%5B5%5D=downtime_notes&order_by=actual_job_start_at&order_direction=desc&authenticity_token='.urlencode($this->token).'&authenticity_token='.urlencode($this->token).'&format=csv'];
  $nome = [0 => 'produtividade do trabalho.csv',1 => 'Trabalhos.csv' , 2 => 'inatividade do trabalho.csv'];
  $i = 0;

  foreach($url as $u):
    $this->urlDownload = $u;
    $this->nome = $nome[$i++];
    echo $this->dw();
  endforeach;
}
public function header(){
  $header = [
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
      "Accept-Language: en-US,en;q=0.5",
      "Accept-Encoding: gzip, deflate, br",
      "Connection: keep-alive",
      "Upgrade-Insecure-Requests: 1",
      "Content-Type: application/x-www-form-urlencoded"
  ];
  return $header;
}
public function dw(){
    $this->url = $this->urlDownload;
    $this->get();
    $dw = $this->resposta;
    $this->arquivo = $this->dir.$this->nome;
    if($this->arquivosExiste()){

    file_put_contents($this->arquivo , $dw);
    $ret =  'Arquivo salvo na pasta: ' . $this->dir . '<br>';
    }else{
      $ret = 'Algum problema foi encontrado :/';
    }
    return $ret;
}
public function arquivosExiste(){
  if (is_file($this->arquivo)){
      unlink($this->arquivo);
   }
  return true;
}
public function post(){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $this->url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36');
  curl_setopt($ch, CURLOPT_REFERER, "https://packmanager.nulogy.net/sign_in");
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION,2);
  curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header());
  curl_setopt($ch, CURLOPT_ENCODING, '');
  $this->resposta = curl_exec($ch);
}
public function get(){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $this->url);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36');
  curl_setopt($ch, CURLOPT_REFERER, "https://packmanager.nulogy.net/sign_in");
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header());
  curl_setopt($ch, CURLOPT_ENCODING, '');
  $this->resposta = curl_exec($ch);
}
}
7
  • 2
    Eu recomendaria implementar como se fosse para executar apenas uma vez o script, mas chamá-lo via tarefa agendada a cada 4 minutos. Arquivos que serão sobreescritos nem precisam ser deletados. E os arquivos que foram criados antes do início do script (observar a hora) podem ser deletados no final dele.
    – C. Bohok
    28/07/2017 às 11:38
  • 1
    Configure sua cronJob para que execute o mesmo a cada 4 minutos, se cada arquivo for para um usuário específico, ele tera de executar a cronJob buscando todos os usuários, ou tera de ter um arquivo específico para cada usuário 28/07/2017 às 12:00
  • Acredito que a melhor forma seja configurando um cronjob na tua hospedagem. Se for cPanel é mais fácil ainda, você só irá colocar o tempo de 4 minutos e irá colocar o caminho do arquivo php que apaga os arquivos do servidor e baixa novamente. Fica bem fácil fazer dessa forma. Abraço!
    – Julio Sieg
    24/10/2017 às 13:16
  • Bom, a melhor opção ao meu ver é você incrementar esse script para que ele faça todo o processo do início ao fim, ou seja, ele cria e deleta tudo, ao final dele, tem que ficar como se não tivesse feito. Sendo assim, você cria uma tarefa agendada, CRON JOB, e coloca uma repetição de 4 em 4 minutos, o que fará exatamente o que você quer. 22/10/2018 às 11:09
  • Uma outra opção é executar em um loop no bash (eu utilizo quando o laço de repetição precisa ser menor que 1 minuto): $ while true; php script.php; sleep 180; done;
    – chavesfop
    30/03/2021 às 11:09

1 Resposta 1

-3

Se estiver rodando em ambiente linux, pode simplesmente criar uma entrada na crontab para executar seu script com a periodicidade desejada.

Segue um site pasa se te guiar na configuração do cron: https://crontab.guru/

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .