Jump to content

jaybo

Members
  • Posts

    39
  • Joined

  • Last visited

Everything posted by jaybo

  1. Thank you Barand - that helped! Appears to work now.
  2. I have some code that is using Ajax long polling, connecting to a mysql DB and then outputting the current data upon a change to the table. I am implementing this page so that while 2 or more people are on the same admin page at the same time they will see any changes the other(s) makes real time. Here is the sql: CREATE TABLE `customers` ( `id` int(55) NOT NULL, `lastModified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `firstName` int(55) NOT NULL, `lastName` int(55) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `customers` ADD PRIMARY KEY (`id`); FILE 1: cusDetLongPoll.php <?php ini_set('display_errors', 1); error_reporting(E_ALL); ?> <!-- (A) HTML SCOREBOARD --> <div id="sTime"></div> <div id="sBoard"> <div id="sFirst"></div> <div id="sLast"></div> <div id="First">First</div> <div id="Last">Last</div> </div> <script> // (B) LAST UPDATED TIMESTAMP var last = 0; // (C) AJAX LONG POLL function poll () { // (C1) FORM DATA let data = new FormData(); data.append("last", last); console.log("Fetch run", last); // (C2) FETCH UPDATE ON SERVER RESPONSE fetch("modules/customer/cusDetLongPoll2.php", { method:"POST", body:data }) .then(res => res.json()) .then(data => { //console.log(data); // (C2-1) UPDATE HTML DISPLAY document.getElementById("sTime").innerHTML = data.lastModified; document.getElementById("sFirst").innerHTML = data.firstName; document.getElementById("sAway").innerHTML = data.lastName; // (C2-2) NEXT ROUND last = data.unix; poll(); }) // (C3) CATCH ERROR - LOOP ON TIMEOUT .catch(err => poll()); } // (D) GO! window.onload = poll; </script> FILE 2: cusDetLongPoll2.php <?php ini_set('display_errors', 1); error_reporting(E_ALL); class CustomerDetails { // (A) CONSTRUCTOR - CONNECT TO DATABASE protected $pdo = null; protected $stmt = null; function __construct () { try { $this->pdo = new PDO( "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET, DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); } catch (Exception $ex) { exit($ex->getMessage()); }} // (B) DESTRUCTOR - CLOSE CONNECTION function __destruct () { if ($this->stmt !== null) { $this->stmt = null; } if ($this->pdo !== null) { $this->pdo = null; } } // (C) GET LATEST CUSTOMER DETAILS function getCusDetails() { $this->stmt = $this->pdo->prepare( "SELECT *, UNIX_TIMESTAMP(`lastModified`) AS `unix` FROM `customers` WHERE id = 1" ); $this->stmt->execute(); return $this->stmt->fetch(); } } // (D) DATABASE SETTINGS - CHANGE THESE TO YOUR OWN! define("DB_HOST", "localhost"); define("DB_NAME", "NAME"); define("DB_CHARSET", "utf8"); define("DB_USER", "USER"); define("DB_PASSWORD", "PASSWORD"); // (E) CHECK FOR CUSTOMER UPDATES // ******** THIS IF STATEMENT IS NOT WORKING - WHEN REMOVED WE CAN PRINT_R THE CUSTOMER DETAILS AS ARRAY. WHEN USED THE IF STATEMENT RETURNS NO DATA. ********* if (isset($_POST["last"])) { // (E1) SET TIME LIMIT set_time_limit(30); // set an appropriate time limit ignore_user_abort(false); // stop when long polling breaks // (E2) LOOP UNTIL THERE ARE UPDATES OR TIMEOUT $_DETAILS = new CustomerDetails(); //print_r($_DETAILS->getCusDetails()); while (true) { $details = $_DETAILS->getCusDetails(); if (isset($details["unix"]) && $details["unix"] > $_POST["last"]) { echo json_encode($details); break; } sleep(1); // short pause to not break server } } From my testing I have found that in the code above at > if (isset($_POST["last"])) { ... When this is taken out and I run the PRINT_R on the $_DETAILS->getCusDetails(); I see the output on the screen. When I add in the if statement then I do not get any output or data at all. I ran this code the first time and it worked, changed the data and timestamp in the DB and it auto updated. But then my browser ran a refresh through my code and it hasn't worked since. May be totally unrelated but this was the order of events. Any help appreciated!!
  3. UPDATE: Did not find a solution to the exact issue - the newer telnet class was also not connecting for me. I have, however, been able to get a perl connection using Net::Telnet component, then run a short php script to output ALL results. This happened within 3 seconds for 900+ results so all in all a good replacement.
  4. regex is matching and adding the testing of $line still produces the timeout. I am trying to echo out each line as it is read also but not getting any output at all currently. Looking at the http.conf file for apache to see if I can change the timeout for the server and see if this helps.
  5. Update - new class not connecting for me, still looking at that one. Current class I am also trying to modify still produces a Gateway Timeout with the newly modified code addition; //edited code to attempt to read the eof to allow all data to pass before close of socket function GetResponse(&$r) { $r = ''; do { $line = fgets($this->fp); $r .= $line; } while (!preg_match('/\d{1,4} Bridge Interfaces displayed/', $line)); } timeout is occurring at exactly 1min. **From tailing the log file I am also seeing that the Fatal Error is due to the Maximum execution time of 300 seconds exceeded (used php_ini to set this).
  6. Thank you. Will work on this and come back with updates/questions!
  7. So in looking at making the current class work through modification: The last line upon completing the output (identifier) is always ‘[1-4 digits number*] Bridge Interfaces displayed’ for the tasks I am running. So I am looking at where to state this as the EOF prompt in the script? In addition when connecting via telnet from the terminal it takes between 10sec-45sec+ depending on the server chassis I am connecting to. Not sure if this would mean I need to tweak the socket_timeout to allow for this?
  8. Thanks Kicken. Currently struggling to connect to telnet with the new class. Will invest some time then come back with an update.
  9. Thank you mac_gyver for that useful input. I tried to switch out while ($s['unread_bytes']); with while (! feof($s)); but this causes an internal error. Not too sure where to put the feof().
  10. Still also trying to debug the other code with PHPTelnet class library. I have a bunch of code that I use with it and would like to find the answer to that too!
  11. Thanks for the additional option here - I'll look to test with that library.
  12. The script runs in 8 seconds in the browser. In the terminal it takes about 45 seconds to output all lines.
  13. I have a telnet request to a chassis that should be returning 500+ responses to the browser (returns 500+ when using the terminal for same request). Currently I am able to output approximately 40 of them. I have used the same code to hit different chassis and cannot output more than 60 results. Here is my code: <?php require_once 'db.php'; require_once "PHPTelnet.php"; $largeParts = array(); $telnet = new PHPTelnet(); $telnet->show_connect_error=1; $result = $telnet->Connect($server, $user, $pass); $resultArray1 = []; $resultArray2 = []; $resultOutput = []; ########## bridge show all commands ########## if ($result ==0) { $telnet->DoCommand('bridge show', $result); $resultArray1 = preg_split('/\n|\r\n?/', $result); //second command to include multiple page output from bridge show command sleep(1); $telnet->DoCommand('a', $result); $resultArray2 = preg_split('/\n|\r\n?/', $result); //Merge the arrays to combine all the result outputs $resultOutput = array_merge($resultArray1, $resultArray2); //duplicate cli telnet output to review echo '<pre>'; echo "\n------------------------>>>>>>>\n"; print_r($resultOutput); echo "\n------------------------>>>>>>>\n"; echo '</pre>'; } // say Disconnect(0); to break the connection without explicitly logging out $telnet->Disconnect(); mysqli_close($mysqli); The class for the connection is PHPTelnet (https://www.geckotribe.com/php-telnet/) As you will see in the below code I have tried see if there are any obvious issues by using print_r for the Function GetResponse(). I have also tried to make a change in case of a stream timeout (due to the hundreds of lines that return when making the telnet call through the terminal). Here is my code for that class: <?php class PHPTelnet { var $show_connect_error=1; var $use_usleep=0; // change to 1 for faster execution // don't change to 1 on Windows servers unless you have PHP 5 var $sleeptime=125000; var $loginsleeptime=1000000; var $fp=NULL; var $loginprompt; var $conn1; var $conn2; /* 0 = success 1 = couldn't open network connection 2 = unknown host 3 = login failed 4 = PHP version too low */ function Connect($server,$user,$pass) { $rv=0; $vers=explode('.',PHP_VERSION); $needvers=array(4,3,0); $j=count($vers); $k=count($needvers); if ($k<$j) $j=$k; for ($i=0;$i<$j;$i++) { if (($vers[$i]+0)>$needvers[$i]) break; if (($vers[$i]+0)<$needvers[$i]) { $this->ConnectError(4); return 4; } } $this->Disconnect(); if (strlen($server)) { if (preg_match('/[^0-9.]/',$server)) { $ip=gethostbyname($server); if ($ip==$server) { $ip=''; $rv=2; } } else $ip=$server; } if (strlen($ip)) { if ($this->fp=fsockopen($ip,23)) { fputs($this->fp,$this->conn1); $this->Sleep(); fputs($this->fp,$this->conn2); $this->Sleep(); $this->GetResponse($r); $r=explode("\n",$r); $this->loginprompt=$r[count($r)-1]; fputs($this->fp,"$user\r"); $this->Sleep(); fputs($this->fp,"$pass\r"); if ($this->use_usleep) usleep($this->loginsleeptime); else sleep(1); $this->GetResponse($r); $r=explode("\n",$r); if (($r[count($r)-1]=='')||($this->loginprompt==$r[count($r)-1])) { $rv=3; $this->Disconnect(); } } else $rv=1; } if ($rv) $this->ConnectError($rv); return $rv; } function Disconnect($exit=1) { if ($this->fp) { if ($exit) $this->DoCommand('exit',$junk); fclose($this->fp); $this->fp=NULL; } } function DoCommand($c,&$r) { if ($this->fp) { fputs($this->fp,"$c\r"); $this->Sleep(); $this->GetResponse($r); $r=preg_replace("/^.*?\n(.*)\n[^\n]*$/","$1",$r); } return $this->fp?1:0; } function GetResponse(&$r) { $r=''; do { // stream_set_timeout($this->fp, 60000); //This did not change anything to the response $r.=fread($this->fp,8000); ##################### WHERE TO PUT THIS ? #################################### // added below line to test value on stream timeout for the 2 servers that have hundreds of results. Did not show any change to results. //stream_set_timeout($this->fp, 60000); ############################################################################# $s=socket_get_status($this->fp); echo ">>>>>>>>>>>>>> TESTING START >>>>>>>>>>>>>> <br>"; // echo "<pre>"; // print_r($r); // echo "</pre>"; // echo "<br><br>"; echo "<pre>"; print_r($s); echo "</pre>"; echo "<br> >>>>>>>>>>>>>> TESTING END >>>>>>>>>>>>>> <br>"; } while ($s['unread_bytes']); ##################### TESTING TO GET STREAM META DATA #################################### // $stream_meta_data = stream_get_meta_data($this->fp); //Added line // echo "<br><br><br><br>"; //Added line // echo "<pre>"; // print_r($stream_meta_data); //Added line // echo "</pre>"; ############################################################################# } function Sleep() { if ($this->use_usleep) usleep($this->sleeptime); else sleep(1); } function PHPTelnet() { $this->conn1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB). chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB). chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB). chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC). chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA). chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF). chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33). chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33). chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0). chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0). chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54). chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0); $this->conn2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC). chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21); } function ConnectError($num) { if ($this->show_connect_error) switch ($num) { case 1: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/fsockopen.php">Connect failed: Unable to open network connection</a><br />'; break; case 2: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/unknown-host.php">Connect failed: Unknown host</a><br />'; break; case 3: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/login.php">Connect failed: Login failed</a><br />'; break; case 4: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/php-version.php">Connect failed: Your server\'s PHP version is too low for PHP Telnet</a><br />'; break; } } } return; The print_r of $s from Function getResponse() outputs as follows: Array ( [timed_out] => [blocked] => 1 [eof] => [stream_type] => tcp_socket/ssl [mode] => r+ [unread_bytes] => 0 [seekable] => ) When looking to watch the telnet process real time, I used the command "-sudo watch ss-t " and it shows that the script is completing as expected and that the socket is not timing out because of a script crash. Our thought was that the socket is timing out prematurely. I tried to increase the stream_set_timeout() but to no avail as you may see from the code. I looked at the documentation https://www.php.net/manual/en/function.stream-set-timeout.php. Not sure if I am just putting that method in the wrong place or if I am missing something else.... such as would the fact that the blocking is True make a difference?
  14. Thanks kicken, sorted it right out!
  15. Thanks for spotting that ginerjm - still no luck however. The error is now as follows; SyntaxError: Unexpected token - at parse (/var/app/current/node_modules/body-parser/lib/types/json.js:83:15) at /var/app/current/node_modules/body-parser/lib/read.js:116:18 at invokeCallback (/var/app/current/node_modules/raw-body/index.js:262:16) at done (/var/app/current/node_modules/raw-body/index.js:251:7) at IncomingMessage.onEnd (/var/app/current/node_modules/raw-body/index.js:307:7) at emitNone (events.js:86:13) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickCallback (internal/process/next_tick.js:104:9)
  16. I am running a script with a curl GET request but my code is not currently outputting anything. Here is the code, I think that I need to add the parameters to the url but need some direction as how to do that? Here is the code; <?php $curl = curl_init(); // Array Parameter Data $data = [ 'lat'=>'52.509120', 'lon'=>'-1.884915', ]; curl_setopt_array($curl, [ CURLOPT_URL => "https://geo.fcc.gov/api/census/area", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => [ "Content-Type: application/json", ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ?>
  17. still to explore guzzle - but we have a resolution! The final code that we got to was indeed correct! The issue at that point was with the mailchimp audience logic. The emails that I was passing (made up emails) were causing the errors as they were invalid emails. I then was able to pass through real email addresses and this allowed the API request to process correctly. As previously discussed the Mailchimp API document for php is incomplete and using their API dashboard you cannot get more detailed error information. Contacting mailchimp and asking them to set up the API watcher for your account for 24-48hrs to check the API requests made during that period is one way of collecting that information.
  18. Great help thank you! I haven't done that before - limited use of Guzzle up to now. I will explore!
  19. You did indeed, Mailchimp responded back to me yesterday: So I sent through both requests (with and without the json_encode) for them to review and respond with error messages. It is unfortunate that they do not allow the api monitoring tool to be used on the client end.
  20. Code now; $operations = []; foreach($users as $user) { $operation = [ 'method' => 'POST', 'path' => "/lists/$listId/members", 'operation_id' => $user['id'], 'body' => json_encode([ 'email_address' => $user['email'], 'status' => $user['status'], // Create sync/button to allow BFCMA back end to change this with the DB to then update with daily/weekly batch request //add additional fields to insert into MC 'merge_fields' => [ // 8/10/21 Stackoverflow suggests to use merge-fields *not currently working with it included 'FNAME' => $user['fname'], 'LNAME' => $user['lname'] ] ]) ]; array_push($operations, $operation); } // create object to put $operations array inside $operationsObject = ['operations'=>$operations]; echo '<pre> '; print_r($operationsObject); echo '</pre>'; try { $response = $mailchimp->batches->start($operationsObject); // echo $response; echo '<pre> '; print_r($response); echo '</pre>'; } catch (\MailchimpMarketing\ApiException $e) { echo $e->getMessage(); } In addition, here is the final part of the code if you were to include the json_encode; // create object to put $operations array inside $operationsObject = ['operations'=>$operations]; echo '<pre> '; print_r($operationsObject); echo '</pre>'; $json = json_encode($operationsObject, JSON_PRETTY_PRINT); echo '<pre> '; print_r($json); echo '</pre>'; try { $response = $mailchimp->batches->start($json); // echo $response; echo '<pre> '; print_r($response); echo '</pre>'; } catch (\MailchimpMarketing\ApiException $e) { echo $e->getMessage(); }
  21. Thanks - yes I missed that one. After using print_r for $response and moving the $operationsObject after the array has been populated I get the following response indicating that there are no operations passed in the request; stdClass Object ( [id] => snxzha6dug [status] => pending [total_operations] => 0 [finished_operations] => 0 [errored_operations] => 0 [submitted_at] => 2022-01-11T00:42:23+00:00 [completed_at] => [response_body_url] => [_links] => Array ( [0] => stdClass Object ( [rel] => parent [href] => https://us6.api.mailchimp.com/3.0/batches [method] => GET [targetSchema] => https://us6.api.mailchimp.com/schema/3.0/Definitions/Batches/CollectionResponse.json [schema] => https://us6.api.mailchimp.com/schema/3.0/Paths/Batches/Collection.json ) [1] => stdClass Object ( [rel] => self [href] => https://us6.api.mailchimp.com/3.0/batches/snxzha6dug [method] => GET [targetSchema] => https://us6.api.mailchimp.com/schema/3.0/Definitions/Batches/Response.json ) [2] => stdClass Object ( [rel] => delete [href] => https://us6.api.mailchimp.com/3.0/batches/snxzha6dug [method] => DELETE ) ) ) If I also print_r $operationsObject then I get the following which again indicates an array, not an object; Array ( [operations] => Array ( [0] => Array ( [method] => POST [path] => /lists/6ecc1e6884/members [operation_id] => 1 [body] => {"email_address":"test1@example.com","status":"subscribed","merge_fields":{"FNAME":"David","LNAME":"Tester"}} ) [1] => Array ( [method] => POST [path] => /lists/6ecc1e6884/members [operation_id] => 2 [body] => {"email_address":"test2@example.com","status":"subscribed","merge_fields":{"FNAME":"Kevin","LNAME":"Ishere"}} ) [2] => Array ( [method] => POST [path] => /lists/6ecc1e6884/members [operation_id] => 3 [body] => {"email_address":"happy@example.com","status":"subscribed","merge_fields":{"FNAME":"Gerald","LNAME":"Happy"}} ) [3] => Array ( [method] => POST [path] => /lists/6ecc1e6884/members [operation_id] => 4 [body] => {"email_address":"Tim@example.com","status":"subscribed","merge_fields":{"FNAME":"Tim","LNAME":"Toolman"}} ) [4] => Array ( [method] => POST [path] => /lists/6ecc1e6884/members [operation_id] => 5 [body] => {"email_address":"grealish@example.com","status":"subscribed","merge_fields":{"FNAME":"Jack","LNAME":"Grealish"}} ) ) ) I tried to json_encode $operationsObject and then pass that through with the request, which appears to pass through the correct object format, but it returns the same $response message.
  22. response now= Fatal error: Uncaught Error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\dashboard\MailchimpAPI\batchRequestAddMem.php:141 Stack trace: #0 {main} thrown in C:\xampp\htdocs\dashboard\MailchimpAPI\batchRequestAddMem.php on line 141 code now: $operations = []; // create object to put $operations array inside $operationsObject = ['operations'=>$operations]; foreach($users as $user) { $operation = [ 'method' => 'POST', 'path' => "/lists/$listId/members", 'operation_id' => $user['id'], 'body' => json_encode([ 'email_address' => $user['email'], 'status' => $user['status'], // Create sync/button to allow BFCMA back end to change this with the DB to then update with daily/weekly batch request //add additional fields to insert into MC 'merge_fields' => [ // 8/10/21 Stackoverflow suggests to use merge-fields *not currently working with it included 'FNAME' => $user['fname'], 'LNAME' => $user['lname'] ] ]) ]; array_push($operations, $operation); } try { $response = $mailchimp->batches->start($operationsObject); echo $response; } catch (\MailchimpMarketing\ApiException $e) { echo $e->getMessage(); }
  23. Yes I don't quite get how I do that. I have been reading the docs, specifically noting "expects a JSON object with a single key: operations, which is an array of objects that describe the API calls you want to make". I see, as you mentioned, that I have the $operations array all set. I have tried a couple of methods to create an object and then put the key:value pair inside, which is how I'm conceptualizing this part... // create object to put $operations array inside // $operationsObject = (object)['operations'=>$operations]; This brings about the same error. I feel I'm missing something that is more straight forward than what I am trying.
  24. Thank you again, I am drawing a blank - I tried to json decode each operation but that just prints an array of objects.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.