PHP counter disappears/reappears - javascript

I downloaded a script to run a very basic counter on two of my website's pages. Since April 2009 it's run beautifully, but in the last three weeks it would suddenly disappear, then reappear occasionally. This week it's every day.At first the counter just disappeared, now the pages with the counters don't load except the banner. The page will load eventually, up to five minutes sometimes. But without the counter showing. That comes ages later. Then it can all disappear again!
[http://www.thepenvro.com/][1] is the home page Then if you click on "NEWS", then on "Social Events News" that's the other page that has a counter. (We are trying to see who is interested in the reunion info). The pages are erratic. They will either be OK, or they are there but missing the counter in the lower left of each the two page, or the pages will only show the headers with no page content OR counter. All in no particular order.
I have gone into the server side of my site and reset the scripting (was told to do that by the Streamline.net tekkie). It doesn't seem to help but now and then and wonder if it's just coincidence.
It affects another script. I have a form to email that works great, but when this counter disappears, it brings down the form to email function on the Contacts page. I put a note at the bottom of the form for visitors to just send an email when they get the error message. The full error message when you can manage to get SUBMIT to even change screens is:
FastCGI Error
The FastCGI Handler was unable to process the request.
Error Details:
The FastCGI pool queue is full
Error Number: 4 (0x80070004).
Error Description: The system cannot open the file.
HTTP Error 500 - Server Error.
Internet Information Services (IIS)
Streamline asks me to replicate the error...I can't! I can only give them what I am posting here and screenshots. So I don't have a clue if it's my script or them. The script for the counter is below. It was something I purchased as well. I first thought maybe it was IE8 that was causing the trouble, but the same problem shows in Firefox.
One last note....It's not the form to email that's a problem as I have that also running in one of the sub-domain's of the site and there is NO trouble there. But I do not have the counter running anywhere on the sub-domain either. I have all the same features for the main and sub-domain.
Thank you for any help...I am a complete novice so any solutions will be gratefully received. We are doing the publicity for our reunion in May and I have a big email campaign after Christmas to get out and I don't want the site all buggered up. If there is an alternative counter or if the version's php I have is too old, I am happy to purchase a better one from a reputable source.
<?php
/*******************************************************************************
* Title: PHP hit counter (PHPcount)
* Version: 1.2 # October 26, 2007
* Author: Klemen Stirn
* Website: http://www.phpjunkyard.com
********************************************************************************
* COPYRIGHT NOTICE
* Copyright 2004-2007 Klemen Stirn. All Rights Reserved.
*******************************************************************************/
// SETUP YOUR COUNTER
// Detailed information found in the readme.htm file
// Count UNIQUE visitors ONLY? 1 = YES, 0 = NO
$count_unique = 1;
// Number of hours a visitor is considered as "unique"
$unique_hours = 1;
// Minimum number of digits shown (zero-padding). Set to 0 to disable.
$min_digits = 0;
#############################
# DO NOT EDIT BELOW #
#############################
/* Turn error notices off */
error_reporting(E_ALL ^ E_NOTICE);
/* Get page and log file names */
$page = input($_GET['page']) or die('ERROR: Missing page ID');
$logfile = 'logs/' . $page . '.txt';
/* Does the log exist? */
if (file_exists($logfile)) {
/* Get current count */
$count = trim(file_get_contents($logfile)) or $count = 0;
if ($count_unique==0 || $_COOKIE['counter_unique']!=$page) {
/* Increase the count by 1 */
$count = $count + 1;
$fp = #fopen($logfile,'w+') or die('ERROR: Can\'t write to the log file
('.$logfile.'), please make sure this file exists and is CHMOD to 666 (rw-rw-rw-)!');
flock($fp, LOCK_EX);
fputs($fp, $count);
flock($fp, LOCK_UN);
fclose($fp);
/* Print the Cookie and P3P compact privacy policy */
header('P3P: CP="NOI NID"');
setcookie('counter_unique', $page, time()+60*60*$unique_hours);
}
/* Is zero-padding enabled? */
if ($min_digits > 0) {
$count = sprintf('%0'.$min_digits.'s',$count);
}
/* Print out Javascript code and exit */
echo 'document.write(\''.$count.'\');';
exit();
} else {
die('ERROR: Invalid log file!');
}
/* This functin handles input parameters making sure nothing dangerous is passed in */
function input($in) {
$out = htmlentities(stripslashes($in));
$out = str_replace(array('/','\\'), '', $out);
return $out;
}
?>

This has nothing to do with the PHP code, but with the configuration of the webserver. It probably gets hit too many times per second to be able to process all requests.
Try looking at the following settings from IIS:
instanceMaxRequests
maxInstances
queueLength

If you visit the counter directly you can see this error message:
<h1>FastCGI Error</h1>
The FastCGI Handler was unable to process the request.
<hr>
<p>Error Details:</p>
<ul>
<li>The FastCGI pool queue is full</li>
<li>Error Number: 4 (0x80070004).</li>
<li>Error Description: The system cannot open the file.
</li>
</ul>
<h2>HTTP Error 500 - Server Error.<br>Internet Information Services (IIS)</h2>
I'd say it's either what Tomh says, it gets too many hits so while one request is reading from the file another one tries to open it and it fails, OR it simply cannot open it because of a permission problem.

A lot of people have experienced the same problem while using streamline.net, myself included. I currently have a site with them that is down about 50% of the day, every day of the week with that error.
My recommendation, change to a new provider.
Streamline.net won't do a thing to help you and will meerly fob you off with vague / innacurate answers. I'm just waiting for my next paycheque then I'm going to buy hosting with someone else.

Related

Magento 1.9.x UTP Payment Integration - document.onreadystatechange issue

Good Morning all, firstly I must confirm this first. I am not a programmer but have basic knowledge of PHP etc from my teenage years. I am a commercial bee farmer that runs an eCommerce Magento website selling live bees & queens. As we are seasonal it is important our website functions correctly.
We recently changed our payment processor to UTP - Universal Transaction Processing whom offered us Magento to seamlessly integrate our payment for Debit / Credit cards. Unfortunately this has not been the case and our customers have been complaining they are unable to make payment.
After weeks of trying to replicate the issue I managed to replicate it consistently in IE 11 (Sorry I deal with people that use this!). It would load a blank page on transfer from my checkout page.
I widdled it down to the following code
echo "<script>document.onreadystatechange = () => {document.getElementById('redirect').submit();}</script>";
My understanding is IE11 has dropped support for this document.onreadystatechange
I modified the code to
echo "<script>document.getElementById('redirect').submit();</script>";
Now I don't believe this is an ideal solution as some browsers are transferring it too early before its read all the form data resulting in errors when payment page is reached.
Is anyone able to offer a solution to this? We are loosing so much custom, it is extremely important to us (being seasonal). Its our only opportunity to make money to survive through winter. This should be UTP's obligiation to fix but they are claiming there is NO issue yet I was able to replicate it multiple times on different platforms, I even set up a FRESH Magento install to prove it to them and they still deny any issue! I am going to and from a company denying there is anything wrong.
Would really appreciate some help in this mmater, here is the full code for this section.
public function redirectPayment() {
$this->log('Redirecting user for payment');
// Add hosted parameters to the generic order information
$session = $this->session->getData();
$req = array_merge(
$session[self::_MODULE]['req'],
array(
'redirectURL' => $this->getOrderPlaceRedirectUrl(),
'callbackURL' => $this->getOrderPlaceRedirectUrl(),
'formResponsive' => $this->responsive
)
);
// Comment session data
$this->log($this->commentSessionData());
$req['signature'] = $this->createSignature($req, $this->secret);
// Always clear to prevent redirects after
$this->clearData();
echo "<form id='redirect' action='" . self::HOSTED_URL . "' method='POST'>";
// Get session stored keys for a hosted request
foreach ($req as $key => $value) {
echo "<input type='hidden' name='$key' value='$value'/>";
}
echo "</form>";
echo "<script>document.onreadystatechange = () => {document.getElementById('redirect').submit();}</script>";
}

How to keep running a query to check database all the time every minute in PHP and JavaScript

I am making a project which is a website. Basically it will set a reminder and notify the user using email/SMS. I am using PHP and JavaScript. My database stores the the list of users in table 1 and a separate table for each user and his tasks(with the time and dates). I want to refer the database every minute to check for tasks even if the user is not logged in(browser is closed). What do i do to keep running the check for query all the time?
I want something that will run in background all the time even if user never opens the browser.
Please help.
The php code to store in a users database is
<?php
include("init.php");
session_start();
if(isset($_POST))
{
$date = $_POST["date"];
$event = $_POST["event"];
$time = $_POST["time"];
$daily = $_POST["daily"];
$weekly = $_POST["weekly"];
$monthly = $_POST["monthly"];
$fname = $_SESSION['fname'];
$fname = mysql_real_escape_string($fname);
$sql = "insert into $fname(fname,date,event,time,daily,weekly,monthly) values('$fname','$date','$event','$time','$daily','$weekly','$monthly')";
if(mysqli_multi_query($con,$sql))
echo "<br><h3> row inserted...</h3>done";
else
echo "Error in insertion...".mysqli_error($con);
}
?>
There is no issue with the code.
I just need to know how and using what can i refer the database all the time at the server end when user is not on the page.
Can php work 24hrs even if the browser is closed because i know javascript wont work.
You need to create an event in MySQL (or the database manager you are using, for example:
CREATE EVENT e_totals
-> ON SCHEDULE AT '2006-02-10 23:59:00'
-> DO INSERT INTO test.totals VALUES (NOW());
Or a recurrent event:
delimiter |
CREATE EVENT e_daily
ON SCHEDULE
EVERY 1 DAY
COMMENT 'Saves total number of sessions then clears the table each day'
DO
BEGIN
INSERT INTO site_activity.totals (time, total)
SELECT CURRENT_TIMESTAMP, COUNT(*)
FROM site_activity.sessions;
DELETE FROM site_activity.sessions;
END |
delimiter ;
Sagar what you are looking for is CRON Task. I am afraid that PHP and Javascript alone can't trigger it.
Work flow:
Make an API containing all your business logic or processing you need to execute it.
Register a CRON job in cPanel or crontab -e in your linux machine.
Use the end point directly using AJAX calls or make a separate end point as cron task will continue working.
Refer to this link in case you want to learn more about cron jobs - http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples
Thanks,
Abhishek Jain

repeat php sleep method inside a foreach loop each iteration

I have to send around 1k emails to different customers for different issues. Normally I would get an excel file with all the necessary information to send the emails. I have a web form where I insert the ticket number and that retrieves the necessary information to send the mail (which is also provided in the excel file). The problem is that inserting 1k ticket numbers in the form is an exhausting and time consuming work. So I copied the link that is generated to send the emails and created 1k links with the specific variables needed to send 1k different emails. Now all I have to do is generate a php function to open all the links and the job is done. However the mail server does not allow more than 20 emails to be sent from the same IP at once. It marks the emails as spam and blocks the IP. I tried a foreach loop with php sleep function inside of it and it is not working. The function sleeps for the given amount of time and then opens all the links given at once. I want to state that the function will be run from my laptop and will not be uploaded in any server or whatsoever.
Below is the function I currently have:
$emails = ["http://www.facebook.com","http://www.tuttojuve.com","http://www.google.com"];
//testing with these links instead of the email links
foreach($emails as $key => $email){
$mail = "<script type='text/javascript' language='Javascript'>window.open('".$email."','_blank');</script>";
sleep(5);
echo $mail;
}
Any help or hint is appreciated,
Thanks in advance
$emails = ["http://www.facebook.com","http://www.tuttojuve.com","http://www.google.com"];
?>
<script>
var linksToOpen = <?php echo json_encode($emails); ?>;
var currentLink = 0;
setInterval(function(){
window.open(linksToOpen[currentLink++], '_blank');
/* browser popup blocker may block this window so add window url to allowed list. */
}, 5000);
/* every x millisecond */
</script>

Syncing multiple clients triggered by a server in PHP and Javascript

I run a server on a shared hosted space (Aruba) with LAMP configuration, with two separate sets of PHP pages, one for the administrator and one for several clients (imagine a quiz game where the administrator submits questions).
I want to achieve this behaviour:
The administrator presses a button and released the question
At any time within ten seconds (or even immediately, but not strictly requested) all the clients must display AT THE SAME TIME the page with the text of the question.
To achieve this, I thought of different solutions:
Web sockets (not feasible, as I cannot install server components on
my web page)
Trigger file generated by the administrator; the clients will periodically (~10 sec) poll (setInterval()) for the presence of this file and, depending on the
creation time of the file (or an equivalent timestamp read from the
file name or file content) the client will start a countdown (setTimeout()) for the
time remaining to when the new page has to be fired, to make sure that all clients eventually trigger at the same time (tenth of second)
Trigger via database (basically same as trigger file, but possibly slower).
I tried the second solution (to manage the reading of trigger file on client-side) both in PHP and in Javascript, but they both fail when there is more than a client connected:
PHP apparently fails because Apache does not support many simultaneous threads
and gets somehow stuck
Javascript somehow occasionally misses to recognize the presence
of the file in the local directory (with more than one client
connected XMLHttpRequest.status incorrectly returns 404 even when the trigger file is there) - I even created separate trigger files for the different clients, to make sure there are no concurrency conflicts.
Any hints on why XMLHttpRequest.status occasionally fails, or advice on a better way of achieving this behaviour?
Thank you in advance.
Have you considered long polling? See https://github.com/panique/php-long-polling for an example of how to do this with PHP. This will not scale well because of the number of apache and php processes that would have to stay active, but would be fine for a few clients. If you need it to scale then I would consider switching server technologies to something like hack (like PHP; see http://hacklang.org/) or node which is great at this kind of thing.
EDIT: I didn't understand the question fully in my original answer. Here is my refined answer:
With the current limitations you are under, I see only one way of achieving a simultaneous server response. First, you will need to implement HTML5 SSE (server side events). When your server is ready to send a message to the clients, trigger an SSE to be sent to each client. This event does not need to send any data so there's no need for clients being contacted simultaneously. The event tells the clients to execute an ajax call to your php ajaxHandler.
During each ajax call from the client, your server will check your database for the value of 'waitingClients' in some table you created. If the value is 0, set the value to 1. If the value is greater than 0, increment the waitingClients value by 1. After each ajax call increments the database value, the individual ajax calls are then suspended in a while loop until 'waitingClients' is equal to the value of 'totalClients'. I recommend that you create some kind of entry in your database that records the number of active clients. This makes your 'totalClients' value more dynamic.
You may run into problems with the ajax calls timing out after 30 seconds. Since you're only returning database values, I doubt that you'll run into this problem unless something happens with a client's connection hanging.
Here is some example code (untested):
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script src="ajaxTest.js"></script>
</head>
<body>
<div id="server_message">Waiting for server response</div>
</body>
</html>
Ajax:
$(function() {
var message = $('#server_message');
$.ajax({
url: 'yourAjaxHandler.php',
type: 'POST',
data: {
getAnswer: true
},
success: function(response) {
console.log(response);
message.text(response);
}
})
});
PHP Ajax handler
<?php
$host = 'db host address';
$dbname = 'your database name';
$username = 'your username';
$password = 'your password';
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// Define expected number of total clients. I would recommend having clients log an entry into the database upon initial login/connection.
// This would make tallying the number of clients more dynamic. Otherwise you will always need 4 clients connected
$totalClients = 4;
if (isset($_REQUEST['getAnswer'])) {
$qry = 'SELECT waitingClients from some_table';
$waitingClients = $conn->query($qry);
if ($waitingClients === 0) {
// Create waitingClients in database if it doesn't exist. Otherwise, increment value to 1
$qry = "UPDATE some_table set waitingClients = 1";
$conn->exec($qry);
} else {
// Increment waitingClients
$qry = "UPDATE some_table set waitingClients = waitingClients + 1";
$conn->exec($qry);
}
while ($waitingClients <= $totalClients) {
// The while loop will keep the ajax call active for all clients
// Keep querying database until waitingClients value in DB matches the number of totalClients
$qry = 'SELECT waitingClients from some_table';
$waitingClients = $conn->query($qry);
}
// Set the value of waitingClients back to 0
$qry = "UPDATE some_table SET waitingClients = 0";
$conn->exec($qry);
// Return your server message to the clients
echo json_encode("Your server message"); // You could also store your server message in the database
}

Im trying to find out what is allowing users to withdraw twice the amount or more, of what is in their accounts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a section of my site that allows users to withdraw dogecoins in their accounts to another wallet. Its newly launched today. Today I noticed a user depositing and withdrawing multiple times in a row. The withdrawals were always double the deposits.
Luckily I have a reserve in case something like this happened, and no user accounts will be affected.
I checked the dogechain, and everything seems good there. No transaction malleability, and the amounts were always what was withdrawn. The problem is, by the time it hit the dogechain, it was already doubled, which pretty much means its my site that is allowing it to happen.
The scope of what is going on, is currently outside of what I know of php.
When the user withdraws, they click a button which opens a small withdraw window:
Button code:
Withdraw</div>
Background javascript withdraw() function:
function _requestWithdraw(amount,valid) {
$.ajax({
'url': './content/ajax/withdraw.php?valid_addr='+valid+'&amount='+amount+'&_unique=<?php echo $unique; ?>',
'dataType': "json",
'success': function(data) {
_message='<br><small>';
if (data['error']=='yes') {
if (data['content']==0) _message+='Entered <?php echo $settings['currency_sign']; ?> address is not valid! Please, check the address and try again.';
else if (data['content']==1) _message+='Entered amount is not valid. You probably does not have enough balance for this.';
}
else {
_message+='Amount has been successfuly sended!<br>Transaction ID: '+data['content'];
refreshbalance();
}
_message+='<br><br>Back';
$("#_withdraw_content").html(_message);
}
});
}
var withdrawing;
function withdraw() {
withdrawing=false;
$.msgBox({
title:"Withdraw Funds",
content:"<div id=\"_withdraw_content\"><br><small>Enter valid <?php echo $settings['currency_sign']; ?> address:</small><br><input id=\"w_valid_ltc\" type='text' class='l' style='width: 100%;'><br><br><small>Enter amount to be paid-out:</small><br><input id=\"w_amount\" type='text' class='l' style='width: 100px; text-align: center;'><br><br><small><small>Min. value: <b>0.001</b> <?php echo $settings['currency_sign']; ?><br>We charge a fee <b>0.0002</b> <?php echo $settings['currency_sign']; ?> for each withdrawal.</small></small></div>",
type:"info",
opacity:0.8,
buttons: [{ value: "Withdraw" }, { value: "Cancel" }],
success: function(button) {
if (button=="Withdraw" && withdrawing==false) {
w_amount=$("input#w_amount").val();
w_valid=$("input#w_valid_ltc").val();
if (w_amount!='' && w_valid!='') {
$("#_withdraw_content").html('<div style=\"height: 50px;\"></div> <img src="content/images/ajax_loader.gif">');
withdrawing=true;
_requestWithdraw(w_amount,w_valid);
}
else {
alert('One of required fields stayed empty!');
}
}
}
});
return false;
}
They input the amount they want to withdraw, and what address to send it too.
The background happenings are as follows:
The escaping function:
function prot($hodnota,$max_delka=0) {
$text=mysql_real_escape_string(strip_tags($hodnota));
if ($max_delka!=0) $vystup=substr($text,0,$max_delka);
else $vystup=$text;
return $vystup;
}
This portion is wallet.php, it is called by the withdraw() function window that pops up on the front end:
<?php
$included=true;
include '../../inc/db-conf.php';
include '../../inc/wallet_driver.php';
$wallet=new jsonRPCClient($driver_login);
include '../../inc/functions.php';
if (empty($_GET['amount']) || empty($_GET['valid_addr']) || empty($_GET['_unique']) || mysql_num_rows(mysql_query("SELECT `id` FROM `sellers` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"))==0) exit();
$seller=mysql_fetch_array(mysql_query("SELECT `id`,`balance` FROM `sellers` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"));
$validate=$wallet->validateaddress($_GET['valid_addr']);
if ($validate['isvalid']==false) {
$error='yes';
$con=0;
}
else {
if (!is_numeric($_GET['amount']) || (double)$_GET['amount']>$seller['balance'] || (double)$_GET['amount']<0.001) {
$error='yes';
$con=1;
}
else {
$amount=(double)$_GET['amount']-0.0002;
$txid=$wallet->sendfrom('',$_GET['valid_addr'],$amount);
mysql_query("UPDATE `sellers` SET `balance`=`balance`-".prot($_GET['amount'])." WHERE `id`=$seller[id] LIMIT 1");
$error='no';
$con=$txid;
}
}
$return=array(
'error' => $error,
'content' => $con
);
echo json_encode($return);
?>
Thes following function is called by the function _renewWithdraw() (I think) function after they have input their wallet address and amount of doegcoins and hit "Withdraw"
function refreshbalance() {
$("#balance_").html('<img src="content/images/alternative_loader.gif">');
$.ajax({
'url': './content/ajax/request_balance.php?_unique=<?php echo $unique; ?>',
'dataType': "json",
'success': function(data) {
$("#balance_").html(data['balance']);
}
});
return false;
This is the page that the refreshbalance function calls:
<?php
$included=true;
include '../../inc/db-conf.php';
include '../../inc/functions.php';
if (empty($_GET['_unique']) || mysql_num_rows(mysql_query("SELECT `id` FROM `sellers` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"))==0) exit();
$balance=mysql_fetch_array(mysql_query("SELECT `balance` FROM `sellers` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"));
$balance_=rtrim(rtrim(sprintf("%0.12f",$balance['balance']),'0'),'.');
$return=array('balance' => $balance_);
echo json_encode($return);
?>
Can some please help me with figuring out how, they are withdrawing double their balance, and how to stop it. I dont have a developer at the moment and Im pretty sure this is completely out of my knowledge to fix in a timely manner.
Im guessing either my site is allowing multiple instances to be ran at the same time, and isnt checking the balance in the right order, to prevent that.
Most importantly, im not even sure what the right question to ask is. Im hoping someone will look at the code, and see a better way of doing it.
I think user might have clicked twice or somehow managed to initiate 2 ajax request. Which behaves as 2 different threads simultaneously trying to withdraw (Implement a locking mechanism on per user basis). You should first execute the query and if it is successfully according to your conditions then send wallet form.
Workaround
The quickest way for you might be switch $wallet->sendfrom and mysql_query. positions.
Let say user has 100$ in account and he made a transaction of 100$ (due to bug or some thing), It becomes 2 Ajax request.
First thread checks the user current balance is 100$, its enough balance process and calls the send wallet information (let say it take 30 second).
Meanwhile another thread comes in, it also check the current balance (100$ which is the same as of the first thread read, and haven't returned yet from $wallet->sendfrom). it will also send wallet and on return both with will execute the update sql script.
$txid=$wallet->sendfrom('',$_GET['valid_addr'],$amount);
mysql_query("UPDATE `sellers` SET `balance`=`balance`-".prot($_GET['amount'])." WHERE `id`=$seller[id] LIMIT 1");
Switching these lines will reduce the chance of error. (You have to implement some locking mechanism for 100% surety).
mysql_query("UPDATE `sellers` SET `balance`=`balance`-".prot($_GET['amount'])." WHERE `id`=$seller[id] LIMIT 1");
$txid=$wallet->sendfrom('',$_GET['valid_addr'],$amount);
Also try to disable the button/Link which initiate the withdraw process as soon as user enters in this mode, and renable it once ajax request is successful. It will reduce the chance of error from front end.
Updated :
Simulate locking with session variable
I believe PHP does not support a nice and clean way for thread safety. So here is workaround using session variable as we require locking per user basis.(People do use flock for similar kind of functionality)
Separate session variables are created for each user $_SESSION["variable_name"], so we can use that if the current user transaction is locked or not.
First step would be to check if $_SESSION["isLocked"] is true or not, (it could be not set if user comes first time). If its true, Means a transaction is already in progress and exit the script with some error.
Secondly if its not set or contains false (Means no transaction in progress) so first step would be to assign true. and processed with processing of withdraw.
Finally when script is done with the all the processing set this session variable to false.
Here is sample code for above steps.
<?php
session_start();
if (isset($_SESSION["isLocked"]) && $_SESSION["isLocked"] === true) {
echo "A transaction is already in progress.";
exit();
}
else {
//hold the lock
$_SESSION["isLocked"] = true;
$_SESSION["lock_time"] = time(); //current time (can be used to unlock the current user session after some time in case of error/bugg or some thing)
//perform wallet api calls
echo "Processing data";
//you must check if above call is success full
//then run update query for updating the balance.
//release the lock
$_SESSION["isLocked"] = false;
}
Please note: Its not thread safety but a way to reduce the chances of errors.

Categories