PHP - Rate Limiting In Php Websockets
function wsProcessClientMessage($clientID, $opcode, &$data, $dataLength) { global $wsClients; // check opcodes if ($opcode == WS_OPCODE_PING) { // received ping message return wsSendClientMessage($clientID, WS_OPCODE_PONG, $data); } elseif ($opcode == WS_OPCODE_PONG) { // received pong message (it's valid if the server did not send a ping request for this pong message) if ($wsClients[$clientID][4] !== false) { $wsClients[$clientID][4] = false; } } elseif ($opcode == WS_OPCODE_CLOSE) { // received close message if (substr($data, 1, 1) !== false) { $array = unpack('na', substr($data, 0, 2)); $status = $array['a']; } else { $status = false; } if ($wsClients[$clientID][2] == WS_READY_STATE_CLOSING) { // the server already sent a close frame to the client, this is the client's close frame reply // (no need to send another close frame to the client) $wsClients[$clientID][2] = WS_READY_STATE_CLOSED; } else { // the server has not already sent a close frame to the client, send one now wsSendClientClose($clientID, WS_STATUS_NORMAL_CLOSE); } wsRemoveClient($clientID); } elseif ($opcode == WS_OPCODE_TEXT || $opcode == WS_OPCODE_BINARY) { // received text or binary message if (function_exists('wsOnMessage')) wsOnMessage($clientID, $data, $dataLength, $opcode == WS_OPCODE_BINARY); } else { // unknown opcode return false; } return true; } Similar TutorialsSo I've been using this websocket: http://code.google.com/p/phpwebsocket/
Love it because I don't know javascript as well as I do PHP. (Absolutely hated learning socket.io and their style of javascript, just gave up on it).
Anyways, I'm using MYSQL with the php socket for the chatroom authentication with my forum. (Sending the cookie values to the socket, to authenticate user). It's working fine and the MYSQL only get's called for each time a user is authenticated (logged into the websocket). The usernames and sessions are actually stored in a Temporary array which is nice. So only on authentication it queries the database for the authentication itself. (Very lightweight and a smart way for a chat system).
My question is, how does this compare to a node.js and socket.io server with a MYSQL plugin, etc? seems like that route would actually be more intensive?
I don't even need to include the socket.io.js for the client / PHP setup I have here as well. This way seems lightweight in my opinion (clientside) but not sure on the server end.
Thoughts?
TLDR: Running a PHP Websocket as compared to a node.js/socket.io server with mysql plugins the same in performance? Is it even noticeable? Should I be worried?
Edit: Disregard compatibility issues too. ( Using this http://tools.ietf.org/html/rfc6455 protocol is fine for my audience and intentions )
Edited by Monkuar, 02 December 2014 - 07:46 PM. Since I got my websocket PHP server running nicely with my MYSQL, I can now have some fun
Attack speed is very simple, but I need your help with the unixtimestamp.
For example, There is a field name called "last_attack" and each time a user attacks a mob and a skill was performed; it will be updated with:
time();Then I disable the attack button for 2 seconds client side, but I also check that value against time() serverside as well. Now let's say the user's attack speed is 1.30% I want to make that Attack Speed check, to check it dynamically. It should now check only if the attack was less than 1.7 seconds ago instead of 2 seconds. How do I split up the unixtimestamp to work with percents? Edited by Monkuar, 03 December 2014 - 02:11 PM. Hello. I have written this script where user restaurant owner can add his place to the database of all local restaurants. (insert basic information into database, add up to 3 images, thumbnail creation, insert image information to database). It works well on localhost, but i would like some suggestions for improvement. Im not very sure of its structure, it may not execute well once it is online. And i also think there are too many "IF's". But i really have no idea how to do it any other way. Thanks for all the suggestions. Code: [Select] <?php if(!defined('PROTECTION') || constant('PROTECTION') != 'demover') { echo "fuck off intruder!"; exit; } $naziv = mysql_real_escape_string($_POST['Naziv']); $naslov = mysql_real_escape_string($_POST['Naslov']); $kraj = mysql_real_escape_string($_POST['Kraj']); $telefon = mysql_real_escape_string($_POST['Telefon']); $web = "http://www.".mysql_real_escape_string($_POST['Spletna']); $gm = mysql_real_escape_string($_POST['Lokacija']); //$gmaps = gmParse($gm); $gmaps = 10; $fill="INSERT INTO bpoint (sName, sAddr, placeID, sPhone, sWeb, sGMaps, companyID) VALUES ('$naziv','$naslov','$kraj','$telefon','$web','$gmaps','$cID')"; if (mysql_query($fill)) { $lastID=mysql_insert_id(); $path="./truck/".$cID."/".$lastID; $pname=$_FILES["pic"]["tmp_name"]; $num=0; if (count($_FILES["pic"]) && mkdir($path, 0777)) { include "thumbs.php"; foreach($pname as $imag){ $bname=date("YmdHis").$num; $num++; $finalpath=$path."/".$bname.".jpg"; $finalthumb=$path."/".$bname."_thumb.jpg"; if($imag!="") { if (move_uploaded_file($imag, $finalpath)) { make_thumb($finalpath,$finalthumb,150); mysql_query("INSERT INTO images (name, companyID) VALUES ('$finalpath', '$cID')"); } } } } unset($_FILES["pic"]); } else {die(mysql_error());} ?> How do you establish a tax rate in a MySQL database to use in a form calculation, then be able to change the value to a new constant value from the form? Hi, I am trying to store the view rate of articles so that I can retrieve them later on by "the most popular". I have searched around but cannot find a straight answer. Can anyone point me towards the right direction? Edit: Never mind, I was over complicating the logic behind this. Alight, I'm trying to figure out the error string for an api http://www.haloreachapi.net/wiki/API_rate_limits The wiki says the limit is 300rpm I tried to run this in two tabs on my browser still won't give me the error string, how can it be done faster? P.s. Api key will be changed in the near future don't waste your time.. <?php $gamertag = "l RaH l"; $url = "http://www.bungie.net/api/reach/reachapijson.svc/game/metadata/30cRxVA9J73esG388CzmOXUVRo5VjYhSfI2qBaqcMzs="; $t_start = microtime(true); for($i = 0; $i < 301; $i++) { $file = file_get_contents($url); echo "Iteration ".($i + 1)."<br>\n"; } $exectime = microtime(true) - $t_start; echo "Execution time: " . round($exectime, 4) . "<br><br>\n\n"; $json = json_decode($file, 1); print_r($json); ?> Php Folks, I started learning php originally from 2015. On & off. Part time. Started getting into it seriously around 2017. From home. No classes. From forums and php manual and tutorial sites. Still at oop & mysqli. Had ups & downs as first learnt a lot of old stuffs then found out they been deprecated. For example, if I had originally known pdo is modern over mysqli then I would started on pdo from beginning. Got no real guidance anywhere. Just learnt things the hard way, coming across obstacles and bugging forums. Half-way learning mysqli I come across pdo. So you see, if I had taken school classes then they would have started me on the new stuffs. But because I learning from home, I came across a lot of old tutorials and started from there without knowing they are sort of outdated stuffs. Anyway, I don't like quitting half-way and so did not quit mysqli for pdo when a lot of programmers advised me to dump mysqli for pdo. Thought, since I "wasted time" on mysqli then might aswell build a few sites with it before ditching it. Part time study. Full time working on projects for 3yrs now. projects are own "hobby sites" so to speak and not for clients. I am not the freelancer type or professional type. layman type. Never really have launched any sites. I finish one site/project then move onto another project for learning purpose. So I learn very little then moving onto building sites based on what little I learnt. When I learnt how to use the SELECT, INSERT. DELETE, UPDATE in sql, I jumped into learning to build my own membership site (reg, log-in, logout, etc. pages) to deal with mysql db. So far, built membership parts (login, logout, account homepage, pagination). All by copying codes from tutorials and forums from people like you and changing here and there according to my needs. And when I get stuck. I bug programmers like you. I do have a conscious and do not like plagiarism even while learning and so everytime I copy paste codes from tutorials or forums (where I get help), I retype every line and then delete the copy-pasted lines and leave my typed lines in the file. that way, I feel good I atleast made some effort to build the site rather than copy & paste. Then, I change the codes here and there to suit my purpose. Don't you like me ? ;). You probably chuckling inside reading this. Here's an example of how I copy-paste then re-write the lines. <?php //Code from: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_login_form ?> <!DOCTYPE html> <!DOCTYPE html> <html> <html> <head> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> <style> body {font-family: Arial, Helvetica, sans-serif;} body {font-family: Arial, Helvetica, sans-serif;} form {border: 3px solid #f1f1f1;} form {border: 3px solid #f1f1f1;} input[type=text], input[type=password] { input[type=text], input[type=password] { width: 100%; width: 100%; padding: 12px 20px; padding: 12px 20px; margin: 8px 0; margin: 8px 0; display: inline-block; display: inline-block; border: 1px solid #ccc; border: 1px solid #ccc; box-sizing: border-box; box-sizing: border-box; } } button { button { background-color: #4CAF50; background-color: #4CAF50; color: white; color: white; padding: 14px 20px; padding: 14px 20px; margin: 8px 0; margin: 8px 0; border: none; border: none; cursor: pointer; cursor: pointer; width: 100%; width: 100%; } } button:hover { button:hover { opacity: 0.8; opacity: 0.8; } } .cancelbtn { .cancelbtn { width: auto; width: auto; padding: 10px 18px; padding: 10px 18px; background-color: #f44336; background-color: #f44336; } } .imgcontainer { .imgcontainer { text-align: center; text-align: center; margin: 24px 0 12px 0; margin: 24px 0 12px 0; } } img.avatar { img.avatar { width: 40%; width: 40%; border-radius: 50%; border-radius: 50%; } } .container { .container { padding: 16px; padding: 16px; } } span.psw { span.psw { float: right; float: right; padding-top: 16px; padding-top; 16px; } } /* Change styles for span and cancel button on extra small screens */ /* Change styles for span and cancel button on extra small screens */ @media screen and (max-width: 300px) { @media screen and (max-width: 300px) { span.psw { span.psw { display: block; display: block; float: none; float: none; } } .cancelbtn { .cancelbtn { width: 100%; width: 100%; } } } } </style> </style> </head> </head> <body> <body> <h2>Login Form</h2> <h2>Login Form</h2> <form action="/action_page.php" method="post"> <form action="/action_page.php" method="post"> <div class="imgcontainer"> <div class="imgcontainer"> <img src="img_avatar2.png" alt="Avatar" class="avatar"> <img src="img_avatar2.png" alt="Avatar" class="avatar"> </div> </div> <div class="container"> <div class="container"> <label for="uname"><b>Username</b></label> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="uname" required> <input type="text" placeholder="Enter Username" name="uname" required> <label for="psw"><b>Password</b></label> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <input type="password" placeholder="Enter Password" name="psw" required> <button type="submit">Login</button> <button type="submit">Login</button> <label> <label> <input type="checkbox" checked="checked" name="remember"> Remember me <input type="checkbox" checked="checked" name="remember"> Remember me </label> </label> </div> </div> <div class="container" style="background-color:#f1f1f1"> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">Cancel</button> <button type="submit" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="#">password?</a></span> <span class="psw">Forgot <a href="#">password?</a></span> </div> </div> </form> </form> </body> </body> </html> </html> One thing I gain from this type of re-writings is that, typing the same thing over and over again sort of gets codes sink into my subconscious. Helps to memorise the codes. Ok. So now you know a little about me. As you can see, I always start on somebody else's skeleton, be it from a tutorial forum or a tutorial site or php manual. I have completed 3 websites, so to speak, in that way. 2 days ago I thought, I been doing this for 3yrs now. Let's test and see how well I can code without working on somebody else's skeleton. No copy-pasting from forums or tutorial sites or php manual. And so, look what I did. I coded all the following from my own memory. let me know how well I did. That repetition of lines re-writing has done me some good to memorise codes. I did make 2 mistakes. Note the comments in the code. You will notice "MY CODE ..." and then a correction "WHAT IT SHOULD BE ...". Compare the 2 and see how close or far away I was from the correction. And then give me score from 1-10 (where 10 is best) how well I did as a home study middle aged guy. Hard learning things at middle age. I think, if I had toild you I started learning a month ago then you'd give 9/10 but because it's been 3 yrs, you'll give 1/9 or 0. Just bear in mind it's not easy to learn things at middle age and remember them without forgetting. I learn fast but forget double fast. Lol! One thing though. My codes are not working. They do not INSERT data into db nor extract & display data from db. What is wrong ? TEST NUMBER 1: On this one, I first tried displaying data rows from mysql using mysqli_stmt_get_result(). That failed and so I tried with mysqli_stmt_bind_result() afterwards and so bear that in mind and don't ask me why I used both instead of one. Clicking the "search" button gives no response. Nothing happens on page. I did search for a ketywords that exist in each mysql tbl columns. <?php include('error_reporting.php'); require('conn.php'); //require('search_form.php'); ?> <form name = "search" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="keywords">Keywords:*</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords" required> <br> <label for="search_column">Search in ... ?</label> <select name="search_column" id="search_column"> <option value="page_url">Page Url</option> <option value="link_anchor_text">Link Anchor Text</option> <option value="page_description">Page Description</option> <option value="keyphrase">Keyphrase</option> <option value="keywords">Keywords</option> </select> <br> <label for="tos_agreement">Agree to TOS or not ? *</label> <select name="tos_agreement" id="tos_agreement" required> <option value="Yes">Yes</option> <option value="No">No</option> </select> <br> <input type="button" name="search_links" id="search_links" value="Search Links!"> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { if(ISSET($_POST['search_links'])) { $_POST['page_url']; $_POST['link_anchor_text']; $_POST['page_description']; $_POST['keyphrase']; $_POST['keywords']; //I WROTE 2 QUERIES HERE AS I WASN'T SURE HOW IT SHOULD BE. FINALLY, STUCK TO THE LATTER. HOWEVER, ON TESTS NONE OF THEM WORK! //QUERY 1. $query = "SELECT FROM links (page_url,link_anchor_text,page_description,keyphrases,keywords) WHERE keywords = ?"; //QUERY 2... $query = "SELECT page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE page_url = ?, link_anchor_text = ?, page_description = ?, keyphrases = ?, keywords = ?"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'sssss',$_POST['page_url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keyphrase'],$_POST['keywords']); //WRONG: FORGOT TO ADD "$result = " ... //mysqli_stmt_bind_result($stmt,$page_url,$link_anchor_text,$page_description,$keyphrase,$keywords); //CORRECTION: WHAT IT SHOULD BE ... $result = mysqli_stmt_bind_result($stmt,$page_url,$link_anchor_text,$page_description,$keyphrase,$keywords); //mysqli_stmt_execute($stmt);WRONG! THIS LINE SHOULDN'T EXIST UNLESS IT'S mysqli_stmt_get_result(). mysqli_stmt_fetch($stmt); //WASN'T SURE WHICH OF THE 3 FOLLOWING LINES ARE CORRECT REGARDING THE WHILE LOOP. FINALLY, STUCK TO THE 1ST LINE ... //1)... while(mysqli_stmt_fetch($stmt)) //2)... //while(mysqli_fetch_array($stmt,mysqli_assoc)) //3)... //while(mysqli_fetch($stmt)) { echo "url"; echo "<br>"; echo "anchor_text"; echo "<br>"; echo "description"; echo "<br>"; echo "keyphrases"; echo "<br>"; echo "keywords"; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt);//CORRECTION: THIS SHOULD BE OUTSIDE THE "WHILE LOOP" mysqli_close($conn);//CORRECTION: THIS SHOULD BE OUTSIDE "IF" } else { echo "1. QUERY failed!"; } if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'sssss',$_POST['page_url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keyphrases'],$_POST['keywords']); mysqli_stmt_execute($stmt); //CORRECTION: FORGOT TO ADD "$result = " $result = mysqli_stmt_get_result($stmt); /* MY CODE WRONG! TRIED ECGHOING THE ARRAY "$row[]"! while($row = mysqli_fetch_array($result,mysqli_assoc)) { echo $row['page_url']; echo "<br>"; echo $row['link_anchor_text']; echo "<br>"; echo $row['page_description']; echo "<br>"; echo $row['keyphrases']; echo "<br>"; echo $row['keywords']; echo "<br>"; echo "|"; echo "<br>"; } */ //CORRECTION: HOW IT SHOULD BE: //$VARIABLE SHOULD BE ECHOED. NOT THE ARRAY $row[] while($row = mysqli_fetch_array($result,mysqli_assoc)) { $page_url = $row['page_url']; echo $page_url; echo "<br>"; $link_anchor_text = $row['link_anchor_text']; echo $link_anchor_text; echo "<br>"; $page_description = $row['page_description']; echo $page_description; echo "<br>"; $keyphrases = $row['keyphrases']; echo $keyphrases; echo "<br>"; $keywords = $row['keywords']; echo $keywords; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("2. QUERY failed!"); } } } ?>
TEST NUMBER 2: On this one, clicking the "submit links" button gives no response atall!.
<?php include('error_reporting.php'); require('conn.php'); //equire('link_submission_form.php'); ?> <form name = "submit_link" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="domain">Domain:</label> <input type="text" name="domain" id="domain" placeholder="Input Domain"> <br> <label for="domain_email">Domain Email:</label> <input type="email" name="domain_email" id="domain_email" placeholder="Input Domain Email"> <br> <label for="url">Url:</label> <input type="url" name="url" id="url" placeholder="Input Url"> <br> <label for="link_anchor_text">Link Anchor Text:</label> <input type="text" name="link_anchor_text" id="link_anchor_text" placeholder="Input Link Anchor Text"> <br> <textarea rows="10" cols="20">Page Description</textarea> <br> <label for="keywords">Keywords:</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords related to Page"> <br> <label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value="yes">Yes</option> <option value="no">No</option> </select> <br> <input type="button" name="submit_link" id="submit_link" value="Submit Link!"> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { if(ISSET($_POST['submit_link'])) { $query = "INSERT into links (domain,domain_email,url,link_anchor_text,page_description,keywords) VALUES ?,?,?,?,?,?"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'ssssss',$_POST['domain'],$_POST['domain_email'],$_POST['url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keywords']); mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("INSERT failed!"); } } } ?>
What is wrong ? Why both codes don't work ? Edited July 14, 2020 by 2020 I am getting Warning: Division by zero in /rate.php on line 64 <?php function rateinstar($value) { preg_match_all('#([0-9]+)([0.0-9.9]+)|([0-9]+)#',$value,$tek); if($tek[0][1] > 0) { $rate=$tek[0][0]/$tek[0][1]; } else { $rate=0; } preg_match_all('#([0-9]+).([0-9]+)#',round($rate,1),$decm); if($decm[2][0] != "") { $no=($decm[1][0]*2)+1; for($i=1;$i<=10;$i++) { if($i<=$no){ if($i%2!=0) echo '<span class="starin piece1"></span>'; else echo '<span class="starin piece2"></span>'; }else{ if($i%2!=0) echo '<span class="starin piece3"></span>'; else echo '<span class="starin piece4"></span>'; } } }else{ for($i=1;$i<=10;$i++) { if($i<=$rate*2){ if($i%2!=0) echo '<span class="starin piece1"></span>'; else echo '<span class="starin piece2"></span>'; }else{ if($i%2!=0) echo '<span class="starin piece3"></span>'; else echo '<span class="starin piece4"></span>'; } } } } function rateintext($value) { preg_match_all('#([0-9]+)([0.0-9.9]+)|([0-9]+)#',$value,$tek); $rate=$tek[0][0]/$tek[0][1]; preg_match_all('#([0-9]+).([0-9]+)#',round($rate,1),$decm); return round($rate,1); } ?> Hi, am trying without much luck, (I am new), to define an exchange rate on the page and then mutiplying it by a value I am extracting from a mysql db. I write the value as below normally but having trouble writing this entry and multiplying it by my defined exchanged rate of say 2.22. <?php if(!empty($row['Band_1_Price'])) {echo "<div class=pricing_box_right2>£".$row['Band_1_Price']."</div></div>"; } ?> Thanks so much. Hi My website is a Wordpress WooCommerce. I modified the PHP function that worked well before I added the multiple customer roles. I have regular customers and regular and tier-level wholesalers. I live in Canada and with have two taxes to apply (GST & PST). We also have customers/wholesalers that get exempted from one tax (PST) only or both taxes. I have one regular wholesale role with two tax exemption roles: 'wholesale_customer', 'wholesale_pst_exempt', 'wholesale_tax_exempt'. I have 4 tier levels wholesale roles with each their own tax exemption roles: 'wholesale_silvia_silver', 'wholesale_silvia_gold', 'wholesale_silvia_premium', 'wholesale_silvia_union' 'wholesale_silvia_silver_pst_exempt', 'wholesale_silvia_gold_pst_exempt', 'wholesale_silvia_premium_pst_exempt', 'wholesale_silvia_union_pst_exempt' 'wholesale_silvia_silver_tax_exempt', 'wholesale_silvia_gold_tax_exempt', 'wholesale_silvia_premium_tax_exempt', 'wholesale_silvia_union_tax_exempt' The tier levels are new and I'm trying to update my existing function that applies different tax rates based on customer user roles. I also have filters to alter the shipping tax for the different tax class based on the customer role. Here are the function and filter that I have updated to add the additional tier level wholesale roles. The changes I've made are not working because I don't see the tax exemptions. Both taxes are always being applied. Can someone help me figure out what I've done wrong to the code that stopped it from working? I'm not proficient in PHP, so was trying my best to make this work. /* * APPLY DIFFERENT TAX RATE BASED ON CUSTOMER USER ROLE * (Code compacted in one unique hook instead of 5 functions with the same hook) */ function all_custom_tax_classes( $tax_class, $product ) { global $current_user; // Getting the current user $curr_user = wp_get_current_user(); $curr_user_data = get_userdata($current_user->ID); // 1 customer_tax_exempt /* special tax rate: zero if role: Customer Tax Exempt */ /*if ( in_array( 'customer_tax_exempt', $curr_user_data->roles ) ) $tax_class = 'CustomerTaxExemptClass'; // 2 customer_pst_exempt // special tax rate: charge only GST if role: Customer PST Exempt if ( in_array( 'customer_pst_exempt', $curr_user_data->roles ) ) $tax_class = 'CustomerPSTExemptClass'; */ // 3, 4 & 5 WHOLESLE SUITE SPECIAL WHOLESALE TAX RATES if (isset($current_user) && class_exists('WWP_Wholesale_Roles')) { $wwp_wholesale_roles = WWP_Wholesale_Roles::getInstance(); $wwp_wholesale_role = $wwp_wholesale_roles->getUserWholesaleRole(); // special tax rate: charge both PST and GST if roles: Wholesale Customer, Wholesale Silvia Silver, Wholesale Silvia Gold, Wholesale Silvia Premium, Wholesale Silvia Union if (!empty($wwp_wholesale_role) && in_array('wholesale_customer', $wwp_wholesale_role) && in_array('wholesale_silvia_silver', $wwp_wholesale_role) && in_array('wholesale_silvia_gold', $wwp_wholesale_role) && in_array('wholesale_silvia_premimum', $wwp_wholesale_role) && in_array('wholesale_silvia_union', $wwp_wholesale_role)) { // Where 'wholesale_customer, wholesale_silvia_silver, wholesale_silvia_gold, wholesale_silvia_premium, wholesale_silvia_union' are the names of the wholesale roles to target $tax_class = 'WholesalePSTGST'; } // special tax rate: charge only GST if roles: Wholesale PST Exempt, Wholesale Silvia Silver PST Exempt, Wholesale Silvia Gold PST Exempt, Wholesale Silvia Premium PST Exempt, Wholesale Silvia Union PST Exempt if (!empty($wwp_wholesale_role) && in_array('wholesale_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_silver_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_gold_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_premium_pst_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_union_pst_exempt', $wwp_wholesale_role)) { // Where 'wholesale_pst_exempt, wholesale_silvia_silver_pst_exempt, wholesale_silvia_gold_pst_exempt, wholesale_silvia_premium_pst_exempt, wholesale_silvia_union_pst_exempt' are the names of the wholesale roles to target $tax_class = 'WholesalePSTExempt'; } // special tax rate: zero if roles: Wholesale Tax Exempt, Wholesale Silvia Silver Tax Exempt, Wholesale Silvia Gold Tax Exempt, Wholesale Silvia Premium Tax Exempt, Wholesale Silvia Union Tax Exempt if (!empty($wwp_wholesale_role) && in_array('wholesale_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_silver_tax_exempt', $wwp_wholesale_role)&& in_array('wholesale_silvia_gold_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_premium_tax_exempt', $wwp_wholesale_role) && in_array('wholesale_silvia_union_tax_exempt', $wwp_wholesale_role)) { // Where 'wholesale_tax_exempt, wholesale_silvia_silver_tax_exempt, wholesale_silvia_gold_tax_exempt, wholesale_silvia_premium_tax_exempt, wholesale_silvia_union_tax_exempt' are the names of the wholesale role to target $tax_class = 'WholesaleZeroTax'; } } return $tax_class; } /* ADDITIONAL FILTERS TO ALTER THE SHIPPING TAX FOR DIFFERENT TAX CLASSES BASED ON CUSTOMER USER ROLE */ add_filter( 'woocommerce_product_get_tax_class', 'all_custom_tax_classes', 1, 2 ); add_filter( 'woocommerce_product_variation_get_tax_class', 'all_custom_tax_classes', 1, 2 ); add_filter( 'option_woocommerce_shipping_tax_class' , function( $option_value ) { global $wc_wholesale_prices; if ( $wc_wholesale_prices && is_a( $wc_wholesale_prices , 'WooCommerceWholeSalePrices' ) ) { $current_user_wholesale_roles = $wc_wholesale_prices->wwp_wholesale_roles->getUserWholesaleRole(); if ( in_array( 'wholesale_customer', $current_user_wholesale_roles ) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_silver', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_gold', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_premium', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_silvia_union', $current_user_wholesale_roles) ){ return 'wholesalepstgst'; } elseif (in_array( 'wholesale_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_silver_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_gold_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_premium_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_silvia_union_pst_exempt', $current_user_wholesale_roles) ){ return 'wholesalepstexempt'; } elseif (in_array( 'wholesale_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_silver_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_gold_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_premium_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } elseif (in_array( 'wholesale_silvia_union_tax_exempt', $current_user_wholesale_roles) ){ return 'wholesalezerotax'; } } return $option_value; } , 10 , 1 );
Thank you Lyse Edited June 18, 2019 by LyseSpecify website platforms Hi all,
I am building a random prize assigner function based on weighted percentages.
I am able to assign a basic true/false weighting but am struggling to form a way of selecting an array based prize based on the win rate.
Heres my current code:
function selectPrize() { $prizes = array( 0 => array( 'name' => 'Top Prize', 'rate' => 50 ), 1 => array( 'name' => 'Middle Prize', 'rate' => 30 ), 2 => array( 'name' => 'Bottom Prize', 'rate' => 20 ), ); // oops } selectPrize();Could somebody please give me pointers on how i could approach this? Thanks. Edited by biggieuk, 19 June 2014 - 05:14 AM. /* Output of the table will display the Suite based on the distinct date. The pass rate percentage calculate based on the Suite1 and app1 and the specific date. For example at Apr 4 2011, I need to Sum the total passcount,failcount,errorcount of Bluetooth, GPSA, EMIReceiver($app1) of XA9 on Real MXE($suite1) , then calculate the passrate percentages. But I fail to get the correct value of the passcount, failcount, errorcount value.Helps! Output of the table suite Date Percentages(pass rate) XA9 on Real MXE Apr 4 2011 9:47AM 99.94% XA9 on Real MXE Apr 5 2011 10:48AM 99.94% XA9 on Real MXE Apr 6 2011 9:49AM 99.95% XA9.5 on Real EXA_B40 Apr 4 2011 7:06AM 99.94% XA9.5 on Real EXA_B40 Apr 5 2011 7:14AM 99.93% XA9.5 on Real EXA_B40 Apr 6 2011 7:29AM 99.93% */ $suite1 --> array value (XA9 on Real MXE, XA9.5 on Real EXA_B40) $app1 --> array value (Bluetooth, GPSA, EMIReceiver) if(is_array($suite_type1)){ foreach($suite_type1 as $suite1) { $sql222="Select Distinct a.StopDTTM from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$fromdate' and a.StopDTTM<='$to_date' and a.SuiteFilePath like '%$Program%' and a.SuiteFileName='$suite1'"; $result222=mssql_query($sql222,$connection) or die("Failed Query of".$sql222); while($row222 = mssql_fetch_array($result222)) { $datetotest = $row222[0]; $days_to_add = 1; $tilldate = fnc_date_calc($datetotest,$days_to_add); //Query the result based on the date $sql223="Select Distinct a.SuiteFileName, a.SuiteID,a.StopDTTM from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$row222[0]' and a.StopDTTM<='$tilldate' and a.SuiteFilePath like'%$Program%' and a.SuiteFileName='$suite1' order by a.StopDTTM"; $result223=mssql_query($sql223,$connection) or die("Failed Query of".$sql223); while($row223 = mssql_fetch_row($result223)){ foreach($app_type1 as $app1) { $sql3="Select Sum(b.passcount),Sum(b.failcount),Sum(b.errorcount) from Suite a,Test b where a.SuiteID=b.SuiteID and b.SuiteID=a.SuiteID and a.StopDTTM>='$row222[0]' and a.StopDTTM<='$tilldate' and a.SuiteFilePath like '%$program%' and a.SuiteFileName = '$suite1' and b.Product='$app1'"; $result3=mssql_query($sql3,$connection) or die("Failed Query of ". $sql3); $row3 = mssql_fetch_row($result3); $total_passcount+=$row3[0]; $total_failcount+=$row3[1]; $total_errorcount+=$row3[2]; } $overall_total=$total_passcount+$total_failcount+$total_errorcount; echo "<tr>"; echo "<td><a href='detailsreport.php?suiteID=".$row223[1]."&suitetype=".$row223[0]."&fromdate=".$fromdate."&to_date=".$to_date."&date=".$row222[0]."&tilldate=".$tilldate."&SuiteFilePath=".$Fprogram."'>" . $row223[0] . "</a></td>"; //Suite File Name echo "<td>" . $row223[2] . "</td>"; //Pass percentage if($total_passcount>0){ echo "<td bgcolor=00FF33>" . number_format((($total_passcount/$overall_total)*100),2)."%</td>"; } else{ echo "<td bgcolor=00FF33>0%</td>"; } } } } echo "</table>"; } Hello guys, I am new to PHP programming. I am trying to figure out how to use PHP language to transmit/write characters to a USB port device at 9600 baud rate 8-N-1. Basically I just need the PHP coding to allow me to send stuff to the USB device but I have no idea how I can interface this. I did some researching but most were for RS-232 COM Port. I can't find the proper one for USB. If someone can help me out, that would be awesome. Thank you! Hi, I am wondering if it is possible to monitor how long someone is on a website for and to limit them for example: 30 minutes. An example of this would be one of those Tv Online websites which allow you to only watch 30 minutes of video time. If you try refreshing the page it will still not allow you. My question is, Is it an ip check which does this? Sorry If it such a broad topic. Nick OMG! Crafting well thought out business logic is such a PITA sometimes! I am working on an ecommerce site that sells subscriptions, books, gear, etc. Similar to a lot of online newspapers, I have a "Subscribe" button in my website mast where people can buy a subscription. After clicking on that button, the user is first presented with different subscription offers (e.g. sliver, gold, platinum), and then I have a one-page checkout form where they create an account - kind of important for an online subscription! - and they pay with a credit card. Easy! Trying to be a nice guy, I decided to add the ability to choose a subscription from my online store as well. (Presumably you want to offer as many ways for people to buy things from you as possible, right?) Well here is the issue I just discovered... What happens if a person is browsing through my product catalog, and they add multiple subscriptions to their shopping cart? Of course I would welcome the extra $$$, but I just realized that would break how people create their accounts and pay, because above I assume that ONE person, buys ONE subscription and pays for it in ONE transaction. So my questions is, "Would it be a mortal sin to limit people to buying only ONE subscription at a time if they do so while in my online store?" I would hope that people would get that, but as we know, users do some crazy stuff!! In fairness, if you went to buy a subscription at the Wall Street Journal or any other large newspaper/magazine, you would be forced to do one subscription per transaction. I am just wondering what happens if someone goes on a shopping spree in my online store, buys several books, some t-shirts, and decides he/she also wants to buy 5 subscriptions on the spot. Thoughts?
Im not sure f this is the right spot for this or not but... I have a website that has a content box that has a fixed height and width. How would i make it so after the box is full it puts a link to read more at the bottom of it? Also images may be used as well. Its also for a wordpress blog Hey there - I have been trying to limit the number of comments a user can make per day on my social network. Thanks to great help on here I am getting really close, however, there are some bugs that have me banging my head against the wall. I am able to limit, but now, its 1. not limiting PER day and limiting all around ( meaning: I can't make any comments at all today ) 2. it is limiting for EVERY user as opposed to limiting a specific user Here is the code I have: Code: [Select] if(isset($_POST['commentProfileSubmit'])) { if($_POST['ProfileComment'] == "" || $_POST['ProfileComment'] == "Tell the community what's on your mind...") { $valid = false; $error_msgs_comments[] = "Whoops! You forgot to write your airwave."; }else{ if($_POST['ProfileComment'] == "" || $_POST['ProfileComment'] == "Leave ".$prof->first_name." a comment here...") { $valid = false; $error_msgs_comments[] = "Whoops! You forgot to write your comment."; }else{ /* if the person signed in is NOT the profile */ $query = "SELECT * FROM `cysticUsers` WHERE `id` = '" . $prof->id . "'"; $request = mysql_query($query,$connection) or die(mysql_error()); $result = mysql_fetch_array($request); $max_post_per_day = 5; $Email = $result['Email']; $check_profi = $result['check_profi']; $check_reply = $result['check_reply']; if($prof->id != $auth->id && $check_profi == 'checked' && $max_post_per_day < 5) { $to = $Email; $subject = "$auth->first_name $auth->last_name commented on your profile on CysticLife"; $message = "$auth->first_name $auth->last_name commented on your profile on CysticLife: <br /><br />\"$body\"<br /><br /> <a href='http://www.cysticlife.org/Profile_build.php?id=" . $prof->id . "'>Click here to view</a><br /><br />Do LIFE,<br /> The CysticLife Team"; $from = "CysticLife <noreply@cysticlife.org>"; $headers = 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n"; $headers .= "From: $from"; mail($to, $subject, $message, $headers); } $query = "SELECT COUNT(*) FROM `CysticAirwaves` WHERE `FromUserID` = $auth->id AND `date` = CURDATE()"; $result = mysql_query($query, $connection); $post_count = mysql_result($result, 0); if($post_count >= $max_posts_per_day) { echo "You have reached the maximum number of posts for the day. Try again tomorrow"; } else { $comment = mysql_real_escape_string($_POST['ProfileComment']); $query = "INSERT INTO `CysticAirwaves` (`FromUserID`, `ToUserID`, `comment`, `status`, `statusCommentAirwave`, `date`, `time`) VALUES ('{$auth->id}', '{$prof->id}', '{$comment}', 'active', 'active', CURDATE(), CURTIME())"; mysql_query($query, $connection) or die(mysql_error()); } if($auth->id == $prof->id) { $just_inserted = mysql_insert_id(); $query = "UPDATE `CysticAirwaves` SET `status` = 'dead' WHERE `FromUserID` = '" . $auth->id . "' AND `ToUserID` = '" . $prof->id . "' AND `id` != '" . $just_inserted . "'"; $request = mysql_query($query,$connection); } } } } thanks so much in advanced Following on from the excellent help in the thread at http://www.phpfreaks.com/forums/php-coding-help/using-a-generated-row-number-in-another-query I have another question regarding the League Standings that are generated there. I want to have another version that limits the records to the last 5 games for each team. Just using 'LIMIT 5' would return the first five teams and all their records but I want it to retrieve all of the teams and each teams last five records (games). The easy way would be to restrict a the dates but as games get postponed and moved using WHERE with a specific date would not guarantee the same number of games for each team. There is the possibility that this could be done via the query but I have not come across anything in some quite extensive searching (although, once again, I do not know if I am using the right search terms!) so I assume PHP would, once again be the saviour! Thanks in advance for any suggestions. Steve |