Jump to content
Larry Ullman's Book Forums

Antonio Conte

Members
  • Posts

    1084
  • Joined

  • Last visited

  • Days Won

    126

Everything posted by Antonio Conte

  1. If you are interested in the mechanics behind the scene, look at iterators. They are objects that keeps track of pointers in an array. It's fairly common to see this code pattern (Some alternations bases on language) // You would've done it this way in Java: // Get the iterator object Iterator it = obj.iterator(); // Check if we have a valid next before calling it. // Will return true if next is available, else false while ( it.hasNext() ) { String element = it.next(); // returns array element } // PHP don't have index bounds in arrays. array[10] will throw exception if empty in Java. // Not in php. Therefor, no need for hasNext() in php. Only make sure we return 'null' when // next(); is called (next() is implied - just how it works logically if you want to compare) while ( $row = $mysqli->fetch_array(MYSQLI_ASSOC) { $row[''] } The reason behind this is to protect the array from being tempered with directly. You create one controlled passage for the users. It's all about creating easy to use functionality. My tip is not to care why it works, just how to use it. Trust that the black box works.
  2. Hehe. Nah. I mess up when it becomes to many nested arrays. I'm more of a fan of adding objects to arrays and play with them that way instead. I hate doing array operations on multidimensional arrays as they ca be both tricky and little efficient. (That was generally speaking. The object solution probably has a lot more overhead than mapped key, value pairs for this kind of small data structures) If I were to program this myself, I would built a normal array with "key" => $object, pairs. Then I would send that array to the session array. $curtain_array( "fabric", new Fabric( input ), "pole", new Pole(input)); $_SESSION['product'][] = $curtain_array; foreach ( $_SEASSION['product']['the_curtain_id_received'] as $obj ) { $this->price += $obj->getPrice(); } Implementing some simple interface will pretty much do the job here. A base class could get a lot of the job done and prevent code duplication == saved time. But I gotta say, I learned OOP in Java, not in PHP. I know this is not usually "how you do it", just my preferred way.
  3. Yes, there are distinctions, but I cannot guarantee the names I used are what they are known as. It's mainly the large companies that have gotten criticism for this. Sites like google, and several more I cannot remember, was caught tracking the user's activity online even when they where searching other pages than their own. This is an article about this from a respected norwegian information technology website. I looked it over with google translate now. It works fine to get the essence: "Third party cookies" is the name used at digi.no. http://www.digi.no/876017/nettbrukere-spores-med-%ABsupercookies%BB
  4. I agree with Jon. It seems like we maybe should take a look at your session array. It feels wrong to me. I would start with your naming. Why 'curtain_basket' instead of 'basket'? Why 'final_curtain_quote' instead of 'quote'? I don't say this to criticize you, because I think you went for clarity when choosing these names. My guess are that they get to long and complicated. Keep it simple. Started to look at your "A $_Session Multidimensional Array" post again. I think we need to identify the products in this setup. track poles are the "hangers" for the curtains, right? Do they differ in price? Are they stored in the db? fabric_drop and fabric_width describe the curtains height and width, right? How do you price that? I don't know the other stuff you wrote about in that thread, but selection them is adding to the price, yes? Can you choose different lining and are there price differences? I think I'm starting to make my point now. The question is what you can identify as "products" here. I think we need to build arrays of arrays here. Most of what you save her has price, right? And names, ids in the DB, and so on. To keep track of what they want, you need to build several small products (poles, lining, stuffing, etc) that together combine the curtain. I'm starting to think the session array should look more like this: $_SESSION['curtain'] = array( // Store what kind of fabric, sizes, and price for this material "fabric" => array( "id" => 10, "type" => "Chinese silk", "width" => 75, "height" => 175, "price" => 10, // You know better how to calculate this ), // Poles cost too. If they want to upgrade pole, it costs "pole" => array( "id" => 54, "name" => "Curtain master 3000!", "size" => 100, "price" => 2, ), // Customer want heading. Price is set "heading" => array( true, "price" => 1 ), // Don't want this, and cost is set to 0 "lining" => array( false, "lining_type" => "Elegant", "price" => 0 ), // Dunno what this is... "fullness" => array( "price" => 2, "fullness" => "Extra Fluffy", ), // or this... "interlined" => array( "Price" => 3 ), "total_price" => 0, // Add amount for each product here for the total "total_products" = 0, ); With this kind of code, you can easily summarize the price and send you a good description of that the customer wants. You should create several functions that can create these small products before the curtain is complete and ready to order: Something along this: (Notice the example above was filled out. Here comes how you can use it:) // User browses fabric types and find a fabric she wants. // The id and fabric price is found in a DB / or already stored in the product (maybe via get or something) // When the user spesifies the needed data, the total cost is calculated for the product. // The product is then added as one part of the full curtain product. fabric_pick( 42, "Cotton Candy patterned curtains", 75, 180, 1 ); // Same pattern as above for all products pole_pick(); heading_pick(bla, bla, bla); lining_pick( true, "Strong lining", 4 ); // Finally, all products are choosen: if ( $_SESSION['curtain']['total_products'] == 6 ) // We have 6 products { // Now the curtain is complete. It can be bought, sent to production team/whater } // User picks fabric. Add product to session function pick_fabric( $fabric_id, $fabric_name, $width, $height, $some_price_per_cm_meter_whatever ) { $fabric_price = ($width * $height) * $some_price_per_cm_or_meter_whatever; // Add the fabric product values $_SESSION['curtain']['fabric'] = array( "id" => $fabric_id, "name" => $fabric_name, "width" => $width, "height" => $height, "price" => $fabric_price, ); // Update number of products for THIS curtain. // We want to keep track of fabric, poles, headings, etc // to know when the CURTAIN is done customizing an ready to be ordered. $_SESSION['curtain']['total_products']++; // And update total price $_SESSION['curtain']['total_price'] += $fabric_price; } // User picks a pole. Add product to session function pole_pick( $value, $value... $value ) { // Add the pole product values $_SESSION['curtain']['pole'] = array( "label" => $value, ..... "label" => $value ..... ); // And remember that we now added a pole product. $_SESSION['curtain']['total_products']++; // And update total price $_SESSION['curtain']['total_price'] += $calculated_pole_price; } No worries. I'm very hard to offend. You won't be able to do that just by discussing programming.
  5. Are you sure it's cookies and not global cookies they won't allow? Jon talked about "tracking users online", which is what a super cookie does. Normal cookies do not do this. I've seen debates on the use of super cookies, but none on normal ones. From a legal perspective, I also believe the law is about personal information and not plain settings. The reason behind this must be to secure the anonymity of user online, not to prevent basic settings from being stored. Just some thoughts. Glad Norway is not a part of EU...
  6. You need to read the function description. You are getting the error message because $_SESSION['curtain_basket']['final_curtain_quote'] is not an array. (And the function needs an array). array_sum() calculates the total of all numeric values in an array. That means: $array = array(2, 5, 3, 10, "strings will be skipped"); $sum = array_sum($array); // $sum is now 20 I bet this is really not what you are looking for. This is probably more like what you want: $sum = 0; foreach ( $_SESSION['curtain_basket'] as $value ) { // Will add $value if it's numeric, else 0 (no change) $sum += (int) ( is_numeric($value) == true ) ? $value : 0; } You might need to change the foreach conditional a bit. I don't know exactly how the $_SESSION array looks.
  7. Just check the category_id then. You probably have something like this in your html: <form action="select_subject.php" method="post"> <p>Select bla bla_</p> <div>This <input type="checkbox" name="category[]" value="magazine" /></div> <div>That <input type="checkbox" name="category[]" value="t-shirt" /></div> <div>Other <input type="checkbox" name="category[]" value="football" /></div> <div><button type="submit">Submit</button> </form> Try placing this in select_subject.php: echo '<pre>' , print_r($_POST['category']) , '</pre>'; As you can see, it's an array when you add the brackets to name="category[]" in the form. Without them, you will only get one value. Let's say you press each one, this would be the $_POST['category'] array: array( [0] => "magazine", [1] => "t-shirt", [2] => "football" ) You can check if these values exist to add forms. In select_subject.php: $category_array = $_POST['category']; // Flip value and keys for the check $flipped= array_flip($category_array); // Set flags for form to include $magazine = false; $t-shirt = false; $football = false; if ( array_key_exists('football', $flipped) ) { $magazine = true; } if ( array_key_exists('magazine', $flipped) ) { $t-shirt = true; } if ( array_key_exists('t-shirt', $flipped) ) { $football = true; } ?> // Maybe you start your html here: // <head><body>, etc.... // The normal form <form ....> </form> // Then test the flags if ( $football) { include("football.php"); // Or echo it, whatever. } // You do the same for the others
  8. Well: Does it work? I would've split the next page into a seperate file, then figure out which forms to include/load there. You also need some kind of flag to prevent the user from reaching step2.php before done with step1.php. // session_start(); // include header //...... // Set step in process $_SESSION['step'] = 2; if ( isset($_POST['categories']) && $_SESSION['step'] == 2 ) { $forms = $_POST['categories']; // Included wanted forms // If this is not allowed on server, use a switch/if-else foreach ( $forms as $key => $value ) { include('form'.$key.'.php'); } } // include footer Just some thoughts. Might not be the best solution, but you could make that work. Set the $_SESSION['step'] to indicate the process or something. When step 1 is "valid", send the form to step2.php. You might need to store the checkbuttons in a session var instead of post, but bet you can work that out.
  9. The problem comes down to users changing cookies. Let's say you base your login system on cookie verification of user id. If a user changes his personal cookie to the ID/email/whatever of an admin, he soon has all the privileges too. Sessions are also hashed. Retrieving other users data is also therefor harder with sessions than cookies. Do you know how standard PHP functions like trim(), strlen(), etc really works behind the scene? Do you care? All you really care about is how to use them. The same applies to cookies/sessions. Just read the recommendations and move along. Someone much smarter decided this was the best solution. Stick to that unless you're a rocket scientist. For the email/id part: Store both. Use the id in CRUD operations, but don't test logic like if the user is logged in, an admin, etc with it. That is a better suited job for emails, as they are harder to replicate the hash of.
  10. Another possibility, if possible on IP boards: Add links instead of threads to each book's errata as a sticky on each forum. You can provide links instead of threads on phpBB3 boars, but don't know if that is possible here.
  11. Yes, if you need the iD. store it. The problem with Using user id is that everyone knowns numbers. If you use usernames or email adresses, you won't have that problem. The thing with user agent is to force a new login if the users switches agent. That'll probably never happen for the legit user, so it's more like a security. Chanses are, if it's not the same agent, it's someones hacking
  12. How about including the polls instead and work out anorher update mehanism? Is that a possibility?
  13. And PLEASE use the code tags when providing code. It makes it so much easier to read code when you have tabs in there. if ( code_tags_used($your_post) ) { echo "Good boy, now I might bother to help"; } else { echo "Now I might not bother"; } function code_tags_used($input) { return ( (strpbrk($input, 'code') && strpbrk($input, '/code')) != false ) ? true : false; }
  14. I think you can try one of two things: 1. Check if you can specify a time zone in Wordpress. Pretty sure you can, as this is often a problem. (Maybe there's a plugin if it's not a default option) 2. Change the default timezone before creating $todaysdate // Set timezone to london (neutral time) date_default_timezone_set('Europa/London'); $todaysdate = date("Ymd");
  15. I would look at the DateTime class. The constructor allows you to specify a time and a timezone object. Specify the neutral London Timezone Object when inserting into the DB. When you query for times, use DateTime::modify() or create an object with you timezone so it is correct. That way it really doesn't matter what time zone you use. My two cents, but there as several ways.
  16. I think you are partially wrong. Everything is a generic object (Before execution) where the type differs. In Java, this would be written as class Object<AnyType>. You define type, not the other way around. ( And because JS is weakly typed, it's done automatically ). The base object is generic and can be base types (integers, floats, strings) or complex types. It's here, in the last category, along with array and "normal" objects, we also find the function type. (In practice, It would create objects of a specific type, but the base object class works sort of like a "wrapper" for all objects, just like in Java.) That's how I've understood it, and also what I would think after working in Java, but I might be completely wrong. Maybe Larry knows.
  17. Wow! You read the Walking Dead comics too? Very cool. Just remember to actually write some code, ok? You need to grow along these books as you won't understand everything at once. You need to make some errors, correct them, read some more, then go back an improve upon you own code. Larry's JS book is awesome. I like it a lot and I would recommend it to anyone asking for a JS book. Buy it. About the "Design Patterns" book: This is an advanced book that will teach you coding principles, not so much the actual code. Even though Lasater explains a lot of the patterns in a good way, they are often advanced concepts. You should understand what things like class diagrams, class hierarchies, abstraction and types to get your money's worth. If you are curious about patterns, search a little bit on google for common pattern names and watch some youtube guides first. If you get some of them, I would say It's ok to buy it. I like this users videos a lot as he's quite good at making it interesting. Watch some videos before you buy this one at least. He also introduces general OOP here. http://www.youtube.c...ser/JREAMdesign
  18. Starting to learn something here. Most important things I've picked up so far. (For my personal understanding of JS) - Functions are objects.(!) Probably my most important discovery. I understood so much more of the JS code I've seen over the years by learning that. - That JS is event driven - Those anonymous functions and nested functions - How JS object works. Not used to that - JSON. (The syntax all makes sense now - Should really have gotten that from the abbreviation) - Simply that $ is a valid function name. A lot more of the JQuery code I've seen makes sense now. - How "simple" common tasks in JS is. I talk about just doing ordinary validation/replacing values etc. Things like simple calculations that's always impressed me. Probably something more, but these are some of the weird things I've discovered for myself as a newbie to JavaScript. I like this book a lot, Larry. Very clear explanations.
  19. Usergenerator.php: <?php class UserGenerator { private $pass_min = 8; private $pass_max = 15; private $user_min = 3; private $user_max = 12; private $user_case = FALSE; private $salt = '$2a$07$usesomesillystringforsalt$'; private $users = array(); public function __construct($pass_min, $pass_max, $user_min, $user_max, $case_sensitive ) { $this->pass_min = $pass_min; $this->pass_max = $pass_max; $this->user_min = $user_min; $this->user_case = $case_sensitive; $this->user_max = $user_max; } public function generate( $capacity = 100 ) { for ( $i = 1; $i <= $capacity; $i++ ) { $username = $this->genUsername( $this->user_min, $this->user_max, $this->user_case ); // Make sure username is unique if ( array_key_exists( $username, $this->users ) == false ) { $password = $this->genPassword( $this->pass_min, $this->pass_max ); $encrypted = $this->cryptPassword($password); $this->users[$username] = array ( 'user_num' => $i, 'username' => $username, 'password' => $password, 'encrypted' => $encrypted, ); } } return $this->users; } public function getQuery( $tablename, $columns) { $values = ''; foreach ( $this->users as $u ) { $values .= "(null,'{$u['username']}','{$u['encrypted']}'),"; } return 'INSERT INTO '.$tablename.' ('.$columns.') VALUES'.rtrim($values, ","); } public function checkPassword ( $password ) { // Query users password in DB. It will be stored encrypted, so use it here. $password_queried_from_db = '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi'; // pass = rasmuslerdorf if (CRYPT_BLOWFISH == 1) { if (crypt($password, $this->salt) == $password_queried_from_db) { return true; } } return false; } private function cryptPassword( $password ) { return crypt($password, $this->salt); } private function genUsername( $min, $max, $case_sensitive = false ) { // Set length $length = rand($min, $max); // Set allowed chars (And whether they should use case) if ( $case_sensitive ) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; } else { $chars = "abcdefghijklmnopqrstuvwxyz"; } // Get string length $chars_length = strlen($chars); // Create username char for char $username = ""; for ( $i = 0; $i < $length; $i++ ) { $username .= $chars[mt_rand(0, $chars_length)]; } return $username; } private function genPassword( $min, $max) { // Set length $length = rand($min, $max); // Set charachters to use $lower = 'abcdefghijklmnopqrstuvwxyz'; $upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $chars = '123456789@#$%&'; // Calculate string length $lower_length = strlen($lower); $upper_length = strlen($upper); $chars_length = strlen($chars); // Generate password char for char $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 0) { $password .= $lower[mt_rand(0, $lower_length)]; $alt = 1; } if ($alt == 1) { $password .= $upper[mt_rand(0, $upper_length)]; $alt = 2; } else { $password .= $chars[mt_rand(0, $chars_length)]; $alt = 0; } } return $password; } private function isNum( $num ) { if ( is_int( (String) $num ) && ctype_digit((int) $num) && $num > 0 ) { return true; } return false; } } Test.php uses this class. It will allow you to generate a specified number of users based on settings used when creating the object. The standard values will be used if non are specified. generate() let you you specify a number of users to generate with default as 100. getQuery() will generate a SQL query. You may need to change this function if it does not work for you. test.php: <?php include('UserGenerator.php'); // Create userGenerator object $gen = new UserGenerator(); // or something like new UserGenerator( 5, 12, 7, 12, true); // Generate 100 usernames and passwords $users = $gen->generate(100); // Generate query string $query = $gen->getQuery('users', 'id, username, password'); // Compare passwords. Change the function to query for the users password here. // The first password is hard coded in the function. 'rasmuslerdorf' is TRUE, the others false echo ($gen->checkPassword('rasmuslerdorf')) ? "Correct password <hr />" : "Wrong password <hr />"; echo ($gen->checkPassword('Rasmuslerdorf')) ? "Correct password <hr />" : "Wrong password <hr />"; echo ($gen->checkPassword('blablalba')) ? "Correct password <hr />" : "Wrong password <hr />"; foreach ( $users as $user ) { echo ' Username '.$user['user_num'].': '.$user['username']. ' Password: '.$user['password']. ' Encrypted: '.$user['encrypted'].' <br />'; } ?> If you PM me your email, I can send the class to you.
  20. An alternative is to create something that will build on both approaches strengths. Have the links in a DB and have a function write these links to a page like nav.php when there is a Insert/modify query to the table. Then you don't need to query each time, and can still keep links in the DB. To be honest, I don't really think this is necassary. Just modify the file and be done with it.
  21. You need to assign that array to a associative part of the sessions array. Something like this: $_SESSON['basket'][] = array( 'fabric_drop' => $fabric_drop, 'track_pole' => $track_pole, 'track_pole_width' => $track_pole_width, 'heading_tape' => $heading_tape, 'lining' => $lining, 'fullness' => $fullness, 'interlined' => $interlined, 'fabric_width' => $fabric_width, 'final_curtain_quote' => $final_curtain_quote );
  22. As a student in computer science, all I can say is that Larry is great at introducing new topics. I would've loved it if my teacher used his book as our book used is rubbish. Is this an introduction course? I have read a lot of introduction level books on the topic, and his books are the ones I would recommend for students on that level. For the students, even if you need to create assignments yourself, I would really recommend Larry as a writer. It will pay off in the long run. This is one student's opinion, but having been studying several other programming languages and been introduced to a lot more advanced topics, I feel my two cents are worth something. As said, it'll pay of in the long run.
×
×
  • Create New...