Jump to content

requinix

Administrators
  • Posts

    15,229
  • Joined

  • Last visited

  • Days Won

    427

Everything posted by requinix

  1. Complex refactoring rituals would still happen. They could be used to increase the efficiency of code, even if not to make it easier to read. Design patterns would still exist. A design pattern is simply a common solution to a problem. They aren't necessarily object-oriented. Frameworks would still exist. They're to save time in development not having to reinvent the wheel. Application stacks would still exist. They're combinations of software so as long as software exists, they will too. "Refactoring" is merely rewriting with the intent to somehow improve the code. Improvement in maintainability is one possibility. Improvement in efficiency is another. Those are are often mutually exclusive. Code that looks horrible means that it will be harder to alter. I'm half-asleep.
  2. First, what version of PHP are you using? If it's not at least 5.4 then can you upgrade to at least 5.6?
  3. That'd be fine. While websites should definitely update the expiration time, APIs are a little more flexible. You could enforce a hard limit of X minutes on just the API if you expect whatever operations (eg, with the mobile app) will last much less than that time. However once that time is up the user will have to log in again; the app could keep the username and password in memory (it really shouldn't if at all possible) but otherwise the user would need to type the information in again. So yeah, updating is fine. The latter (setting a flag) is probably fine for the site. It's more of a technical question: would the site actually need to use the token later? You could impose a security layer within the stored procedures such that "sensitive" operations require a token before they can perform any action. For example, changing a password could require a username, password, and token, where it uses the token (after validating it, of course) to identify the user performing the update and checks whether that user is allowed to do so: if the token corresponds to that user or to a particular sort of administrative user that is allowed to change passwords then update the password, else fail. The API would work differently since APIs don't really use sessions. I mean you could, but then you force the consumer to deal with cookies and that can suck. If you decide against the added security then your API would be the one that validates the token (via a stored procedure) and does the update. Questions are good. There should never come a point in your life where you don't have questions to ask. About anything. It would be nice if other people reading this thread commented too, though.
  4. If you don't mind PHP evaluating up to 800 conditions to get the value of a single variable, sure.
  5. IS NULL is how you check whether a value is actually NULL or not. You will get true/1 or false/0. = NULL is normal comparison, except when you compare something with NULL you will simply get NULL as the result. Try it: SELECT 1 IS NULL; SELECT 0 IS NULL; SELECT NULL IS NULL; SELECT 1 = NULL; SELECT 0 = NULL; SELECT NULL = NULL;
  6. Floating-point arithmetic Round your calculations but only at the very end.
  7. Depends what you mean by "the site". The PHP code behind your site will not use it, but the AJAX and Javascript on your site will - that's how it communicates with the server. The mobile app would use it too.Basically it comes down to whether the thing is running on your server (PHP code) or not (AJAX runs on the browser, mobile app runs on mobile). ...Maybe? I don't think I understand what you're saying. You're developing a site which includes a user login component. The external API is /api/users/login and is the only way code that is not running on your actual server can interact with the server. So AJAX and third-parties would use it. (For all intensive porpoises your mobile app is "third-party" because it's not running on your server - you just happen to be its developer too.) The internal API is what the stuff that is running on your actual server, as in the actual PHP code, interacts with. Or I guess put another way, consider what the code for /api/users/login would look like. You receive some input (GET, POST, whatever), somehow get that to your stored procedure, receive the token, and return it however you'd like as output. The question is exactly what the "somehow get that to your stored procedure" is. Obviously your code needs some way to communicate with the database, but it could do so directly (by setting up a database connection, binding parameters, and executing SQL) or indirectly (by calling other code which communicates with the database). If you do it directly then that's alright. If you do it indirectly then whatever you use there to fill in the gap would be the internal API. Directly: <?php // /api/users/login $email = $_POST["email"]; $password = $_POST["password"]; // this example here uses output parameters from the proc. yours simply returns a resultset $connection = new mysqli_or_pdo_or_whatever(/* parameters */); $query = $connection->create_a_statement_for_the_stored_procedure(); $query->bind_the_parameters_to_the_query($email, $password, $variable_to_receive_the_token); $query->execute(); return json_encode(array( "token" => $variable_to_receive_the_token ));Indirectly with an internal API. <?php // /api/users/login $email = $_POST["email"]; $password = $_POST["password"]; $user = User::login($email, $password); // User::login will somehow, directly or indirectly (via yet another internal API), communicate with the database to log in return json_encode(array( "token" => $user->token ));The internal API has a number of advantages, most notable being:- Much less code - The exact mechanism of how to log in are abstracted away and the /api/users/login doesn't need to know them - The mechanism can change so long as the API ("provide me with an email and password and I will return you a User object") looks the same Therein lies a problem with your API. Or rather, the code you have in place to perform the work for your API. Yes, you are correct in that it is like an internal API. Except it has too much knowledge about how it's being called: the information is coming from a request, it knows the parameters are called "username" and "password", and it outputs JSON according to the result. You won't be able to reuse that anywhere and reusability is a big principle behind an API - internal or external. What you should do is split it apart into two pieces: one to receive data from the request and send whatever output, another to handle just the login. // this function can handle a login that originates anywhere // it returns an array in a specific format that is independent of how the calling code needs to react function loginUser($username, $password) { try { $sql = "CALL checkPassword(:username, :password)"; $dbCon = getConnection(); $stmt = $dbCon->prepare($sql); $stmt->bindParam("username", $username); $stmt->bindParam("password", $password); $stmt->execute(); $result = $stmt->fetchAll(); return array( "loggedin" => $result[0]["loggedin"], "uid" => $result[0]["uid"], "firstname" => $result[0]["firstname"], "token" => $result[0]["token"], "potentially" => $result[0]["field1"], "other" => $result[0]["field2"], "useful" => $result[0]["field3"], "data" => $result[0]["field4"] ); } catch (PDOException $e) { // calling code should not need to know about PDOException or anything specific like that // wrap this into a more general exception throw new loginUserException("Failed to log in", 0, $e); } } // this function can handle a login but only if the information comes from the request in // a specific format and only if the response can be JSON in a specific format function loginUserFromRequest() { global $app; $req = $app->request(); $paramUsername = $req->params("username"); $paramPassword = $req->params("password"); try { $return = loginUser($paramUsername, $paramPassword); // the function returns an array with a lot of stuff. we only care about some of it echo json_encode(array( "uid" => $return["uid"], "loggedin" => $return["loggedin"], "firstname" => $return["firstname"], "token" => $return["token"] )); } catch (loginUserException $lue) { echo json_encode(array( "error" => array( // notice that this will always say "Failed to log in" // never expose database error messages! "text" => $lue->getMessage() ) )); } }loginUserFromRequest() is a mere function, but provides the backbone for the /api/users/login external API. In an MVC architecture, it is your controller (and view).loginUser() is an internal API and provides the backbone for other code in your application to log a user in. You can reuse it anywhere that you have a username and password. loginprocess.php would have code that resembles loginUserFromRequest() in that it gets the username and password from the request, passes it to loginUser(), receives the result, and displays something to the user. Let me turn the question around on you: is the site in a state where you can leave it alone? If so, feel free to focus on the external API. You'll probably end up refactoring parts of the site as you go anyways. But if there is something wrong with the site and it's in a state where you shouldn't leave it alone and go work on something else, then... well, there's your answer.
  8. There are two main types of APIs and I think this may be confusing you: 1. An external API, like the kind you would put at a URL like /api/users/login. Javascript/AJAX on your site can call it, other third-party services can call it. Your PHP does not call it. This API is not necessary for a "traditional" site where you have a POSTed login form, but is important if you want to use AJAX (or let other people call your API). 2. An internal API. This isn't accessible by anything but your own PHP code. Your stored procedure to login is an example of this: it provides an interface between "you" (your PHP code) and "the service" (the user login data in the database.) If you wrote some generic code to call it, as in some User class with a login() method, that itself would be a sort of API because it is the interface between "you" (other PHP code across the site, like the code for loginprocess.php) and "the service" (whatever thing is in place that deals with logging users in). The API you have now that returns JSON is fine. The login token is fine; I suggest some mechanism to refresh a token, however, or else people will be forced to log in every X minutes regardless of whether they were active or not. (You can refresh on a hit to an API and on a page load on the site.) Unless you're talking about a "remember me"-type token which is used to log someone in automatically, but your description doesn't quite sound like that. Your PHP does *not* use the external API, and this is where those two types of APIs come into play. If your PHP used it, it would have to call a page on its own website, which would execute code elsewhere in parallel, and after all is said and done you've created a lot of needless work for your code and your server. What you should do is create the internal API. This is the code that connects to the database, runs the stored procedure, and returns whatever information. It will have two consumers: loginprocess.php calls it when someone submits the form, and the /api/users/login API calls it when someone invokes it. Thus the two execution flows are 'user -> submits login form on website -> loginprocess.php -> internal API --+ | v database | redirect user or whatever <- loginprocess.php <- internal API <-+' ' login page -> AJAX -> /api/users/login -> internal API --+ | v database | JS reacts <- response <- /api/users/login <- internal API <-+'
  9. Automatic refresh means refresh the page. Load it from scratch. F5. Doesn't know anything about new data because it loads everything all over again. So... is that still sufficient? Add a to your HTML output, replacing number with how many seconds you want it to wait before refreshing.
  10. Look at the line above to see if there's something wrong with it.
  11. It has been removed with PHP 7.
  12. Would it be sufficient to simply refresh the page every few seconds? Automatically, that is.
  13. Shh.
  14. Where's the Dislike This button?
  15. Adding the level should be as simple as UPDATE table_with_the_planets SET whatever_thing_youre_updating = whatever_thing_youre_updating + column_with_the_levelI have no idea what any of this has to do with rarity, or really why you need to "add what level the planet is" in the first place.
  16. No. Don't do it. That's bad. You have an array already and it has everything you want. Just use $array[1] and [2] and so on. Dare I ask... What's this array, why does it look like you have 1-178 sorted like strings and partitioned into those sub-arrays, and why do you think you need to put them into separate variables?
  17. Because whenever you want to run a query, you'll find yourself going to some other place in code where you do a query, copying the code there to connect to the database (because you don't remember the server or username or password), and pasting it in the new code. And if anything there changes, like if you moved to a new host, then you'd have to go through the code you have, change the information, then copy and paste the changed code to everywhere else you need. With OOP you put most of that code into a class. There's still some code that you write/copy elsewhere, but there's less of it and it's much less likely to change in the future.
  18. You mean procedural and object-oriented code for interacting with databases? Because databases themselves are... neither. Question doesn't make sense. Procedural tends to mean a lot of copy and paste, with all the bad things that can mean. Object-oriented makes nicer code.
  19. PHP won't just make something null. It looks like the only way to change $_db is using set_db_adapter(). Have you checked whether it's being called with a null $db_adapter?
  20. It seems like you simply have the wrong username and/or password. Is there a place where you configure user accounts? Does it say that actual username? Sure you have the right password? You are connecting to the database from code running on hosted site, right? Not locally?
  21. I wasn't trying to I wouldn't use my own code for real because it's not clear how it works. There's something to be said for code that's longer but easier to understand.
  22. And the code for Session_DB_Handler would be...
  23. Have you considered showing us the code so we don't have to make blind guesses?
  24. No string manipulation functions? No functions at all! Unfortunately it turned out much simpler than I thought it would. $input = " this is phpfreaks"; $output = ""; $word = ""; for ($i = 0; @$input[$i] != ""; $i++) { if ($input[$i] == " ") { $output = " " . $word . $output; $word = ""; } else { $word = $word . $input[$i]; } } $output = $word . $output; echo "[{$output}]\n"; [phpfreaks is this ]
  25. You've got a try/catch up there at the top that will show an error message if PDO had a problem. Was there an error?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.