PHP - Breaking An Infinite Loop When User Disconnects?
I'm not sure what PHP considers an "aborted connection" and things like that, but the way this chat works is by updating a file and using the timestamp off it to determine if new posts exist. Rather than re-checking the server over and over, this code will check once and keep the connection open until a response is made. The only problem is, it works too well! Even after the tab is closed and I try another script on the site or the same script, it all hangs until I update the file - here is the code snippet:
while (($currentmodif <= $lastmodif) && (connection_aborted() == 0) && (connection_status() == 0)){ // check if the data file has been modified usleep(10000); // sleep 10ms to unload the CPU if (connection_aborted ()) break; if (connection_status () != 0) break; clearstatcache(); $currentmodif = filemtime($filename); } I have put several measures in to attempt to break the loop when the user disconnects, but it just doesn't work! It will continue to hang and hang and hang until I re-upload the file $filename HOW CAN I BREAK THE WHILE LOOP WHEN THE MEMBER LEAVES THE PAGE? I could post up an example but its ultimately useless after one load unless you have control over updating the file. Thanks! Similar Tutorialsmy webhost told me there was a infinite loop that in a matter of 30seconds used up over 12GB can someone help me find this and stop the loop for doing so? or is there a program that could help me with this kind of stuff <?php include "sessionStore.php"; $userfinal = get_username($_SESSION['user_id']); $the_time = time(); mysql_query("UPDATE users SET date='$the_time' WHERE Username='$userfinal'")or die(mysql_error()); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Zhshero Friends</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="default.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1><font color=white>ZhsHero Friends</h1> <h2>Making the world a better place :)</h2> </div> <div id="menu"> <ul> <li><a href="http://zhshero.freehostingcloud.com/home.php">Home</a></li> <li class="active"><a href="http://zhshero.freehostingcloud.com/mymembers.php">Members</a></li> <li><a href="http://zhshero.freehostingcloud.com/update_profile.php">Settings</a></li> <li><a href="http://zhshero.freehostingcloud.com/inbox/">Inbox <? $sql = mysql_query("SELECT count(message_id) FROM messages WHERE to_user='$userfinal' AND message_read='0'"); $total = mysql_fetch_array($sql); $num = $total[0]; echo $num; ?> </a></li> <li><a href="http://zhshero.freehostingcloud.com/logout.php">Logout</a></li> </ul> </div> <div id="content"> <div id="colOne"> <center><h2><font color=white><?php echo 'Welcome ' . get_username ( $_SESSION['user_id'] ) . ' '; ?></h2> <p><img src="<? echo get_main_P ( $_SESSION['user_id'] ) ?>" border=1 width="135" height="150"></p> </center> <h2><font color=white>News box</h2> <p><? $result = mysql_query("SELECT * FROM otherapia"); while($row = mysql_fetch_array($result)) { echo $row['id'] . " " . $row['news']; } ?></p> </div> <div id="colTwo"> <h2><font color=white> ZhsHero Friends Users - <a href="http://zhshero.freehostingcloud.com/who_online.php">View online users only</a></h2> <p> <center><table border=2 width="250" height="125"><tr> <? $Members = mysql_query("SELECT * FROM users") or die(mysql_error()); $numRowsMembers = mysql_num_rows($Members); ?> <?php for($count = 4/n; $count <= $numRowsMembers; $count++) { $name = mysql_fetch_array($Members); ?> <td width="150" height="125"> <a href="view_profile.php?username=<? echo $name['Username']?>"><img src="<? echo $name['main_P']?>" width="100" height="100"/> <? echo $name['Username']?></a> <? if (isset($name['date']) && (time() - $name['date'] > 300)) { echo 'offline'; } else { echo "<font color=green>[Online]</font>"; } $name['date'] = time(); // update last activity time stamp ?> </td> <? } ?> </tr></table></center> </p> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <p>Copyright © 2010 ZhsHero LTD. Designed by <a href="http://www.freecsstemplates.org/"><strong>Free CSS Templates</strong></a></p> </div> <center><a href="http://www.adleaf.com" style="font-size:12px;">Free Advertising</a><br/><script type="text/javascript"> riv_client = 318310; riv_backgroundColor = '000000'; riv_borderColor = '000066'; riv_headlineColor = '669900'; riv_textColor = 'FFFFFF'; riv_linkColor = 'CC3300'; riv_adWidth = 728; riv_adHeight = 90; riv_adType = 4; </script> <script type="text/javascript" src="http://ad1.adleaf.com/js/rivad.js"></script> </body> </html> Hey everyone ... This should be a pretty easy question for someone who is used to using fgetcsv: I have a script that needs to import a csv file into a mysql table ... I keep getting stuck in a loop that only ends when the script hits the 30 second timeout I have set on the server ... It never actually inserts a record, and it never spits out a message indicating and error ... Can someone help figure out why I get caught in this loop? Here's the code: Code: [Select] function import_csv() { if(isset($_POST['submit_csv'])) { $filename=$_POST['filename']; $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT INTO `{mydatabase}`.`{my table}` (`name`, `qrl`, `begin`) VALUES ('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='results.php' method='post'><input type='file' name='filename'><br /><input type='submit' value='submit' name='submit_csv' /></form>"; } } Hi guys, So here is the deal. We have a list of brands that excists in a database. There are also images associated with the names. But not all the brands have images. So in the script i read if the file excists. Well this all works fine but it looks horrible. So i want to break the list in half (or limit it to 24). But i cant limit the sql query. Is there a way to "limit" a while loop and let it resume on the same page, just to change the layout (multiple collumns)? (I hope i am clear on this... i confuse even myself) $host = 'localhost'; $user = 'qwerty'; $pass = 'qwerty'; $db = 'qwerty'; $query = "SELECT * FROM ros_brands"; $result = mysql_query($query) or die(mysql_error()); $filename = "/resources/images/mm_files/" . $row['image_file_id'] . ".gif"; while($row = mysql_fetch_array($result)){ $filename = "/var/www/vhosts/test.nl/httpdocs/resources/images/mm_files/" . $row['image_file_id'] . ".gif"; if (file_exists($filename)) { echo "<a href='#'><img src='/resources/images/mm_files/" . $row['image_file_id'] . ".gif' /><span>". $row['name'] ."</span></a>"; } else { // echo "The file $filename does not exist"; } } I am currently streaming my mp4 files perfectly fine using php. My issue is, how do I detect when the video is either no longer being watched, or disconnected? I need to run a function after this so that I know the video is no longer being watched for analytics. Is there a way maybe with sockets or something? I'm currently using this.
if (file_exists($request)) { $fp = @fopen($request, 'rb'); $size = filesize($request); $length = $size; $start = 0; $end = $size - 1; header("Content-Type: video/mp4"); header('Accept-Ranges: 0-' . $length); if (isset($_SERVER['HTTP_RANGE'])) { $c_start = $start; $c_end = $end; list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); if (strpos($range, ',') !== false) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size); exit(); } if ($range == '-') { $c_start = $size - substr($range, 1); } else { $range = explode('-', $range); $c_start = $range[0]; $c_end = (isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size); } $c_end = ($end < $c_end ? $end : $c_end); if (($c_end < $c_start) || (($size - 1) < $c_start) || ($size <= $c_end)) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size); exit(); } $start = $c_start; $end = $c_end; $length = ($end - $start) + 1; fseek($fp, $start); header('HTTP/1.1 206 Partial Content'); } header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size); header('Content-Length: ' . $length); ob_end_flush(); $buffer = 8192; $time_start = time(); $bytes_read = 0; while (!feof($fp) && (($p = ftell($fp)) <= $end)) { $response = stream_get_line($fp, $buffer); echo $response; $bytes_read += strlen($response); if (30 <= time() - $time_start) { file_put_contents('/var/www/html/movieCon/'.$user.'_'.$token.'_'.$movie_id.'.con', time()); $time_start = time(); $bytes_read = 0; } } fclose($fp); exit(); }
I'm trying to figure out how to do something. I have two tables for use in a quiz program--one table for questions and one table for answers. I'm thinking about looping through all the questions, one at a time, and all the answers that correspond to the given question, echoing the form: the radio buttons and the submit button, and have the program pause to wait for the submit button to be clicked before looping to the next question/answer set. I'm assuming I'll need to make two queries, one for the Questions table, and one for the Answers table, incrementing the QuestionID with each loop (or randomizing them and marking them as asked so the same question doesn't come up multiple times), processing the answers before the next loop, etc. 1. Is this possible? 2. Is this a good approach? 3. Where would I look to learn how to do all this? I don't have any code to show because I haven't yet written anything about this. I'm still thinking about how I would do it. I have to learn about randomizing, and about nested queries, and about a few other things. I'm just tossing this "out there" for some ideas. Thanks to all. Rich Hollenbeck Before anyone flames me, I want to be clear, I have searched and researched this issue for years. Maybe its my keywords or maybe its just my understanding, but nothing I have found seems satisfactory or even addresses my specific need. Anyway, my gratitude in advance for everyone being polite and patient. I have a website that keeps track of pricing data for an online gaming site. When I made it I had no understanding of coding beyond BASIC on a Color Computer II from 1981. So I put together everything bit by bit. Now its three years later and I have a much much greater understanding of things. But I'm stuck with a data base that contains 365 columns just for a year of pricing data on an item. And I want to keep all data for every new day, not just one year. I know there has got to be a better way then name,bla,bla,day1,day2,day3,day4,day5... and adding columns for every new day. Any suggestions? And I know this question is mostly focused on MySQL (actually any database but I use MySql) rather than PHP. But PHP will be playing an integral part of maintaining the database. Plus, the people here are always incredibly knowledgeable, and polite. Again, the specific question is how should I design a database that will keep an on-going history of pricing data? I have two while loops that should run infinitely. while loop #1 runs during 9:30am - 4pm, monday through thursday while loop #2 runs when its not 9:30am-4pm, monday through thursday. $hourmin = date("Gi", time(now)); $current = getdate(); while ( $hourmin > 829 && $current[hours] < 15 && $current[wday] > 0 && $current[wday] < 6 ): // while loop #1 while ( $hourmin < 830 || $current[hours] > 14 || $current[wday] = 0 || $current[wday] = 6 ): // while loop #2 as you can see the while condition is the easy part, but I'm not sure how to set this up. I was going to do this using a combination of if statements and the goto function but my version of php does not support goto. I just want it to switch back and forth between these these two while statements infinitely. Is this possible in PHP? Hi all, I am working on a project where I need to monitor accounts and suspend features associated with them if their deposited balance runs out. To do this I'm thinking it might be best to have a script running with an infinite loop that constantly refreshes but I'm not sure what kind of strain this might put on the server. The pseudocode would look something like this: while (1) { For each row in database { If balance <= 0 { mysql query - account_status = suspended } } } Please note (obviously) this is psuedocode and not actual code. I'm just concerned about how I would stop this script timing out, and what kind of impact it would have on server performance? Is there any better way to do this? Happy to discuss, dB My code: Code: [Select] $rank = implode(',', $ibforums->input['rank']); echo $rank; For that form, it will show: '2,0,0' Problem is, I need to update each row with each individual value, and is this possible with using 1 query? Hi everyone ! I am stuck on a task which I'm sure has been achieved by several others in the past. I need to create a category table with unlimited / infinite levels (depths) of categories, sub-categories, sub-sub-categories, sub-sub-sub-categories and so on. I need to know how to show the category tree through PHP. An example would be great or even a link to another page where someone has laid out a step-by-step tutorial. Please help! Thank you very much! Kind Regards, Xeirus. What is the best way to break up repeating code? Make each page from a standard template (e.g. Header, Columns, Footer) and include the variable content using PHP?? Or make each page a stripped down PHP page which creates the variable content and then Includes the static parts (e.g. Header, Columns, Footer)?? Hope you follow me?! :-/ Debbie I'm experimenting with a basic CRUD App. The table created by the code below renders, however when I view source, the last tag is the closing </tr> after the while loop finishes. There's nothing after that. No closing table, html, or body tags. I can't see what I've done wrong.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Eric's PHP CRUD App</title> <style type="text/css"> table { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; text-align: center; margin: 0 auto; } table td { text-align:center; border: 1px solid #dfdfdf; } tr:nth-child(odd) { background: #fdfdfd; } tr:nth-child(even) { background: #B8D3FF; } th { background-color:#ccc; } .center { width: 1050px; margin:0px auto; } h1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; padding-bottom: 15px; text-align: center; margin: 0 auto; color: white; } </style> </head> <body bgcolor="#999"> <?php require_once("db_connect.php"); echo "<h1>Update Student Records</h1>"; echo "<table cellpadding='10'>"; echo "<tr bgcolor='#cccccc'>"; echo "<th>First Name</th>"; echo "<th>Last Name</th>"; echo "<th>Test 1 Grade</th>"; echo "<th>Test 2 Grade</th>"; echo "<th>Test 3 Grade</th>"; echo "<th>Test 4 Grade</th>"; echo "<th>Final Exam Grade</th>"; echo "<th>Average Grade</th>"; echo "<th>Final Grade</th>"; echo "<th>delete</th>"; echo "<th>edit</th>"; echo "</tr>"; $sql = "SELECT * FROM students"; $result = mysqli_query($link, $sql) or die(mysql_error()); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC) or die(mysql_error())) { $final = ""; $average = (($row["test1Grade"]) + ($row["test2Grade"]) + ($row["test3Grade"]) + ($row["test4Grade"]) + ($row["finalExamGrade"])) / 5; if ($average >= 90) { $final = "A"; } else if ($average >= 80) { $final = "B"; } else if ($average >= 70) { $final = "C"; } else if ($average >= 60) { $final = "D"; } else if ($average < 60) { $final = "F"; } echo "<tr>"; echo "<td>" . $row["firstName"] . "</td>"; echo "<td>" . $row["lastName"] . "</td>"; echo "<td>" . $row["test1Grade"] . "</td>"; echo "<td>" . $row["test2Grade"] . "</td>"; echo "<td>" . $row["test3Grade"] . "</td>"; echo "<td>" . $row["test4Grade"] . "</td>"; echo "<td>" . $row["finalExamGrade"] . "</td>"; echo "<td>" . round($average) . "</td>"; echo "<td>" . $final . "</td>"; echo "<td><a href='delete.php?id=" . $row['studentID'] . "'>›</a></td>"; echo "<td><a href='update.php?id=" . $row['studentID'] . "'>›</a></td>"; echo "</tr>"; } echo "</table>"; ?> <a href='insert.php'>Add new student</a> </body> </html> Edited by Ch0cu3r, 13 November 2014 - 01:07 PM. Added code tags I have a site that everything was typed manually, but I want to get all this info off so I can put all info into a database for easier editing and so forth.
I'm trying this code, which works to a point.
function curl($Url){ if (!function_exists('curl_init')){ die('cURL is not installed. Install and try again.'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $start = strpos($output, '<h2 style="text-align: center;"><span style="text-decoration: underline;">Alabama Tattoo Shops</span></h2>'); $end = strpos($output, '<p>', $start); $length = $end-$start; $site = substr($output, $start, $length); $site = explode("<p>", $site); foreach ($site AS $line) { print_r($line); } return $output; } $site = curl('http://www.tattooshopusa.com/alabama/'); I am trying to break down the tables i have on my website in order to place them into my mySQL database. I am new to php and have been having some trouble and any help would be greatly appreciated. So far I have this but it doesnt seem to be working. I am using DOMDocument but I wonder if maybe preg_match woulf be better? Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\Hosting\5915198\html\2.php on line 11 <?php // Load html string $dom = new DOMDocument(); $dom->loadHTML('www.empirebuildingsestate.com/company.html'); // Get tables from html $tables = $dom->getElementsByTagName('tr'); // Get rows from tables $rows = $tables->item(0)->getElementsByTagName('td'); // Loop over each row foreach ($rows as $row) { // Get each column by tag name $cols = $row->getElementsByTagName('td'); // Echo values (here you can assign them in array for example) echo $cols->item(0)->nodeValue.'<br />'; echo '<hr />'; } ?> hi gang, I just spent the better part of the day trying to find a way modularize my PHP code. I want to execute a php file and load the results into my main php program. I am not looking to include php source code into my prog and then execute it, I want to execute it and load the results into my prog. I know I can do this if I call a php file via apache: using file(http://ww.site.com/blah.php?parms) but is there a way to do it without using http ? The php file is local - in the same directory. I want something like this: $r = something.php?parms... how do I do this? regards, david If i have a list of categories like: 1. Billboards and advertisement section 1(a)City Clock 1(a)(i)Application fee (has columns for approved price and proposed price) 1(a)(ii)Advertisement Per year (has columns for approved price and proposed price) 1(b)Billboards 1(b)(i)Application fee for construction (has columns for approved price and proposed price) 1(b)(ii)Charge per year without advertisement (has columns for approved price and proposed price) 1(c)Something here..... 1(c)(i) something here...(has columns for approved price and proposed price) 1(c)(ii)something here...(has columns for approved price and proposed price) 1(c)(iii) something here... (has columns for approved price and proposed price) e.t.c THEN SOME CATEGORIES LOOK LIKE:category 2 2. Category name 2(a)something here..(has columns for approved price and proposed price) 2(b)something here.. 2(b)(i)something here..(has columns for approved price and proposed price) 2(b)(ii)something here..(has columns for approved price and proposed price) NOW: i have categories without sub categories and others with sub-sub categories , a main category doesn't does have a column for prices ( or lets just say other columns) , a sub category WITHOUT its sub category will have columns for prices, if a sub category has its sub category, then its subcategory should have columns for prices (this is where my problem is - how do i handle such a situation in php Mysql?? ) If I break up this long line of code will it still work correctly? Original... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Desired... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Or maybe... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Debbie I have gold data being reported here goldprices.org.uk (scroll down near the bottom). Recently it broke for no apparent reason. I checked the scraper and everything seems to be OK. The issue is that the gold price in (troy) ounces is being scraped fine - however to work out the price in grams you must multiply by 0.0321 (grams in a troy ounce). The code looks like this: Code: [Select] $ounce_price = null; $grams_price = null; if(count($nodes) == 1 && $nodes[0][1]) { $ounce_price = $nodes[0][1]; $grams_price = $ounce_price * 0.0321; However $ounce_price * 0.0321 breaks the code and returns '0.0321'. I then tried the code: Code: [Select] $ounce_price = null; $grams_price = null; if(count($nodes) == 1 && $nodes[0][1]) { $ounce_price = $nodes[0][1]; $grams_price = $ounce_price + 1; And the code returned the value '2'. So it appears that when $ounce_price is being multiplied/subtracted etc it reverts to a value of '1'. However if I do $grams_price = $ounce_price the value is the correct ounce price. I'm so confused as to why when adding an equation to $ounce_price the value reverts to '1' as opposed to equalling the correct number. Any help here would be HUGELY appreciated - I've been stuck for several days and only just decided to ask online :s Nick Hey guys, How can i break just one cycle of a foreach loop. Example: $arr = array('0','1','2'); foreach ($arr as $value){ if($value == 1){ break from this iteration and continue onto next one} echo $value; } So the output should be 02 |