Jump to content


  • Content Count

  • Joined

  • Last visited

  • Days Won


Everything posted by gizmola

  1. How about just using serialize() and unserialize(). This is what php session handling does.
  2. Yes absolutely. PyCharm is simply an editor/Integrated Development Environment. You need some sort of server environment to test. It's possible to make it work in a localhost or virtual server on your workstation, but for a smallish project like this one, probably not worth the trouble.
  3. maxxd, From what I've seen, it's more a matter of the php team wanting to give developers the same tools and capabilities that exist in other languages. Adding syntax to easily use anonymous functions is yet another step in furthering that longtime goal. With that said, the associative array assignment syntax does make this a change that will cause some head scratching for long time PHP developers.
  4. Note: I edited the original post and removed the comments about the code block. I also removed the email and site url specifics. This is the line that sets that: // Enter your email addresses: @required $emailTO[] = array( 'email' => 'stefan@...', 'name' => 'Stefan' ); If that is your email address, then I don't see any obvious coding issues. So to gw1500se's point, this would suggest a configuration issue with the server, where the Mail Transfer Agent which will be delivering your mail needs to be setup and working. There are many things involved in getting a working MTA. You'll likely need support from your hosting company.
  5. This is the modern/functional programming way of handling a problem like this. I'm not a huge javascript fan, but having to practice it on occasion certainly opened my eyes to the use of filter/map/reduce and other mainstays of functional programming. I've also found this guy's youtube channel to be both educational and inspirational. You do have to do a bit of research for the php functions that are similar, but in the case of arrays there are ones like array_filter that I find are great as glue for so many smallish tasks as demonstrated by Barand's code.
  6. Good find. There are actually many of these errors where it's requesting http over https which the browser won't allow. Either the server needs to be configured to serve https or the code/configuration needs to be changed so that it uses relative paths or for some of the included external javascript and css, to use '//....' rather than 'http://'. The login fails for the same reason, as it's attempting an ajax call to: http://....com/requests.php?f=login which is denied.
  7. I'm not a big fan of extract or anything that could make a bunch of odd variables when you can just use: 'pagecontent' => html_entity_decode($row['pagecontent']), With that said, I didn't see anything exceptionally broken in your code. Probably the issue is that you aren't setting the HTTP Header to indicate you are returning json. Before your echo: header('Content-Type: application/json'); If something else is broken, you should have a message in your logs.
  8. This appears to be what you have now on submit: $sql = "INSERT IGNORE INTO bookingcategory SET bookingid=$bookingid, categoryid=$catID"; So there are 2 things to note here: On a new booking a booking row gets created and you get the id of this new booking row and store it in $bookingid For each category selected a row is inserted in bookingcategory with the bookingid and the categoryid So, the first issue you need to deal with is how will php get the bookingid that has just been created? Your primary options are either to redirect to the same script, only passing a url parameter like ?bookingid= Set a cookie with the booking id there Use a session variable I would suggest that you use sessions, since they have the advantage of hiding the bookingid from the user. If you pass a parameter, anyone looking at your system could just change the booking id parameter and see other bookings, however, if this is an admin system, perhaps that doesn't matter as much. Still sessions have great utility and may help with other problems you'll face. Now assuming, you want to be able to add to this script, the logic you described, what is missing is that you need to SELECT the booking and related information so you can refill the form variables or otherwise display the booking data which has now been saved. It should be obvious to you that you can't do that unless you have access to the saved booking id. Getting a list of the preselected categories would require a query like: SELECT c.* FROM bookingcategory bc JOIN category c ON c.id = bc.categoryid WHERE bc.bookingid = $bookingid The actual query may be slightly different as there is no way to intuit the actual column names from your posted code. The results of that query can be used to set the selected categories in your form/UI.
  9. I realized that the name of the password column in the database is 'contrasena', so you need to change this line of code: if (md5($password) != $user['realpass']) { to if (md5($password) != $user['contrasena']) {
  10. First off, there is no reason to query anything until you have insured you have input from the user. An empty username or password should fail and no querying should occur. There is no reason to do multiple queries here. Do one query by username, and use that result for further analysis. I can't guarantee this works, but it should be pretty close. Make sure you understand the changes I made and review documentation if you aren't clear. <?php session_start(); $servername = "localhost"; $dbusername = ""; $dbpassword = ""; $dbname = ""; $pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername,$dbpassword); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); if ($pdo->connect_error) { die("Connection failed: " . $pdo->connect_error); } $id=""; $username = trim($_POST['username']); $password = trim($_POST['password']); //Login if (!empty($username) && !empty($password)) { // Check the email with database $stmt = $pdo->prepare('SELECT * FROM users WHERE username=:username LIMIT 1'); $stmt->execute(array('username' => $username)); // Get the result $user = $stmt->fetch(PDO::FETCH_ASSOC); // Check if user exists if ($user) { if ($user['bloqueado'] == 'NO') { if (md5($password) != $user['realpass']) { die("contrasena incorrecta"); } else { $_SESSION['loguin'] = "OK"; $_SESSION['username'] = $username; header("Location: ./herramientas.php"); exit; } } else { die("Tu usuario ha sido bloqueado o todavía no ha sido aceptado por un administrador. Si el problema persiste contacta con contacto@leonmacias.com"); } } else { die("No hay ninguna cuenta con este nombre de usuario"); } } else { echo 'El campo usuario esta vacio'; }
  11. I apologize if this wasn't clear, but while I fixed some issues and formatting problems, I didn't mean to imply that I made the code work. Those are things we want you to do for yourself. Barand went further towards making your code actually work. If you have specific questions after making fixes, we welcome you updating the question with the latest code and any new questions you might have.
  12. Well, if you have a specific PDO question, then it would be better for future readers to do a new topic. If we are just cleaning up what you've been working on and it's dwindling down, then no worries, and continuing the topic has the advantage that those who have already been helping you will get notifications.
  13. I overstated the issue with else. It's bad form, but not an error. The uninitialized variable is probably the reason things don't work as you expect. I fixed a few issues and formatted your code properly: <?php session_start(); $servername = "localhost"; $dbusername = ""; $dbpassword = ""; $dbname = ""; $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $id=""; $username = $_POST['username']; $password = md5($_POST['password']); $func = "SELECT contrasena FROM users WHERE username='$username'"; $realpassask = $conn->query($func); $realpassaskres = $realpassask->fetch_assoc(); $realpass = $realpassaskres[contrasena]; $func2 = "SELECT bloqueado FROM users WHERE username='$username'"; $blockedask = $conn->query($func2); $blockedres = $blockedask->fetch_assoc(); $bloqueado = $blockedres[bloqueado]; //Login if(!empty($username)) { // Check the email with database $userexists = $pdo->prepare("SELECT COUNT(username) FROM users WHERE username= '$username' LIMIT 1"); $userexists->bindParam(':username', $username); $userexists->execute(); // Get the result $userexistsres = $userexists->fetchColumn(); // Check if result is greater than 0 - user exist if ($userexistsres == 1) { if ($bloqueado == NO) { if ($password != $realpass) { die("contrasena incorrecta"); } else { $_SESSION['loguin']="OK"; $_SESSION['username']="$username"; header("Location: ./herramientas.php"); exit; } } else { die("Tu usuario ha sido bloqueado o todavía no ha sido aceptado por un administrador. Si el problema persiste contacta con contacto@leonmacias.com"); } } else { die("No hay ninguna cuenta con este nombre de usuario"); } } else { echo 'El campo usuario esta vacio'; } For example, you had $id = "''"; Not sure what you were trying to do there. If you are initializing it to a null equivalent empty string then just use "" or '' I removed the ending '?>' from the file. You don't need it and it's best not to have end block statements as they can in some circumstances cause issues. I'd recommend looking at PSR-2 and adopting those standards. Something odd about your code is when you do 2 queries in a row where USERNAME = '$username'. Do one query and either SELECT * or SELECT contrasena, bloqueado. Whenever you have a header('Location:...) you need to follow that with exit/die. (They are the same function, but most people use exit). Of course currently you are doing those queries and yet you do nothing with them. Also because you are not using prepared statements with bound parameters, your code will allow SQL injection. Again, our advice is that you use PDO. Here's a tutorial that will teach you everything you need to know.
  14. The first step towards writing decent code is to properly indent and format your code. Don't put multiple lines of code on the same line. You should have a newline at the end of each line. You should have indentation for any blocks. PHP is case sensitive for most things other than function names and class names. Be consistent. Make all control statements (if-then-else) lower case. //Login if(!empty($username)) { // Check the email with database $userexists = $pdo->prepare("SELECT COUNT(username) FROM users WHERE username= '$username' LIMIT 1"); $userexists->bindParam(':username', $username); $userexists->execute(); The $pdo variable doesn't exist, however this is where it looks like you dropped in some PDO code. The consensus of experts at phpfreaks is that PDO is the better database API to use, so we'd recommend you convert everything to pdo anyways.
  15. The association with a handler and files of an extension or specific name is part of the apache configuration. There are actually a couple of different ways of doing it, and some potential security ramifications which are discussed in this blog post. It is possible to make these settings in an .htaccess file if the server has been configured to allow it. <FilesMatch \.foo$> SetHandler application/x-httpd-php </Files> This block would need to be inside a directory block if it's in an apache config for a vhost, but would be fine in an .htaccess. Note the basic regex which insures that myfile.foo will get parsed as php, but myfile.foo.jpg will not. This was a common exploit used to attack apache servers with php applications which allow uploads of images for example.
  16. The first issue with SQL is what happens when your input contains characters that are special to SQL. Quotes are the primary issue. In the old days you had to "escape" any strings, because they could have quotes that cause the SQL statement to become invalid. Consider: If the SQL is: INSERT INTO my_table (comment) VALUES ('$input') Right away you should see the issue. It quickly gets out of hand when you add in character sets and different combinations of quotes. The old way was to "escape" all the quotes before you stored them, which went through the input and tried to find all the characters that could mess up your flavor of database and add "escape" characters. The oldest version of this was addslashes which would inject backslashes into your input at each character. Even when this works, it's annoying because now you have screwed up your original input by adding a bunch of slashes that have to be removed when you read the value back out of the database. For this reason alone, using prepared statements is fantastic, as the entire issue of escaping, as well as the possibility of executing a SQL injection goes away. There is really no excuse not to do it as it's easier, less complicated and secures your code from SQL injection exploits. Everything else that Mac advised I 100% agree with.
  17. It's always good to look at how the major frameworks solve these types of problems. For example take a look at Symfony's OptionsResolver component.
  18. That is great, but don't forget about Mac's comment regarding prepared queries. You should not use variable interpolation for the sql string. Here's an article you can read that covers the topic in great detail.
  19. Before I get into this, PHP has a Boolean type. You should use it and have code like this: //Set initialization to success, and test this assumption $uploadOk = true; if (some_test_that_fails) { .... $uploadOk = false; } if (some_other_test_that_fails) { ...... $uploadOk = false; } if ($uploadOk) { // Everything is ok, proceed etc. } else { // It failed } In your case, since you already wrote the code with the "false" block first, you can simply test for "Not $uploadOk" which is: if (!$uploadOk) { // Handle Error... } else { // Proceed } There are a couple of issues with your code I see: $target_file = "$get_current_user.jpg"; You do not include this, but it implies that a variable: $get_current_user is set in some code you didn't reference or describe. Since we don't know what that variable contains, at very least we can see that when the image file is eventually saved it will be named 'Whatever.jpg'. So this is the crux of your issue... if the username is 'Someuser', then the file will be named 'Someuser.jpg'. Later on, your system expects this apparently. Because you do this query: mysql_query("UPDATE user SET user_image = 'https://.../images/users/$get_current_user.jpg' WHERE user_name = '$get_current_user' "); 3 Things here: Set the path to be relative to the document root ie. '/images/users/....' rather than using a full url. If you ever move this code, you will regret that you hardcoded your domain mysql_query is long gone from php. You should be using either mysqli or PDO. Consensus is that PDO is a better api. You should also not be using interpolation for your parameters, but instead be using Prepared statements and binding the variables to the query. See the PDO Tutorial . The problem with your file naming is that no matter what type of image you have, you make the extension .jpg. So basically, your issue can be addressed by making a few changes: Change the initialization from what I quoted above to: $target_file = strtolower($get_current_user); Notice no extension forced here. You will set the finalized $target_file variable only when you need it: if (!$uploadOk) { echo "There was an error<br>"; } else { // Tack on the extension $target_file .= '.' . $imageFileType; if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "Uploaded successfully (You may need to clear Cache to see the new image)"; // Again this needs to be PDO or Mysqli code mysql_query("UPDATE user SET user_image = CONCAT('/images/users/, $target_file) WHERE user_name = '$get_current_user'"); } else { echo ""; /// was Select a suitable image, file not uploaded yet } } Last but not least, this assumes that the files are getting stored in the right directory, since you don't specify a path to the target for move_uploaded_file. That needs to be the real file system directory path where the images will be stored.
  20. Like most languages, Python has map(). I'm not sure this is actually better than iterating, given that ltrim is a built in string method: strings = [' hi', ' there', 'friend'] print(strings) strings = list(map(lambda str: str.lstrip(), strings)) print(strings)
  21. Javascript and Ajax run in the browser, so you need tools that give you some visibility into what is going on. Most developers use Chrome Dev tools integrated into Chrome. You right click and look at the console tab for errors, as well as the network tab for HTTP requests and responses. Getting familiar with those tabs and what you can do with them are essential for debugging ajax calls in a page as they will show you whether or not an ajax call is able to connect to its target, as well as the data sent and any response or errors that might occur. Here's a video I found that does pretty good job of showing how to use the network tab to debug an ajax call.
  22. A few things you may or may not understand that are important: HTTP is stateless. There is a request/response protocol built into HTTP that you need to understand for clarity on many issues involving web applications. This is important to you for these reasons: User A makes HTTP GET request to your page, returns HTML. Closes connection. User A's browser now runs your javascript code, generates random var. User A (I assume but you did not state this explicitly) makes HTTP GET request to other page. However, server has no way of knowing that this is still user A. FIrst to the cut and dried answer: To pass your javascript variable to the database, you need to use AJAX. The typical way of doing this would be to have it use the POST method. Your PHP script that will be the target of the Ajax call, will read the value from the $_POST superglobal, so you can write that first. Again the problem is that, if this is a multi user application, how do you identify one user from another? You need some sort of id to tell them apart, and this has to be a candidate key in the database, or you will have no idea in Page 2 etc which row you should be reading back. In general, PHP sessions solve many problems for this application, and in an unauthenticated scenario, might remove the need entirely for a database. You could simply save the javascript variable as a session variable and read that in Page 2 etc. Like all things, the devil is in the details. Oftentimes people are coy about the nature of the requirement, and don't understand that there are caveats and use cases for many features. Very few of the people who answer the vast majority of questions here have the patience to exhaustively cover every possible scenario and solution in the hopes that one of them will match the problem.
  23. I don't know that you ever need to use a period. Like all file system related files, a period is relative to the current working directory. If that is truly what you wanted then you can just omit the leading slash. These are equivalent: and url("img/coins.png") In most cases, css, js, images and the like are deployed to a specific set of directories relative to the document root, so it removes confusion to always reference these files using "/img...", "/css...", "/js..." etc.
  24. Remove the period from in front of your relative paths. The location of the files should be relative to your site document root.
  • 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.