PHP - Moved: Optimize Php For Set Top Box (middleware) Usage
This topic has been moved to Application Design.
http://www.phpfreaks.com/forums/index.php?topic=320813.0 Similar TutorialsThis topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=321105.0 This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=319964.0 This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=346818.0 the difference between memory usage and bandwidth usage? I did a test with 500 rows in table, got 2.36mb memory usage, and then once without 500 rows in table, i got 2.34 (IN MBS) memory usage, can that translate into bandwidth usage? somone told me that bandwidth usage != memory usage, how so? it does effect it some doesn't it ? Hey so I made a ToDo List as my first php script after starting to learn. I want you guys to just look at my code and tell me where I can improve. I want to drop any bad habits early on so they don't move forward with me. Also tell me where I can optimize and minimize the code so I don't write unnecessary code. Thanks! I'm going to omit things like some html that isn't crucial. You can see it live he https://taziamoma.com/ToDoList/ . Also try to do an SQL injection so I can see if I protected myself from it properly. Thank you! index.php <?php include_once("includes/connection.php"); $errors = ""; if (isset($_POST['submit'])) { if (empty($_POST['task'])) { $errors = "You must fill in the task"; } else { try { $task = $_POST['task']; $sql = "INSERT INTO todopost (title) VALUES ('$task')"; $db->exec($sql);; header('Location: index.php'); } catch(PDOException $e) { echo $sql. "<br>". $e->getMessage(); } } } if (isset($_GET['del_task'])) { $stmt = $db->prepare("DELETE FROM todopost WHERE id = :id"); $stmt->execute(array(':id' => $_GET['del_task'])); header('Location: index.php'); } <body> <div class="outside"> <div class="container"> <div id="myDIV" class="header"> <h2 style="margin:5px">My To Do List</h2> <form method="post" action="index.php" class="input_form"> <?php if (isset($errors)) { ?> <p><?php echo $errors; ?></p> <?php } ?> <input type="text" name="task" class="input"> <button type="submit" name="submit" class="addBtn">Add</button> </form> </div> <ul id="myUL"> <?php try { $stmt = $db->query('SELECT id, title FROM todopost ORDER BY id DESC'); while($row = $stmt->fetch()) { ?> <div class="li_cont"> <li><?php echo $row['title']; ?></li> <a class="right" href="index.php?del_task=<?php echo $row['id'] ?>">x</a> </div> <?php } } catch(PDOException $e) { echo $e->getMessage(); } ?> </ul> </div> </div> </body> </html> connection.php <?php ob_start(); session_start(); $host = "localhost"; $username = "root"; $password = ""; try { $db = new PDO("mysql:host=$host;dbname=tazejesa_todo", $username, $password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: ". $e->getMessage(); } ?>
Hi, There is a feature in cpanel called optimize website and when you go in it there is a field to fill Compress the specified MIME types. My question is this the correct way to optimize PHP CSS JS did i enter the mime types correctly? text/html text/plain text/xml/css/application/x-httpd-php/application/x-javascript I am very new to PHP and have tried various techniques but I am getting a 500 error when clicking on the export button to download a csv report. I'm not sure why the previous developer did it this way. Is there a better why in PHP to make this code better? Willing to understand and learn from an PHP expert. The database is MYSQL. $coursefilterid = $_GET['course']; $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sqluserenrolled = "select mdl_user.username, mdl_user_enrolments.userid as enrolleduserid, mdl_enrol.courseid from mdl_user_enrolments Inner Join mdl_enrol on mdl_enrol.id = mdl_user_enrolments.enrolid Inner Join mdl_user on mdl_user.id = mdl_user_enrolments.userid where mdl_enrol.courseid = '" . $coursefilterid . "' order by mdl_user.username "; $queryenrolleduser = mysqli_query($conn, $sqluserenrolled); ?> <html> <head> </head> <body> <form method="post" action="<?php echo "userlistssiexport.php?id=$coursefilterid"?>"> <input type="hidden" name="exportcourseid" value="<?php echo $coursefilterid;?>"> <input type="hidden" name="sessid" value="<?php echo $USER->sesskey;?>"> <input class="btn btn-primary" type="submit" name="submit" value="<?php echo "Export";?>"> </form> <?php $noteid = ""; $cmId = ""; ?> <table class="data-table"> <caption class="title">User info</caption> <thead> <tr> <th>Username</th> <th>Firstname</th> <th>Lastname</th> <th>Email</th> <th>Last login</th> <th>Createddate</th> <th>Position</th> <th>Organization</th> <th>Certificate Request Date</th> <th>Role1</th> <th>Role2</th> <th>Role3</th> </tr> </thead> <tbody> <?php while ($row = mysqli_fetch_array($queryenrolleduser)) { $enrolleduserid = $row['enrolleduserid']; $sql = "select mdl_user.username as username, mdl_user.firstname as firstname, mdl_user.lastname as lastname, mdl_user.email as email, mdl_user.lastlogin as lastaccess, mdl_user.timecreated as createddate, mdl_user_info_data.data as position from mdl_user Inner Join mdl_user_info_data on mdl_user_info_data.userid = mdl_user.id Inner Join mdl_user_info_field on mdl_user_info_field.id = mdl_user_info_data.fieldid Inner Join mdl_user_lastaccess on mdl_user_lastaccess.userid = mdl_user.id where mdl_user_info_field.id = 1 and mdl_user.deleted = 0 and mdl_user.id = '" . $enrolleduserid . "' group by mdl_user.username order by mdl_user.username "; $query = mysqli_query($conn, $sql); if (! $query) { die('SQL Error: ' . mysqli_error($conn)); } else {} ?> <?php $no = 1; $total = 0; $username = ''; $coursename = ''; $content = ''; $modulename = ''; $organization = ''; $userid = ''; $certificatedate = ''; $userrole = ''; $enrolleduserid = ''; while ($row = mysqli_fetch_array($query)) { // Do something here $username = $row['username']; $coursename = $row['coursename']; $content = $row['content']; $noteid = $row['noteid']; // $notedatetime = date("d/m/y g:i (A)", $row['notedate']); $notedatetime = date("D M j Y G:i A", $row['notedate']); $lastaccess = date("D M j Y G:i A", $row['lastaccess']); $createddate = date("D M j Y G:i A", $row['createddate']); $datafile = $username . $coursename . $content; echo '<tr> <td>' . $row['username'] . '</td> <td>' . $row['firstname'] . '</td> <td>' . $row['lastname'] . '</td> <td>' . $row['email'] . '</td> <td>' . $lastaccess . '</td> <td>' . $createddate . '</td> <td>' . $row['position'] . '</td> '; $modid = $row['contextid']; // Get module name $sqlmodule = "select mdl_user.username as username, mdl_user.firstname as firstname, mdl_user.lastname as lastname, mdl_user.email as email, FROM_UNIXTIME(mdl_user_lastaccess.timeaccess) as lastaccess, FROM_UNIXTIME(mdl_user.timecreated) as createddate, mdl_user_info_data.data as organization from mdl_user Inner Join mdl_user_info_data on mdl_user_info_data.userid = mdl_user.id Inner Join mdl_user_info_field on mdl_user_info_field.id = mdl_user_info_data.fieldid Inner Join mdl_user_lastaccess on mdl_user_lastaccess.userid = mdl_user.id where mdl_user_info_field.id = 3 and mdl_user.deleted = 0 and mdl_user.username ='" . $username . "'"; $querymodule = mysqli_query($conn, $sqlmodule); ?> <?php $modulenamelink = ""; while ($row = mysqli_fetch_array($querymodule)) { $organization = $row['organization']; } echo '<td>' . $organization . '</td>'; $sqlCertificateDateuid = "select id from mdl_user where username = '" . $username . "'"; $queryCertificateDateuid = mysqli_query($conn, $sqlCertificateDateuid); while ($row = mysqli_fetch_array($queryCertificateDateuid)) { $userid = $row['id']; } $sqlcertificatedate = "select * from mdl_certificateemail where userid = '" . $userid . "' and courseid = '" . $coursefilterid . "'"; $querycertificaterequestdate = mysqli_query($conn, $sqlcertificatedate); while ($row = mysqli_fetch_array($querycertificaterequestdate)) { $certificatedate = date("D M j Y g:i:s A", $row['unixdatetimecertificate']); } echo '<td>' . $certificatedate . '</td>'; $sqluserrole = "select mdl_role_assignments.userid, mdl_role_assignments.roleid,mdl_course_modules.course, mdl_role.shortname as rolename,FROM_UNIXTIME(mdl_role_assignments.timemodified) from mdl_role_assignments Inner Join mdl_context on mdl_context.id = mdl_role_assignments.contextid Inner Join mdl_course_modules on mdl_course_modules.instance = mdl_context.instanceid Inner Join mdl_role on mdl_role.id = mdl_role_assignments.roleid where mdl_course_modules.course = '" . $coursefilterid . "' and mdl_role_assignments.userid = '" . $userid . "' group by mdl_role_assignments.userid, mdl_role_assignments.roleid, mdl_course_modules.course, mdl_role.shortname, mdl_role_assignments.timemodified order by mdl_role_assignments.timemodified "; $userlistrole = ''; $queryuserrole = mysqli_query($conn, $sqluserrole); while ($row = mysqli_fetch_array($queryuserrole)) { $userrole = $row['rolename']; $userlistrole = array( array( $userrole ) ); // echo '<td>'.$userrole.'</td>'; } foreach ($userlistrole as $listrole) { // echo $listrole; } $teacherrole = array( 'student' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td>student</td>'; } } } $teacherrole = array( 'editingteacher' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td></td>'; echo '<td>editingteacher</td>'; } } } $teacherrole = array( 'manager' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td>manager</td>'; } } } echo '</tr>'; } } ?> </tbody> <tfoot> </tfoot> </table> </body> </html> <?php } } else { header("Location:/index.php"); // echo "something"; die(); } } else { header("Location:/index.php"); die(); } ?>
Hello everyone... I made point system that ranks users in my app. There are two parts to the system, a primary score and a dynamic score. The primary score is based on how you well you perform and the dynamic score is based on how well your friends perform. Both of these get added together to equal your total score. The problem is that I have a lot of looping occurring which results in about 400 queries being run when I access the page that executes this class. Can this be optimized? What's the best way to do this? I don't want to store the data as I want this presented in real-time. Code: [Select] <?php class edge { public function get_all_users_edge() { $sql = "SELECT id FROM users WHERE status = 3"; $result = mysql_query($sql) or die(mysql_error()); $ids = array(); while (($row = mysql_fetch_assoc($result)) !== false) { $ids[] = $row; } $all_edges = array(); foreach ($ids as $k => $id) { $edge = $this->get_users_edge($id['id']); $all_edges[$k] = $edge; } return $all_edges; } public function get_users_edge($uid) { $users_primary_edge = $this->get_users_primary_edge($uid); $users_dynamic_edge = $this->get_users_dynamic_edge($uid); return $users_primary_edge + $users_dynamic_edge; } public function get_users_primary_edge($uid) { if (active_id($uid) === false) { return false; } $uid = (int)$uid; $sql = "SELECT CHAR_LENGTH(`users`.`credentials`) AS `cred_chars`, CHAR_LENGTH(`users`.`specialties`) AS `spec_chars`, `companies`.`companyvideo` AS `video`, `investor_info`.`accredited` AS `accredited`, ( SELECT COUNT(`user_id`) FROM `blog_posts` WHERE `user_id` = '${uid}' ) AS `post_count`, ( SELECT COUNT(`uid`) FROM `votes` WHERE `uid` = '${uid}' ) AS `vote_sent_count`, `votes_received`.`inv_vote_received_count`, `votes_received`.`pub_vote_received_count`, ( SELECT COUNT(`userid`) FROM `employees` WHERE `userid` = '${uid}' ) AS `joined_count`, `votes2`.`ent_count`, `votes2`.`inv_count`, ( SELECT COUNT(`company_id`) FROM `company_fans` LEFT JOIN `companies` ON `company_fans`.`company_id` = `companies`.`companyid` LEFT JOIN `employees` ON `employees`.`companyid` = `companies`.`companyid` WHERE `userid` = '${uid}' ) AS `company_fans_count`, ( SELECT COUNT(`user_id`) FROM `recommendations` WHERE `user_id` = '${uid}' ) AS `recommendation_count`, ( SELECT COUNT(`partner_id`) FROM `partners` WHERE (`user_id` = '${uid}' OR `friend_id` = '${uid}') AND `approved` = '1' ) AS `associate_count` FROM `users` LEFT JOIN `investor_info` ON `investor_info`.`uid` = `users`.`id` LEFT JOIN `employees` ON `employees`.`userid` = `users`.`id` LEFT JOIN `companies` ON `employees`.`companyid` = `companies`.`companyid` LEFT JOIN ( SELECT `employees`.`userid`, SUM( IF( `votes`.`vote_type` = 1, 1, 0 ) ) AS `inv_vote_received_count`, SUM( IF( `votes`.`vote_type` = 0, 1, 0 ) ) AS `pub_vote_received_count` FROM `votes` INNER JOIN `employees` ON `employees`.`companyid` = `votes`.`company_id` WHERE `employees`.`userid` = '${uid}' GROUP BY `employees`.`userid` ) AS `votes_received` ON `votes_received`.`userid` = `users`.`id` LEFT JOIN ( SELECT `beta_keys`.`ref_id`, SUM( IF( `users`.`accounttype` = 1, 1, 0 ) ) AS `ent_count`, SUM( IF( `users`.`accounttype` = 0, 1, 0 ) ) AS `inv_count` FROM `beta_keys` INNER JOIN `users` ON `users`.`id` = `beta_keys`.`userid` WHERE `beta_keys`.`ref_id` = '${uid}' AND `users`.`status` = 3 GROUP BY `users`.`id` ) AS `votes2` ON `votes2`.`ref_id` = `users`.`id` WHERE `users`.`id` = '${uid}'"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); $score = 0; if((!empty($row['cred_chars'])) && (!empty($row['spec_chars']))) { $score += 200; } if(!empty($row['video'])) { $score += 50; } if($row['accredited'] == 1) { $score += 100; } $score += (50 * $row['post_count']); $score += (5 * $row['vote_sent_count']); $score += (3 * $row['inv_vote_received_count']); $score += (1 * $row['pub_vote_received_count']); $score += (200 * $row['joined_count']); $score += (40 * $row['ent_count']); $score += (200 * $row['inv_count']); $score += (10 * $row['company_fans_count']); $score += (30 * $row['recommendation_count']); $score += (20 * $row['associate_count']); return $score; } public function get_users_dynamic_edge($uid) { $uid = (int)$uid; $sql = "( SELECT `users`.`id` FROM partners INNER JOIN `users` ON `partners`.`user_id` = `users`.`id` WHERE partners.friend_id = '${uid}' AND `approved` = 1 ) UNION ALL ( SELECT `users`.`id` FROM `partners` INNER JOIN `users` ON `partners`.`friend_id` = `users`.`id` WHERE `partners`.`user_id` = '${uid}' AND `approved` = 1 )"; $result = mysql_query($sql) or die(mysql_error()); $i = 0; $score = 0; while (($row = mysql_fetch_assoc($result)) !== false) { $dynamic_scores[$i] = array( 'uid' => $row['id'], 'score' => $this->get_users_primary_edge($row['id']), ); $i++; } if(!empty($dynamic_scores)) { foreach($dynamic_scores as $k => $dynamic_score) { $score += $dynamic_score['score']; } } return ($score * 0.1); } } ?> We are toying with the idea of using PHP to do sorting instead of our database to reduce load and scale. Basically what we would have is multidimensional arrays that are resturned from the SQL engine and we will need to sort them on a specific key in PHP. We have written this functionality, but are looking to make it faster ANYWAY possible. Do you guys see anyway to speed up this code, without throwing more hardware at the problem yet? Currently on our test server this code takes approx 2.4 - 2.6 seconds to execute. We would love others to try this code and report what it takes them to execute. We are shooting for sub 1 second time. Code: [Select] $array = array(); $temp = array(); for($i = 0; $i < 100000; $i++) { $temp['id'] = rand(10000, 99999); $temp['history_id'] = rand(100000000, 999999999); $array[] = $temp; } //// // Start timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; //// // Actual sort //// usort($array, function($a, $b) { //Compare numbers if ($a['history_id'] == $b['history_id']) { return 0; } return ($a['history_id'] < $b['history_id']) ? -1 : 1; }); //// // End timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); //// // Output execution time //// echo "Executed in: <strong>". $totaltime ."</strong> seconds."; Hi sorry for my bad English I have this queries but when I using num_queries show over 40 for this code!! how can I optimize it for best performance category table is : ".$prefix."_modules_categories item table is : ".$prefix."_modules $display = $openclose; if ($display == 0) { $show = "none"; $catimg = "<img src=\"$closedimg\" align=\"absmiddle\" border=\"0\">"; } else { $show = "show"; $catimg = "<img src=\"$openimg\" align=\"absmiddle\" border=\"0\">"; } //Categories $result = $db->sql_query("select mcid, mcname FROM ".$prefix."_modules_categories WHERE visible='1' ORDER BY mcposition"); //$coin=0; global $multilingual, $currentlang; while ($row = $db->sql_fetchrow($result)) { $mcid = $row['mcid']; $mcname = $row['mcname']; //$coin++; $mcname1 = $mcname; if(strlen($mcname1) == 0){ if ($multilingual == 1) { include("modules/languages/lang-".$currentlang.".php"); $mcname = "$mcnamed[$mcid]"; } else { include("modules/languages/lang-english.php"); $mcname = "$mcnamed[$mcid]"; } }else{ $mcname = "$mcname1"; } $content .= "</div><table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><a id=\"x".$mcname."\" href=\"javascript:Toggle('".$mcname."','$align');\">$catimg</a></td><td><b>".$mcname."</b></table>\n"; $content .= "<div id=\"".$mcname."\" style=\"display: $show; margin-left: 1em;\">\n"; $result2 = $db->sql_query("SELECT title, custom_title, view, url FROM " . $prefix . "_modules WHERE active='1' AND inmenu='1' AND title!='$def_module' AND mcid='$mcid' ORDER BY custom_title ASC"); while ($row = $db->sql_fetchrow($result2)) { $title = $row['title']; $custom_title = $row['custom_title']; $view = $row['view']; $url = $row['url']; $arraymodules[] = "$title:$custom_title:$view:$url"; $m_title = $title; $m_title2 = ereg_replace("_", " ", $m_title); include("modules/".$title."/language/lang-".$currentlang.".php"); if ($custom_title != ""){$m_title2 = $custom_title;}else{ if(strlen($mudulename) != 0){ $custom_title = "$mudulename"; } $m_title2 = $custom_title; } if ($m_title != $main_module) { $showit = 0; switch($view){ case 0: // All users case $showit = 10; break; case 1: // Registered user access if (is_user($user) || is_admin($admin)) $showit = 1; break; case 2: // Admin only access if (is_admin($admin)) $showit = 2; break; default: // Subscriber only access if (is_user($user) || paid()) $showit = 3; break; } global $db , $prefix; $rowz = $db->sql_fetchrow($db->sql_query("SELECT gtset FROM ".$prefix."_config")); $gtset = intval($rowz['gtset']); if ($showit != 0) { $adds = $_SERVER['SERVER_NAME']; if ($url != "" AND $gtset != 0) { $content .= "<table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><img src=\"$arrowimg\" align=\"absmiddle\" border=\"0\"></td><td><a href=\"$url\" title=\"$m_title2\" onMouseOver=\"self.status=' $m_title2 ';return true\" onmouseout=\"self.status='';return true\">$m_title2</a></td></tr></table>\n"; } else { $content .= "<table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><img src=\"$arrowimg\" align=\"absmiddle\" border=\"0\"></td><td><a href=\"modules.php?name=$m_title\" title=\"$m_title2\" onMouseOver=\"self.status=' $m_title2 ';return true\" onmouseout=\"self.status='';return true\">$m_title2</a></td></tr></table>\n"; } } } $mudulename = ""; } } $content .= "</div>"; $db->sql_freeresult($result); $db->sql_freeresult($result1); Hi guys,
Having some trouble entering some php into my wordpress site that runs on Optimize Press.
I'm trying to insert this URL/ tracking code into my page as a hyperlink - 'Click Here Now'.
http://www.mysite.co...1_50onRed&sub1=<?php echo $sub1; ?>&sub2=<?php echo $sub2; ?>&sub3=<?php echo $sub3; ?>&sub4=<?php echo $sub4; ?>&sub5=<?php echo $sub5; ?>&lpid=<?php echo $lpid; ?>
This is what I have done so far:
<a href="http://www.mysite.co...;sub1=<?php echo $sub1; ?>&sub2=<?php echo $sub2; ?>&sub3=<?php echo $sub3; ?>&sub4=<?php echo $sub4; ?>&sub5=<?php echo $sub5; ?>&lpid=<?php echo $lpid; ?>">Click Here Now</a>
This does generate a hyperlink, however when I click it, I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=' at line 2
I understand for this code to work the page has to be saved in php. I thought wordpress did this automatically?
Can anyone help please? Also, please bear in mind I am using the Optimize Press plugin.
Many thanks in advance!
Tom
I have a script to write out the number of hits each of my websites got each day of the week since I don't trust Google Analytics spying on my websites. The problem is that I have to query each day individually and count how many instances there are with that domain. Since I setup my database give me the time, location, demographics, etc. on each line I'm not sure how to optimize this further. Help would be greatly appreciated. Code: [Select] echo '<table><tr><td>Domain</td>'; foreach($timearray as $t){ echo '<td>'.$t.'</td>'; } echo '</tr>'; $i = 0; foreach($urlarray as $u){ $today = date("Y-m-d"); $yesterday = date("Y-m-d", mktime(0,0,0,date("m") , date("d")-1, date("Y"))); $lastmonth = date("Y-m-d", mktime(0,0,0,date("m")-1 , date("d")-1, date("Y"))); $twoweeks = date("Y-m-d", mktime(0,0,0,date("m") , date("d")-15, date("Y"))); $result3 = mysql_query("SELECT refer,Count(*) as count FROM `approved` WHERE time>'$lastmonth 23:59:59' AND time<'$today' AND refer LIKE '%$u%'"); $row3 = mysql_fetch_array($result3); $result4 = mysql_query("SELECT refer,Count(*) as count FROM `approved` WHERE time>'$twoweeks 23:59:59' AND time<'$today' AND refer LIKE '%$u%'"); $row4 = mysql_fetch_array($result4); if($row3['count']==0){echo "<tr style='background:red'>";}elseif($row4['count']>0){echo "<tr style='background:green'>";}elseif($i % 2){echo "<tr style='background:#CCC'>";}else{echo "<tr style='background:#FFF'>";} echo '<td>'.$u.' '.$row3['count'].' '.$row4['count'].'</td>'; foreach($timearray as $t){ $result = ''; $result = mysql_query("SELECT COUNT(*) AS count FROM `approved` WHERE time LIKE '$t%' AND refer LIKE '%$u%'"); while($row = mysql_fetch_array($result)){ echo '<td>'.$row['count'].'</td>'; } } echo '</tr>'; $i++; } echo '</tr></table>'; Hi, My hosting disabled my account because my site used too many system resources (CPU). There is no way for me to know how much CPU my site is using since i am not a psychic or god so no clue how they expect me to monitor this or fix this (the site has been running just fine for 2 years with the same code). Is there any code that can tell me how much CPU my site is using on the server? Thanks in advance, Jay Hello, So I am trying to reduce my memory footprint to the lowest possible value without sacrificing functionality. I noticed that if I write a comment that is 2kb long, it costs me 2kb more memory to run the script. How can I get PHP to free the memory taken up by comments? It seems like it would be a real pain in the butt to have to run php -w on all my source files each time I update my server. Any ideas? Thanks. David For example, take a look at this: https://code.google....p/phpwebsocket/
When I run the server, it works fine and I am using the server for my Inventory system on my game. When users drag and drop items in their inventory to change position, it sends the data to the html 5 websocket server, and updates the positions accordingly/etc. And I will use it for a bunch of other stuff later.
My question is: What kind of VPS would I be looking for in terms of ram/cpu power to keep a websocket server like this up 24/7? Is it more memory intensive than socket/io/nodejs? Or what? How can I test these things? Looking at cmd.exe or php.exe in my task manager when having it run on my local windows machine isn't really a good way to test performance, or to estimate how much ram or VPS/CPU power of a server I'll need before launch. I can get a idea, but I don't think it's going to be close to reality. That's why I'm asking you guys here if you would know. Thanks
Edited by Monkuar, 17 January 2015 - 12:24 AM. Hi guys, Yet another rookie question, trying to implement this: I have a function: <?php //MyHelper.php function getnext( $name ) { $conn = DB::table('counter')->where('name', $name )->first(); $result = $conn->findAndModify( ['name' => $name], ['_id' => ['seq' => 1]], ['seq' => true], ['new' => true, 'upsert' => true] ); return $result['seq']; } ?> And I am calling it so: $db_array = getnext(array('name' => 'role_id')); print_r( $db_array); Results in call to a member function on NULL, not sure where I'm going wrong! It is making a connection and the counter table has a 'role_id' in it. Can anyone tell me where I'm going wrong? I have searched a lot but no information about this aspect. I wonder how much heavy is the process of getting parts of a webpage by preg_match? But my question is that which of these options are in favor of lighter CPU process: 1. getting each item between specified tags by a preg_match or 2. First getting the content between <body>, then processing by php tools such as preg_match (again), explode, etc. Thanks for considering this unusual question So I'm debating whats the best method. I'm aware that catch/blocks should be used in exceptional cases but what if it saves me from having 4 nested if/else conditions? The following is code for an xbox registration site Code: [Select] try { // check code is valid $c1 = $this->input->post('code1',true); $c2 = $this->input->post('code2',true); $c3 = $this->input->post('code3',true); $gt = $this->input->post('gamertag',true); $pass = $this->input->post('password',true); if( $c1 == '' || $c2 == '' || $c3 == '') { throw new FormError("Authorization code invalid."); } // check db for code validation $q = $this->db->query("select * from `codes` where `activated` = 0 and `code` = ".$c1.$c2.$c3." limit 0,1"); if($q->num_rows() != 1) { throw new FormError("Authorization code invalid."); } $r = $q->row_array(); $email = $r["recipient_email"]; $codeGt = $r["gamertag"]; // check valid gamertag $q = $this->db->query("select * from `users` where `gamertag` = '".$gt."'"); if($q->num_rows() > 0) { throw new FormError("Gamertag already exists."); } // validate gamertag /w inputted gamertag if(strtolower($codeGt) != strtolower($gt)) { throw new FormError("Gamertag Invalid"); } $this->_createAccount($email,$pass,$gt); // show register-thanks screen $this->load->view("register-thanks",$data); $success = true; } catch (Exception $e) { $data['error'] = $e->getMessage(); } I have some simple test code: Code: [Select] echo memory_get_usage(true); echo("\n" . '<br />' . "\n"); echo memory_get_usage(false); echo("\n" . '<br />' . "\n"); echo memory_get_peak_usage(); that prints out the three types of memory usage in bytes for my basic admin page. All three values are around 2.25 MB in bytes. What's best practice for PHP memory usage? Is 2.25MB far too much for a single user's visit? Do these PHP memory values include images in the page? |