0

I built a script to get data from Gmail API(My previous 1000 emails,) I upload this script to my website to a different folder just for testing, And when I run the script first time it works fine, huge data start loading on the page, But then if I try to reload the page again it gives error 504 Gateway Time-out The server didn't respond in time. In fact, my whole website stops working Doesn't matter which URL of my website I open, I get the same error, But if I close the browser and reopen it or wait for 5 min then everything starts working fine again.But if I run the script again same things happen again. this is the script btw

<?php
session_start();
require_once 'google-api-php-client/vendor/autoload.php';
$client = new Google_Client;
$client->setClientId('xxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://localhost/gmail_api/redirect.php');
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
$client->setAccessType('offline');    
//$client->setApprovalPrompt('force');
$saved_token = '{"access_token":"xxxxxxxxxxxxxxxxxxxxxx","token_type":"Bearer","expires_in":3600,"refresh_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxx","created":1502292805}';
 $access_token = json_decode($saved_token,true);
if(isset($_SESSION['access_token'])){
 $access_token = $_SESSION['access_token']; 
}
$client->setAccessToken($access_token);

// It still works without this if
if($client->isAccessTokenExpired()){
  $refresh_token = json_decode($saved_token)->refresh_token;
  $client->refreshToken($refresh_token);
   $access_token = $client->getAccessToken();
   $_SESSION['access_token']= $access_token; 
}

?>
<!doctype html>
<html>
<head>
<style type="text/css">
 body{
  background: white !important;
  text-align:center;
 }
</style>

</head>
<body>
 <form method="get" action="">
<input type="text" name="search">
<input type="submit" value="search">
 </form>
<?php
function decodeBody($body) {
    $rawData = $body;
    $sanitizedData = strtr($rawData,'-_', '+/');
    $decodedMessage = base64_decode($sanitizedData);
    if(!$decodedMessage){
        $decodedMessage = FALSE;
    }
    return $decodedMessage;
}
 function getHeader($headers, $name) {
       foreach($headers as $header) {
    if($header['name'] == $name) {
      return $header['value'];
       }
     }
   }


try{     
      $gmail = new Google_Service_Gmail($client);
      $optParams = [];
                $optParams['maxResults'] = 1000; // Return Only 1000 Messages
                $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
                $optParams['includeSpamTrash'] = false; //No Messages from spam or trash
                $optParams['q'] = $_GET['search'];
                $list = $gmail->users_messages->listUsersMessages('me',$optParams);

    while ($list->getMessages() != null) {

        foreach ($list->getMessages() as $mlist) {

            $message_id = $mlist->id;
            $optParamsGet2['format'] = 'full';
            $single_message = $gmail->users_messages->get('me', $message_id, $optParamsGet2);
            $headers = $single_message->getPayload()->getHeaders();
            $payload = $single_message->getPayload();

            // With no attachment, the payload might be directly in the body, encoded.
            $body = $payload->getBody();
            $FOUND_BODY = decodeBody($body['data']);

            // If we didn't find a body, let's look for the parts
            if(!$FOUND_BODY) {
                $parts = $payload->getParts();
                foreach ($parts  as $part) {
                    if($part['body'] && $part['mimeType'] == 'text/html') {
                        $FOUND_BODY = decodeBody($part['body']->data);
                        break;
                    }
                }
            } if(!$FOUND_BODY) {
                foreach ($parts  as $part) {
                    // Last try: if we didn't find the body in the first parts, 
                    // let's loop into the parts of the parts (as @Tholle suggested).
                    if($part['parts'] && !$FOUND_BODY) {
                        foreach ($part['parts'] as $p) {
                            // replace 'text/html' by 'text/plain' if you prefer
                            if($p['mimeType'] === 'text/html' && $p['body']) {
                                $FOUND_BODY = decodeBody($p['body']->data);
                                break;
                            }
                        }
                    }
                    if($FOUND_BODY) {
                        break;
                    }
                }
            }

               $subject = getHeader($headers,'Subject');
                $Date = getHeader($headers,'Date');
                $From = getHeader($headers,'From');
            // Finally, print the message ID and the body
               echo "<h2>$subject </h2>";
             echo "Date:$Date <br>";
            echo "From:". htmlspecialchars($From)."<br>"; 
            print_r($FOUND_BODY);
        }

        if ($list->getNextPageToken() != null) {
            $pageToken = $list->getNextPageToken();
            $list = $gmail->users_messages->listUsersMessages('me', array('pageToken' => $pageToken));
        } else {
            break;
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
    unset($_SESSION['access_token']);
}

?>
</body>
</html>

It works great on localhost, Doesn't matter how many times I reload the page

Any guess what could be wrong?

beginner
  • 2,366
  • 4
  • 29
  • 53

1 Answers1

1

The 504 error means that one server did not receive a timely response from another server that it was accessing while attempting to load the web page or fill another request by the browser. You may follow the workaround given in the link above and see if it helps.

Here are some additional references:

abielita
  • 13,147
  • 2
  • 17
  • 59