PHP - Best Practice For Php Page Memory Usage?
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? Similar Tutorialsthe 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 ? 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. I've been doing some benchmarking for memory usage for a very resource-sensitive project I'm doing (that I probably shouldn't be using PHP for, but oh well). I came across something peculiar, and I'm trying to figure out why I get results as I do. Here is my test file: <?php $string_parts = 4; $max = 10000; $arr = array(); $i = 0; $start = memory_get_usage(); for(;$i<$max;$i++){ $arr[] = array_pad(array(), 4, "A"); } $end = memory_get_usage(); printf("%d iterations, %d bytes in array\n", $max, $end-$start); $arr2 = array(); $i = 0; $start2 = memory_get_usage(); for(;$i<$max;$i++){ $arr2[] = array("A", "A", "A", "A"); } $end2 = memory_get_usage(); printf("%d iterations, %d bytes in array (%.2f%%)\n", $max, $end2-$start2, ($end2-$start2)/($end-$start)*100); ?> Output on my system: Code: [Select] 10000 iterations, 4145696 bytes in array 10000 iterations, 5585744 bytes in array (134.74%) A 35% memory gain for two of the same exact arrays seems really weird. Any information as to why, or perhaps any useful functions or resources would be appreciated. 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 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? 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 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 This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=320813.0 I was wondering how to resize DIVs based upon their usage. I have some vague ideas of how to do it, but not sure. Basically, the more a user clicks a DIV, the large it becomes relative to all other DIVs (no DIVs ever disappear!) Any ideas? This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=319964.0 Hi,
I study a php book and every thing is going fine, the problem is that I dont know how to practice what I study...
iv'e searched alot in the internet of exercise and found few but not every thing there is the same as what I study and sometimes they ask me to do things that I dont know yet..
some people saying that you need to think about a project and start building it but I dont have enough knowledge so start build something on my own..
right now I know about if/else, loops, operators, functions and objects, arrays, date and time, and file handling.
so most of the exercise I find involving mysql that I dont know yet.
can someone give me tips maybe how he started to study php?
it will help me alot and im sure it will help to more people.
thakns in advance,
guy.
Hi. I've been learning OOP and watched a video on YouTube about a "secure" OOP PHP login script. It was pretty good, and helped me to understand some OOP approaches, but I couldn't help thinking some of it was wrong. I'm not sure so feedback appreciated! The class starts of something like this: Code: [Select] <?php class Login { private $_id; private $_username; private $_password; private $_passmd5; private $_errors; private $_access; private $_login; private $_token; public function __construct() { $this->_errors = array(); $this->_login = isset($_POST['login'])? 1 : 0; $this->_access = 0; $this->_token = $_POST['token']; $this->_id = 0; $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username']; $this->_password = ($this->_login)? $this->filter($_POST['password']) : ''; $this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password']; } Isn't "hard" setting variables, like the POST vars in the contruct bad? Shouldn't they be passed through elsewhere? I've learnt that OOP needs to be reusable and manageable as it's primarily the point of using OOP in the first place. I might be wrong but I noticed straight away that the above class doesn't seem reusable (in the true sense). Hopefully i'm getting the hang of it... Thanks mysql_query("INSERT INTO people (company, lname) VALUES ('clean($_POST[Company])', 'clean($_POST['lname'])' "); using a clean function in the query instead of doing it before hand? Hi, (Apologies in advance if this is a total newbie question - if it is, just give me some idea on what I need to search for!) I have written php code that essentially pulls together multiple records (using mySQL) and displays them in a webpage. The challenge I have now is making the output pretty. What is the best way to do this? I have my css file (with several styles in the format below): Code: [Select] .textstyle0 {font-family:Tahoma;font-weight:normal;font-style:normal;font-size:48px;text-decoration:none;color:#ffffff;} div.Object50 { position:absolute; padding-right:5px; top:189px; left:92px; z-index:0; text-align:left; width:437px; } And my html file (that I want to bring in the php output): Code: [Select] <div class="Object50"><span class="textstyle0">Q. THIS IS A TEST?<br></span></div> My php code is sitting in a tidy block: Code: [Select] $result = mysql_query("SELECT * FROM tbl_scores WHERE ID=$f_id") or die(mysql_error()); $row = mysql_fetch_array( $result ); $f_score = $row['score']; $f_freq = $row['freq']; echo "test" . $f_score; Do I need to update all my php code with the relevant css tags or can I reference the php? Or do I split up my php code? Do I leave my php code at the top and store all the values somewhere? Then these get pulled into html? I guess I am trying to reduce how much of the php coding I need to modify while leaving the flexibility in the design.... Until participating and reading this topic, I had though the following code was perfectly fine. I don't claim to even be good at OOP or application design, although I would like to be lol Anyway, the only functionality regarding google maps polylines I could think of in PHP, was encoding and decoding them, so I placed them in a static class: <?php /* -- Polyline.class.php @return string (encoded lat/lng) - polyline::getEncoded(-2.5675, 2.5456); @return string (encoded lat/lng's) - polyline::getEncoded(array(-2.5675, 2.5456), array(-2.5675, 2.5456)); @return string (encoded lat/lng's) - polyline::getEncoded(-2.5675, 2.5456, -2.5675, 2.5456); @return array (decoded array(lat, lng)'s) - polyline::getDecoded('zmtn_?_epn_?zmtn_?_epn_?zmtn_?_epn_?'); */ class Polyline { private static $_calls = 0; private static $_lastLat = 0; private static $_lastLon = 0; // public accessors public static function get_encoded() { // $encoded to store encoded points $encoded = ''; $args = func_get_args(); if ( is_array($args[0]) ) { while ( list($k, $arg) = each($args) ) $encoded .= self::_encode($arg[0]) . self::_encode($arg[1]); } else { $cnt = count($args); if ( !$cnt ) return false; $i = 0; while ( $i < $cnt ) $encoded .= self::_encode($args[$i++]); } self::$_calls = 0; self::$_lastLat = 0; self::$_lastLon = 0; return $encoded; } public static function get_decoded($str) { $points = array(); $lat = 0; $lon = 0; while (strlen($str)) { $lat += self::_decode($str); $lon += self::_decode($str); $points[] = array($lat * 1e-5, $lon * 1e-5); } return $points; } // private private static function _encode($dec) { $dec = round($dec * 1e5, 0); if ( !(self::$_calls % 2) ) { //lon if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLon; self::$_lastLon = $dec; } else { //lat if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLat; self::$_lastLat = $dec; } $dec = isset($ndec) ? $ndec : $dec; $is_neg = stristr($dec, '-'); $dec <<= 1; // invert bits if negative if ( $is_neg ) $dec = (~$dec); //0 pad to 32 bits $dec = str_pad(sprintf('%b', $dec), 30, '0', STR_PAD_LEFT); // chunk into 5 char strings and reverse $dec = array_reverse(str_split($dec, 5)); // or with 0x20 except last one ( add 63 to each and convert to ascii ) $c = count($dec); for ( $i = 0; $i < $c; ++$i ) $dec[$i] = (isset($dec[$i+1]) && $dec[$i+1] & 31) ? ((bindec($dec[$i]) | 32) + 63) : (((bindec($dec[$i])) > 0) ? bindec($dec[$i]) + 63 : ''); // set times called self::$_calls++; return vsprintf('%c%c%c%c%c%c', $dec); } private static function _decode(&$str) { $shift = 0; $result = 0; $i = 0; do { // while ascii($str[$i++]) > ascii([space] " ") $b = ord($str[$i++]) - 63; $result |= ($b & 0x1f) << $shift; $shift += 5; } while ($b >= 0x20); $str = substr($str, $i); return (($result & 1) ? ~($result >> 1) : ($result >> 1)); } private function __construct() {} private function __clone() {} } ?> not that it matters much, since the rest of the application in which this class resides went to design shit, but; is this bad practice in your opinion? This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=346818.0 Hi Guys, I have a query regarding best practice for performance on a web application I'm developing. I am retrieving data via an API that I then need to display on a website. The data retrieved all relates to a product ID. The issue I am having is that each product has a UniqueID, but also a GroupID. The GroupID is used to display the same products but of different colour/size combinations. ie. UniqueID GroupID Size Colour 1 1 n/a n/a 2 2 Small Red 3 2 Medium Blue 4 2 Large Green I need to display the products in a list, but where there are multiple products in a group, I need to provide a dropdown selector for size and a dropdown selector for colour. I'm struggling a bit with how to structure it with just the array spat out by the API, so I was considering saving the data to a MySQL database and then querying that to get what I need. Is this a good way to go or is the double query hit going to be horribly inefficient? Cheers! I don't really have an issue with my script... I simply want to know if it is a bad practice to create a script that recurses through your root directory and zips up everything into one large zip file... I am creating a backup deal for my site and my site is rather large... Is this considered bad practice? Hi guys, so I tried searching this, but I had some issues being able to find the proper wording and keywords to query. Everything I searched PHP, HTML, Coding Standard, Coding Style, Coding, Style, Standard, etc. I got varying results. With that being said, if anyone knows of a topic that already addresses this, please feel free to link it and I will gladly do the footwork.
^ TL;DR --> I searched, but couldn't find a topic for this...
Alright, now down to the brass tacks... I am having some trouble building a function in PHP that will display the header. I believe (if I am not mistaken) that I have seen people warning against peppering PHP code with echo <HTML HERE> throughout your code. I can sort of understand why, but I admit I am not completely sure why this is. I am trying to figure out a way to display HTML without doing the following...
<?php // -------------------------------------------------------------------------- // ADMIN BAR HANDLER // -------------------------------------------------------------------------- /** * First we need to determine if the user * is logged in or not. After determining * the user's logged in status, we will then * choose to display the admin bar or * redirect the user to the login page. */ function admin_bar() { if ( defined( USER_IS_LOGGED_IN ) ) { echo "<div class='admin_bar'> Admin Bar Here </div>"; } else if ( defined( USER_IS_NOT_LOGGED_IN ) ) { header( "Location: " . LOGIN_PAGE ) ; } } ?> |