Jump to content
Larry Ullman's Book Forums

masterlayouts

Members
  • Posts

    64
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by masterlayouts

  1. Hello Larry,

     

    Thank you for all your help, I learned many things reading your books and now I am back to the desk for learning after many hours of producing. You were right that a programmer may have a very nice life doing procedural programming and I have to say that I finished a quite big project and I didn't mind 'repeating myself' as in fact was not that bad, put things in functions and the repeating part was rather easy: copy/paste and changing a few things. I like the fact that I can keep things separate, HTML, SQL, PHP, CSS. Anyway... I've got so used with your way and the patterns I learned from book that now I have a question related OOP.

     

    Is it a mistake if I use the same structure, for example the "configuration" file and the "connection" file and simply rewrite in oop syntax? Especially the database connection file that usually in frameworks does not stay outside the "http" folder.

     

    if I do write, let's say, a validation class for forms and for some project this is all that I need, is it a mistake that I do not create a CRUD class and other things like a framework has? I know it sounds like reinventing the wheel, but it is not quite like that. An existing framework has a lot of things that are useless to small projects and require maintenance that small projects do not necessary need. Why should I have the forms, for example, generated from PHP when, maybe, as part as my workflow, I prefer have them in HTML, so I can see them and work visually, like in Dreamweaver. I guess many with a background in design and not in programming would prefer it this way.

     

    Let's take for example Dreamweaver, it has some basic things that can do "programming for poets" and it is really fast, but it lacks a server side validation script. A simple validation class to resolve this issue will resolve a lot of problems and speed up the development. Will this be a bad thing ("unprofessional")?

     

    I look at your "Shopping Cart Widget" class in the book. You do not actually create a very general class and extend it afterwards in a framework style. It performs pretty particular things and probably can be abstracted more (a guess). Is that example just for study (as it compares with the procedural code before) or it may really be a production piece of code? If you add, let's say, real time quotes from Fedex, is it necessary to write a class "ShippingClass" than extend it with "ShippingFedexClass" when, assuming it is possible, writting just a functio in your Shopping Cart Widget class may provide shipping quotes?

     

    Bottom line, if we do not have very abstractizied classes for everything and keep things separate (things like forms, I believe this is a very good example), is this a mistake? Is it possible to have the best of both worlds?

     

    Thank you,

    Greg

  2. Because we plan for it and this is the client's specifications. It is a job site, so there will be many pages with job listings, split by various criteria like country, domain...etc. Here it make sense the approach learned from your book example.

     

    People apply for jobs. The number of people that apply for a certain job it's a lot smaller... we should have less than 2-3 pages with results (as opposed to hundreds and maybe thousands). Here I was thinking to make the pagination based on the number returned by mysqli_stmt_num_rows($stmt). Both are generated on the fly, but it is a safe assumption that we have a small set of results returned for certain type of pages/queries.

     

    Thank you for your answer.

  3. Thank you for your reply, I put it together and works well. I do not want to beat the death horse, but I have another question related to the issue of pagination.

     

    In the script provided we check first for a parameter p for the page, and if it's not provided we query to find out how many records do we have and split the records per page. Certainly, when we anticipate a lot of records and we do not expect (or there are not so important) changes I can certainly see the advantage of querying first for a count of the records than limit the query.

     

    Now I am thinking to two situations. First situation, when the changes operated are important (like deleting one of the records), which would require a recount.

    Second, when we expect the number of returned records to be small.

     

    In these situations, wouldn't be easier or even faster than instead of using two queries, one to do the count the second to retrieve the records, to use just the second query to retrieve the records and use something like

     

    $totalRecords = mysqli_stmt_num_rows($stmt);

     

    to get the number of records retrieved and operate the pagination based on this value. I understand that this way we have to retrieve all the results every time, which is a more expensive query in case of many records than the quick count and the second limited by LIMIT to the number entered in $display. But for the circumstances mentioned when changes are important and we do not expect a very large number of returned records, will be a mistake to make the pagination this way?

  4. Thank you for your answer. I have a search page and a result page. I changed the form method from POST to GET as per your advise.

     

    If the form has a text field named "keywords" and the value empty, also a submit button named "search" with the value "search database" when I click on the submit button I noticed a few things and I would like to ask a few questions about it.

     

    First I noticed that the URL contain a parameter 'submit' and its value, like following:

    http://localhost/results.php?keywords=&search=search+database

     

    My first question is if it's possible to eliminate the submit button from the URL (and generally if it's possible to eliminate any form element from being passed in the URL)?

     

    Than I noticed the spaces are replaced by "+". When we take the value with $_GET the "+" returns to empty space. Now if I use "+" in the keyword (like "+TV -Samsung") as in a boolean search, the "+" get encoded, where "-" and all the other characters (like double quotes) doesn't. If I search for the expression:

     

    +"widescreen tv" -Samsung

     

    the result is:

     

    http://localhost/results.php?keywords=%2B%22widescreen+tv%22+-Samsung&search=search+database

     

    I assume that I have to get the keywords value with $_GET['keywords'] and run it through mysqli_real_escape_string() and this is the search result page. Is this the proper way of doing a search-result page? I am asking because initially I was thinking to apply what I learned in the beginning of the book and use POST to handle the form, than redirect to the results page with the parameters appended to the URL and values URL encoded. I assume this is the wrong way of doing it.

  5. I have the following problem. On the page where I output the results of the query I also have the form (it is the same page). One of the fields is used by users for keyword searches in boolean mode (MATCH... AGAINST). Now if I click the link to the next set of results p=2&s=10 (let's say) I get an error because the content of the form is empty and even if I gave the parameters for "page" and "start" I do not pass the input for user's search/keywords (that input text field). I was thinking to put the input into a hidden field and the value of that hidden field will always be the $_POST for the keywords field. I am not sure this is the best approach, but I guess it is better than encoding the user input and passing it in the url. Maybe I am wrong. Could you please let me know what you think?

     

    Also wouldn't be better if we calculate the $start page based on the $page and $display (so we don't have to pass it as parameter in URL)?

     

    On a separate note I noticed that using prepared statements there are a few methods that I guess may be used for paginating results, like "mysqli_stmt_store_result" and "mysqli_stmt_data_seek". Is it possible / better to re-write the script using these?

     

    I also noticed that there are another methods for multi-query and I was thinking that they may be used very nicely on a pagination script because of the "mysqli_stmt_more_results" and "mysqli_stmt_next_result" which seems to fit perfect for the task. I would appreciate your help. This is probably one good example of beautiful things that may be achieved with prepared questions and cannot be obtained otherwise (multi-query). <suggestion> on the next edition of your book, please extend the prepared statements chapter or please write a book about it.

     

    Thank you.

  6. True, but the root of the problem is the same thing that we debate in other thread: properly sanitizing the user input. If the input is properly sanitized I do not see how anybody would benefit of a function that search for the presence of keywords such "CC" and "BCC".

     

    With the same token we should create functions that are hunting keywords to prevent SQL injection, yet we do not do that. We prefer as mechanism of defense sanitizing the user data. I would prefer not to use a function such the scrubber, but to have a high degree of certainty that the user input is properly sanitized.

     

    I expressed myself wrong, clearly there is no "body" isolated by "header", you are right to point it out.

     

    bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

  7. I am sorry, this being a written forum and not a speaking one you must took it the wrong way. Obviously I cannot pretend to you to be clairvoyant and anticipate changes in mysql engines. In fact you received similar questions about PHP6 and my opinion was (as you can probably check) that it cause no difficulties of understanding and learning PHP. I merely made a suggestion that the forum as well as the book should reflect major changes and I believe the new innodb with fullindex feature is such a major change. My point was not to through away the book, but to pin a thread, add a downloadable pdf annex to keep readers updated. I do not think is such a terrible idea and I do believe that people will continue the trend to drop myisam engine for innodb.

     

    FULLTEXT searches require a FULLTEXT index, wich itself require a MyISAM table" (pag188).

     

    One of the links posted is from owasp. They believe the first mechanism of defense against SQL injection is prepared statements. I would simply wanted to see more code in your book using prepared statements, this is what I understand by "more secure". Not that your code is unsecure, but if all reputable security sources are saying the same thing: use prepared statements, I guess a reason should be. Hence "more secure" code.

     

    You were right, the tread started with the question posted in title: "Does Form Input That Goes In A Match Query Need To Be Sanitized?". Your answer was that all user input should be sanitized. But admittedly there are degrees here as well. If I do not use the output of the query why would I sanitize the input of the parameter that goes in MATCH... AGAINST? Advising me to sanitize all input do not carry too much weight, I would certainly expect a more detailed answer. My suggestion was to look at what goes to the database and what we output from the database as separate problems. I do not know if it is a good thought or not, I am not saying, I am asking. I was expected a debate, not a fight.

     

    In any case, just for the sake of the argument, your redirect that you are using mysqli and not mysql (true), does not resolve the issue. mysqli_real_escape_string() does the same thing as mysql_real_escape_string(). What I said it fails to do is true for both of them:

    "Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection. (...) Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z."

     

    What I think failing to sanitize the backtick does is to create the risk of sql injection and it was rated as critical by owasp, not by me. I guess you understand better than me the examples offered. I can think to a simple fix, but maybe there are other solutions better than the one suggested. I guess all the examples offered in the links provided are replicable. I for one I checked if the backtick is escaped or not by the mysqli_real_escape_string function and it wasn't. Maybe I do not understand the depth of the problem, but it sure is a problem and I was hoping for your explanation and solution to the problem.

     

    I always mention that I am a beginner. When I put something down I am eagerly waiting for your answer, sometimes I know it is something wrong, but I do not understand or not understand entirely why it is wrong, so I ask to find out. Otherwise I know what I am asking is simple, but I am asking to be sure. Rest assured that I was in no way disrespectful, it was not my intention. You can take a look at the ranking and review I gave your books. But I will be more careful in the future posts and create my own tag <suggestion>, <point of debate> and so on for not to be confused with other things as blame, disrespect, bad opinion...etc. If I am wrong everywhere else, you are wrong at least here: I do not think you are a bad teacher. au contraire.

  8. if the user input is properly sanitized from the beginning i do not see how the form may be abused. The problem is why would somebody have access to the email's header in the first place? Why would somebody be allowed to enter control characters as input in the form? If it's a contact form, than the first argument of the function mail is hidden, the second should take the subject and I will let it alphanumeric, than the body. I see no point in hunting CC and BCC...

     

    $string = "\n \r";

    echo filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS);

  9. Thank you for your answer. I guess we have one kind of problems with input and another kind of problems with the output.

     

    I just gave an XSS example, but the question was meant for SQL injection as well. I am happy you address them both and made the distinction clear.

     

    In my opinion, the first kind of problems does not necessary cause problems to the other and vice-versa. One can have a XSS problem if decide to output the result query and in that result figures the attacker's crafted XSS snippet, otherwise there is no problem. In this context I was asking about the queries that perform searches based on keywords of the type that occurs in fulltext, aka MATCH... AGAINST. I see no reason to disallow a search for an input that contains tags as far as I do not output the problematic input. In this sense, I guess, the form input does not have to be sanitized against XSS, but only against SQL injection.

     

    Coming back to the injection issue I am pretty sure you know that this is not enough to prevent SQL injection. For example, the backtick it's not sanitized by this function. As result, all applications that use only the kind of protection you suggest are vulnerable.

     

    To the best of my (limited) knowledge all form input should be reduced at minimum acceptable, like alphanumeric for most of the fields. For everything else that exceeds alphanumeric input, regular expressions are preferable catered precisely for that thing. For fields like address where no discernible pattern is possible I would pretty much stay with alphanumeric. For search queries, I believe the input field should be sanitized only against SQL injection and never used the output directly on the page. For quick and general use on small projects I guess the advise would be mysql_real_escape_string() + a regular expression that will search and eliminate all problematic characters such backtick (at least).

     

    In my opinion, we should learn about mysql mode and programming without prepared statements only from an historic point of view. in fact PHP depreciated the mysql mode and suggest only mysqli and pdo.

     

    Bottom line here is the mysql_real_escape_string() fail to sanitize the input in such a way that the injection to be prevented. After small research I find out that MySQL object names are not protected by encode_sql and this is the root of the problem. Also I find out it may be fixed at the server level in that particular file. There are a few interesting links I like to share:

     

    http://stackoverflow...5811853#5811853

    https://www.owasp.or...ion_Cheat_Sheet

    https://makandracard...names-for-mysql

     

    I hope this is useful. I am just surprised that a huge security hole such the failure of mysql_real_escape_string() to properly sanitize backtick was not mentioned in your book (or forum). It should be as unless prepared statements or stored procedure are used, everything else is vulnerable and the severity of the problem is critical. At the end of the day it's an easy fix: eliminate backtick's from user's input. But how many are actually doing it?

     

    Overall, from the time you wrote the book I guess there are several thing that changed, such as everything you said about myisam and innodb engines. Now innodb engine supports fulltext indexing, so pretty much nobody will use myisam. Than everything else that lacks prepared statements should be just an historic perspective. It would be more interesting to be taught to write secure code from beginning. When it comes to mysql_real_escape_string() function it must be said always that it is not enough and at very list the input should be sanitized against backtick.

  10. All form input has to be sanitized and run through mysqli_real_escape mechanism. My question is do we have to sanitize the form input for that/those field/fields that will add to a query whose function is just search and that input is never displayed or otherwise used in the application? As result risky user input as the attempt of XSS or SQL injection may happen. I am interested to know if the database will take care of the input and escape it or do whatever it is necessary by itself or do I have to sanitize the input before add it to the query?

     

    $q = 'SELECT subject, body FROM messages WHERE MATCH(body, subject) AGAINST($_POST['unsanitizedUserInput'])';

     

    user enter:

     

    <IMG SRC="javascript:alert('XSS');">

     

    Where user may enter anything at all, in my example I put for brevity an XSS attempt, that obviously cannot do anything wrong here, but it is not my example that I want to discuss but the concept behind it. I cannot think to any input that may cause problems, but some other people may do. Sorry for the syntax errors, I hope I am made myself clear even if the example chosen is wrong.

     

    It is a good question as in the book the examples for fulltext index are very basic and do not discuss security issues at all. In all the other parts of the book you discuss them, as in the case of mysql statements where you said to run everything through mysql_real_escape() for example. I would like to know if in case of search we do have to run the input that goes only on search through such a function or not and in general what advise you can gave us security wise about FULLTEXT searches and user input.

     

    In this example the query do not cause security problems, but maybe there are situations when it may cause security problems. Question remains: do we sanitize the user input that goes in searches or not? Thank you.

     

    $q = 'SELECT subject, body FROM messages WHERE MATCH(body, subject) AGAINST(\'<IMG SRC="javascript:alert(\'XSS\');">\')';

  11. Hi Hartley, thank you for your reply. The thing is that the number of values is variable and doing something to generate a unique name requires the same effort. I am interested in the best practices here, otherwise I assume it may be done either way. I am also interested if having the value of the parameter of numeric value is an advantage or not. I am guessing it is easier to use numbers; on the other hand if the database has a look up table to restrict the input to predefined values and this values are string I assume it is equally safe, the advantage being that it has meaning and one don't have to do any extra effort to interpret what the numeric value means. Now I do not have enough experience to decide.

  12. Sending values to a script (chapter 9), we are using hidden form fields and URL parameters.

     

    What if I want to pass more values for one parameter? (not "name1=value1&name2=value2", rather "name1" having "value1" and "value2"). In the hidden form element I guess we define the element's value as an array. I am more interested in the URL situation, what will work best.

     

    Is it safer to use numeric values as parameters or strings will be just fine?

  13. I am a little confused about session/cookies automatic interaction/behavior. You explained that it is preferable to store the email (users.email) in session and not the userID (users.userID) because the email is harder to forge than userID which is a number, hence leaving the site exposed to XSS attacks.

     

    However, for whatever operations the user may be allowed to do, like CRUD operations, you will need the id of the table for that specific action (let's say "posts" table, for example, we will need something like posts.postID) and the userID. To get users.userID from users.email we will have to make a SELECT query every time, as opposed of having the userID stored in the session, hence a query less every time.

     

    It seems to me that will be a lot more convenient to store the userID in the session. You said that it will not be a problem to have the userID stored in session as far as we do not have it stored in cookie. Here I am a little confused, because I do not understand how setting the userID in session become a cookie problem (as the argument against using the userID in session is predicted on leaking the value in the cookie and I do not understand why).

     

    I do not stored anything explicit in a cookie, will a cookie be always created when starting a session? What it will contain if no explicit value/parameters were given?

     

    If I stored the userID in the session, should I be preoccupied that it may leak in the cookie without knowing it? Is it a common behavior for the cookies to replicate sessions?

     

    Should I explicitly set a cookie every time to overwrite odd behavior or is it possible to let the cookie work automatically and do the job only from session?

     

    Shouldn't cookies and sessions be isolated and work separately?

     

    I am guessing all problems start with directives like the one you suggested on page 357. What is the effect of "ini_set ('session_use_only_cookies', 1)" when you store the userID in the session and no cookie was set explicitly?

     

    Why don't we simply use a salt and hash the value? Isn't more beneficial this approach considering that it should be safer and we end up having the userID stored, which is much more practical to use than users.email?

     

    You presented cookies as being safer from one point of view. However, sessions are stored on server, shouldn't be safer to use sessions? I see a reason why using cookies to store user settings (as selected language for the forum, for example), but I do not see any good reason to use cookies to store sensitive information as the userID. If the argument, as I understand it, is that whatever a cookie holds it can be forged easily because it is easy to guess numbers, I do not see why it is not a big problem this behavior in the first place or why does it feel safer as chances are the attacker can very easily know the email of the victim, hence being in the same situation as when using numbers. It looks more secure, but in my opinion it is a false sense of security. Emails can be as easily be guessed (or known in advance) as numbers, it is not such an important defensive mechanism. I guess my point is: never use cookies when safety is paramount... maybe I am wrong.

  14. Passing it like a variable it means something like this:

     

    q = 'SELECT email FROM ' . $tableName . ' WHERE id=? LIMIT 1';

     

    When you make a function or create a class to work with the database it make sense to have the table passed dynamically. Certainly, I was looking for something parameter wise, I just wanted to be sure I do not miss something. Thank you for your help.

  15. It looks like in a relational database there is no easy way to make it. You either go with the big query collecting all data in one query, but having this way columns with duplicated data or running several queries, this way you will not have duplicate data retrieved, but making several trips to the database will slow things a little. Depending of what we want we have to chose one of those (or take the second and using UNION to make just one trip to the database). I hoped for an easier way and it looks like it is where databases may handle hierarchical relations, which MySQL cannot do.

    • Upvote 1
  16. My approach was in the end the following: I used the correct database design and maintain the constraints at the database level as it should. This guarantees me database integrity. However, when it come to creating the user interface, those options that are less likely to ever change and are quite small in terms of choices/options I hard coded them in the page. For example we can easily add a constrain to allow just "m" and "f" for male and female, there is no need to use a query to create, let's say, a radio group in html. The same thing with look-up tables. I see no problem in having a look-up table act as constrain and in the same time hard coding the html. I found that the database integrity is maintained and in the same time, if needed, for example if some options change frequently so changing many html snippets across different pages frequently may become a pain, than I can add a query to the page to create those options dynamically for that html element of the form in the user interface. I guess this is the best of both worlds.

     

    Also I found that cached pages are more likely server options and is not difficult at all to cache pages after all. In Zend server for example, it's just a matter of clicking a few buttons.

     

    The subject more interesting would probably be query optimization. However, I guess this thread got the answers required. Thank you for your help.

    • Upvote 1
  17. I have the following database scenario:

     

    companies
    -------
    companyID (PK)
    CompanyName
    
    jobs
    -------
    jobID (PK)
    companyID (FK)
    description
    
    domains
    -----
    domainsID (PK)
    jobID (FK)
    domains ('retail', 'it, 'management'...etc.)
    
    benefits
    ------
    benefitsID (PK)
    jobID (FK)
    benefits ('free transport', 'health insurance'...etc.)
    

     

    Each job in jobs is posted by 1 company only, here I would like to limit the result to 1.

    Each job may have multiple domains.

    Each job may have multiple benefits.

     

    What would be the easiest way to retrieve the information for a specific job in jobs table? The name of the company from companies table, all the domains associated with the jobID in jobs and all benefits associated with the same jobID in benefits table?

     

    What I would like to obtain (using variable named as columns in the tables) is a multidimensional array like:

     

    [jobID] array =>
    0 => string ['description']
    1 => string ['companyName']
    2 => array [benefits] =>
     0 => string 'some benefits'
     1 => string 'another benefit'
     ... so on for all benefits associated to that jobID
    3 => array [domains] =>
     0 => string 'some domain'
     1 => string 'another domain'
     ... so on for all domains associated to that jobID
    

     

    What gives me problems is the fact that one table has 1 record only and I would like to see it enforced, where the domains and benefits table have a variable number of rows. If I join all I will have a number of records equal to 1 + number of domains with that jobID + number of benefits with that jobID. I can extract the information the way I want it, still I guess I am making a mistake and I have the feeling that it may be a better way to achieve the same result.

     

    What query is best fitted to this situation?

    Is there a better solution (maybe using views) for this complex example?

  18. Sorry for asking so many question in one thread, I was feeling they are related and just followed my train of thoughts (which derailed apparently). I'll try to keep it simpler and cleaner next time. Thank you again for answering, even to so such a crazy thread.

     

    Pag.338 the "check login" script has such logic:

     

    if($check){
    // ok
    header("Location: $url");
    exit();
    }
    else {
    // not ok, throw error
    mysqli_close($dbc);
    }
    

     

    If the data is entered in the database correctly I redirect the user to the next page or any other page such "user account". If an error is trowed than the administrator receive the email (as per your "connection" script) and the user will see a generic error message. Why (for simplicity) not sending the user to a generic "error" page. If the code stops at exit() it will not be executed further and I see no mess, but the generic "error" page. I understand that it is good practice to use if-elseif-else the way it was intended and not cutting corners. However, I see no problem in doing redirects and using exit().

     

    The other question unanswered is this. In the code above you are closing the database for one branch of the if-else, but not for the other. Extrapolating I may thing to the first example with if-elseif-else where I have 3 branches (and I can easily imagine one with more elseif's so with more than 3 branches). My question is why not performing the cleaning for each branch (in the example from your book, why not closing the database for the other branch as well?)

     

    If all this stuff is optional, than I think this is the reason why other programmers (not in your book) simply add a statement to close the databse after the last HTML tag - because it doesn't matter.

    
    mysqli_close($dbc);
    ?>
    

     

    If it matters, than I guess it should be used for each branch following the specific logic of that branch. Following your example why not:

     

    if($check){
    // ok
    mysqli_close($dbc); // perform cleaning like free statement, close query and close db, here just closing the db
    header("Location: $url");
    exit();
    }
    else {
    // not ok, throw error
    mysqli_close($dbc);
    }
    

  19. I have a question related to the scope of a conditional and what would be the best practice. A few threads away some user asked what happens when updates a record and using the "mysqli_stmt_affected_rows" to check if the record was updated or not, as well as the update is not mandatory, will return "0" if the user do not change anything. Another member gave a book answer:

    if (mysqli_affected_rows ($dbc) == 1) { // If it ran OK
     echo "Password Updated";
    } elseif (mysqli_affected_rows ($dbc) === 0) { // use three equal signs so there is no confusion with a false return
     echo "Password unchanged because it was the same as on record";
    } elseif (mysqli_affected_rows ($dbc) == -1) { // update query failed
     echo "Oopsie! System error.";
    }

    (I am using prepared statements, but the idea is the same). Now I would be tempted to say that I am interested to catch the error, so I would rather reduce the code to:

    if (mysqli_affected_rows ($dbc) >= 0) {
      // updated or canceled
    }
    elseif {
      // system error
    }

    Or even better, I would prefer to eliminate as much as possible unnecessary accolades and do just the check for the error and leave the rest of the code flow naturally. If there is no error, it will execute, otherwise what is between the accolades will execute and will probably be an exit() so it will not spill outside the conditional.

    if (mysqli_affected_rows ($dbc) < 0) {
      // do something when error occurs...
     exit();
    }

    I found it more readable this way and in OOP I would probably use try-catch in a quite similar manner I guess. I am wondering if this is a good practice or not as some may argue that it makes more sense to keep everything within the scope, in this case, the conditional statement.

     

    The question may be well generalized. For example if the user is logged-in we check for a session value, like the email in your examples. Wouldn't be easier instead of something like

    if(userAuthenticated){
    // do what is supposed to do
    }
    else{
    // throw error
    }
    

    to check for the error only.

    if(! userAuthenticated){
    // throw error
    }
    // do what is supposed to do

     

    Now it probably works either way, what I am asking is what is the best practice under the circumstances?

     

    A few moths ago I was asking a similar question regarding the validation and an user replied that changing the type of a variable is bad practice and it should be value or NULL, TRUE or FALSE. Now the code written at the beginning of your book use this practice of changing the type of a variable. You first declare it FALSE, than if it pass the validation you give the variable the value from the form. Later in the book, you are using an error_array() to catch the errors, than check if this is empty before moving forward. It works either way, but if it's agreed that it is bad practice to change the type of a variable than the second way of doing things is appropriate, even if the first one works (and I personally, using a ternary operator) I found it much easier to use, read, understand).

     

    Related to the same issue, I noticed that some programmer open the database connection at the beginning of the script/page and perform cleaning, like mysqli_free_result($query) and mysqli_close($database) even bellow the tag. Something like:

    
    mysqli_free_result($q);
    mysqli_close($dbc);
    ?>
    

    I can clearly see it is easier this way (probably they are using some automated method of generating pages), but I am wondering if it's correct (I guess not). If you insert data into the database, let's say, if it's a success you will redirect the user to the next page; if there is an error you redirect it to an error page (like the code from beginning). Either way the code will not get to the end of the page to perform the cleaning. This happen in some of your examples as well, even if you do not place it at the end of the page, but in the context of "success operation" branch of conditional. On short, most of your examples contain something similar to this:

    if (mysqli_affected_rows ($dbc) == 1){
    // do something
    }
    else {
    // error
    header("Location: error.php");
    exit();
    }
    

    Here I have two questions: if the code executes the redirect, why it reads the next line with exit()?

    Second question, why don't we treat the "error" part of the branch in the same way we treat the "success" one? Why we do not perform the cleaning before exit() statement as well? I assume closing the database connection and freeing the query are optional?

    else {
    // error
    mysqli_free_result($q);
    mysqli_close($dbc);
    header("Location: error.php");
    exit();
    }
    

×
×
  • Create New...