Jump to content

Psycho

Moderators
  • Posts

    12,157
  • Joined

  • Last visited

  • Days Won

    129

Everything posted by Psycho

  1. Try filter_var() with the FILTER_VALIDATE_URL flag. http://php.net/manual/en/function.filter-var.php EDIT: Never mind, the documentation states I guess you would have to create your own function to do this. I can think of two options. 1. You can either create a regex that has a complete white-list of characters AND checks the pattern. This would be very elaborate and would probably require multiple patters. 2. If the additional characters you want to allow are only accented characters have a process that replaces the accented characters with their non-accented counterparts (and saves to a temp var) and then use filter_var() on that temp value. filter_var() would then validate all the other formatting/ properties of the URL. If validation passes you can then use the original value before the replacements were made.
  2. Some possibilities based on a single Google search: http://code.google.com/p/php-imap/ http://www.phpclasses.org/package/2934-PHP-Retrieve-and-parse-messages-from-a-POP3-mailbox.html http://ezcomponents.org/docs/tutorials/Mail
  3. You are mixing up your terminology in your post so I'm not really following you. In the first sentence you are referring to 'Staff Members' (one entity) and 'Clients'. Then in the last sentence you are referring to 'Staff' and 'Members' as separate entities. But, generally speaking you want separate tables for different records. But, you may need additional tables based upon how records are related to one another. If there is a one-to-one or one-to-many relationship then you can define the relationship in the records. For example, each staff may be related to multiple clients, but each client is related to one (and only one). staff. In that type of scenario you could have a field in the clients table that is a foreign key back to the staff record's primary ID. Conversely, if each staff is associated to only one client you could store the relationship in the staff table. However, if you have a many-to-many relationship then you should use an additional table. For example, each client can be associated to one or more staff and each staff can be related to one or more clients. In this case you would have a separate table for staff and one for clients and then a third to define the relationships. That table would have a single record for each individual relationship. The records would contain the primary ID of the staff and the primary ID of the client. That is just a very general pattern. There can be many nuances that would determine your specific table structures.
  4. It is not bothersome to me. As I quite plainly stated previously I could care less what any one does or doesn't do - if it works for them great. but, if you ask my opinion I will give it. And, I still disagree with you regarding the output in the functions/methods. The output belongs in the View component not the model or controller components.
  5. You are making this much harder than it needs to be. Here are a few comments before I provide some revised code: 1. Don't use multiple queries when only one is needed. 2. If a query should only return one result then you don't need a while() loop to get the result such as this while($info = mysql_fetch_array( $queryuser )) { $check=$info['email']; // gets current email // } If there "were" multiple results you would only be left with the last value anyway. 3. You don't need to check if the submitted email is the same as the current user's. It makes no sense to do a select query to see if it matches and then do an update query. just run the update query once you verify that the email is not the same as another user's 4. Don't use '*' in your select queries if you don't need all the records. It is a waste of server resources - especially when you are only checking one field! 5. You are not sanitizing the user input and are open to SQL Injection attacks. Sample code //Preprocess email enterd from form $email = mysql_real_escape_string(trim($_POST['email'])); //Query DB to see if any other users are using the email $query = "SELECT email FROM members WHERE email = '$email' WHERE inv<>'$ivn'"; $result = mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)) { //There is another user with this email. Perform error handling } else { //No other user is using this email. It is safe to update }
  6. No idea since I don't know what set_value() even does exactly. He is using an MVC framework, it doesn't return to anything. I think echo'ing the json in this case is acceptable. Well, login_submit() is a method of that class. The class has to to instantiated somewhere and then there has to be something that initiates the method login_submit(). My position is that the method should set an error message parameter for the class then return false. If one of the redirect() conditions was met then there probably isn't a need to return anything (I assume). Example: $login = new Login(); if(!login_submit()) { echo $login->errorMessage; }
  7. @scootstah: Not exactly. What I meant was it is inefficient to run those three lines before they are needed. For example, I see a lot of people in form processing scripts where the first thing they do is connect to the database. Then they run a bunch of validations (e.g. string length, characters, etc.). If the validations pass then they run an INSERT/UPDATE query. But, if you aren't going to run the query if the validations don't pass - then why connect to the DB before doing the validations? Of course if one of the validations requires a query, that is a different story. But, the DB validations should only be done after all the other 'easy' validations have passed. DB transactions are costly and should not be run unless needed. In the previous code, I assumed the set_rules() method was setting some value to be used by the run() method. If that is the case, and it seems so, then it made no sense to run the set_rules() at the top since the run() would only be executed if the validations passed. But, the change in logic makes that moot. @CoolAsCarlito: I already gave you my recommendations. You've incorporated some and not others. And that's your choice. If you ask me my opinion on the new code I'll just suggest you follow all of my suggestions. I'm not being arrogant, but my opinions aren't going to change because you didn't want to heed them. If it works for you then fine. But, since you ask, I still think you are taking the wrong approach by echo'ing errors in the function. Since you have a class you should create an error message property. Then if there are validation errors, set the error message property. Then the function can return true/false. If false, then access the error message property and display it.
  8. Here are my suggestions/recommendations: 1. When doing validations, do a negative test so you can immediately follow with the error message. That way you have a logical flow of the validations/errors. Otherwise the validations and the associated errors are difficult to follow since they are separated at the top and bottom of the code. 2. For the user status check a switch() would be more appropriate 3. Functions, as a general rule, should not be echoing content. They should instead return a result to the instance it was called. 4. Add some comments! Be liberal with your comments so you know what your code is doing months from now when you have to make changes. [EDIT]5. Also, the first few lines that call the method $this->form_validation->set_rules: I'm not sure what that does, but I have a suspicion that what is done there is only used if the method $this->kow_auth->login is called. If so, it is a waste to always call those three lines of code for the instances when any of the validations fail. Instead, move those three lines just before $this->kow_auth->login is called so they are only executed if all of the previous validations pass. I have updated the code below to do this. Also, not sure what the function redirect() does. But, I would leave that out of the function. Instead the function can do a return true; if all validations pass or the error message if there is a failure. Then the place that calls the function can determine what to do. You also have one un-handled scenario. You have this condition if ($this->form_validation->run()) { But there is no else condition. So if that condition does not pass there will be no error message and login will not succeed. I have added an error condition for this, but leave it to you to provide appropriate text Below I have included how I would personally write that function and then an example of the usage: function login_submit() { $user_id = $this->users->get_user_id_by_username($this->input->post('username')); if ($user_id == 0) { $error = 'Incorrect username and password combination!'; } elseif ($this->kow_auth->is_max_login_attempts_exceeded($user_id)) { $error = 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again!'; } else { $user_status = $this->users->get_user_status($user_id); switch($user_status) { case 1: $error = 'Sorry you must verify your account before logging in!'; break; case 3: $error = 'Your account has been suspended!'; break; case 4: $error = 'Your account is currently banned!'; break; case 5: $error = 'Your account has been deleted!'; break; default: $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); $this->form_validation->set_rules('remember', 'Remember me', 'integer'); if (!$this->form_validation->run()) { $error = 'NEED TO ADD AN ERROR MESSAGE!'; } else { if (!$this->kow_auth->login($this->form_validation->set_value('username'), $this->form_validation->set_value('password'), $this->form_validation->set_value('remember'))) { $error = 'Incorrect username and password combination!'; } else { return true; } } break; } } //There was a failure return json_encode(array('error' => 'yes', 'message' => $error)); } Usage: if(login_submit()===true) { redirect(''); } else { echo $login_result; }
  9. That data is a serialized array. Simply unserialize() each record and you will have an array that you can access each piece of data independently. while($row = mysql_fetch_assoc($result)) { $data = unserialize($row['field_name']); echo "Street: {$data['street_address']}<br>\n"; echo "City: {$data['city']}<br>\n"; echo "State: {$data['state']}<br>\n"; echo "ZIP: {$data['zip']}<br>\n"; }
  10. "Reviled" - wow, I didn't think it was that bad
  11. OK, I had one typo in the code I provided. I changed a var name from selValue to urlValue and didn't change it in one place. The below is a complete page that works. The one thing I'm not sure if you need is the $url variable. Go ahead and try it against real data for both options. If one does not work you should see what URL is being used and how you need to modify it <?php //Test data $node->field_buy_at[] = array('display_url'=>'page1.php', 'display_title'=>'One'); $node->field_buy_at[] = array('display_url'=>'page2.php', 'display_title'=>'Two'); $node->field_buy_at[] = array('display_url'=>'page3.php', 'display_title'=>'Three'); //PHP configuration variable $newWindow = true; //Determines if the link will open in a new window //Generate a variable for the javascript code $newWindowJS = ($newWindow) ? 'true' : 'false'; //Create the options for the destinations select field $destOptions = ''; foreach ((array)$node->field_buy_at as $item) { $destOptions .= "<option value='{$item['display_url']}'>{$item['display_title']}</option>\n"; } ?> <html> <head> <script type="text/javascript"> function openURL(selObj, newWindow) { urlValue = selObj.options[selObj.selectedIndex].value; if(urlValue=='') { return false; } if(newWindow) { selObj.form.WINDOW_NAMER.value++; window.open(urlValue, 'Window_Name'+urlValue); } else { window.location = '<?php echo $url; ?>' + urlValue; } } </script> </head> <body> <form action="../"> <select name="myDestination" onchange="openURL(this, <?php echo $newWindowJS; ?>);"> <option value=''>-- Select One --</option> <?php echo $destOptions; ?> </select> <input name="WINDOW_NAMER" type="HIDDEN" value="1"> </form> </body> </html> Also, you should add one entry as the first item in the select list - else the user cannot "select" the first value since it is already selected so there would be no onchange event. I've made those changes above.
  12. There are plenty of tutorials out there. I learned through reading existing code snippets, tutorials, the manual and this forum. I think Tizag has some pretty good tutorials. As for the code working, I really didn't expect it to work off the bat. I wrote all that code without any testing as I don't have your data to test against and I made some assumptions. I'll try some mock data to test it but I'm not going to spend too much time on it.
  13. Well, I only worked off the information you provided, which was not much. The original code didn't do anything with user name or email address, so I didn't include that in the code I wrote (You should only query the fields you need, not '*'). And, why would you have separate records to store the meta_key and meta_value data? You have separate fields for each so why not one record per user with both values in their respective fields? Seems like a poor DB design - well the fact that you are storing serialized data is usually a poor option since you can't use a lot of MySQL features against those fields. I think you need to give a clearer picture of the DB design. Do you only have two records in the wp_usermeta table per user (one for the meta_key and meta_value) or can there be many records for each user? Based on the results above, there is no "county" in the serialized values of meta_value. So, the "18" you are seeing is the result of the value $regions[''] being incremented by 1 on each loop that processes the results.
  14. As you see there are many ways to skin a cat so to speak. The method you use is up to you but the method I would use would depend on "how" that line is used. If that line of code was used in a loop to generate many results I would prefere to have a single echo statement with the variables included within double quotes. Or, even better, I would concatenate the results into one big variable - then output that variable in the HTML. However, if that line is only used once, then I would prefer scootstah's method. I think it is much cleaner to separate your logic (PHP Code) from the output (HTML code). I either put all the logic in a separate file or at the top of the script to generate variables for the dynamic output. Then, in the HTML code I would only have echo statements for that dynamic content. A couple other notes: 1. The backslash, as floridaflatlander alluded to, is to 'escape' the quote mark. This tells the PHP engine that you want that quote mark to be treated as a literal quote mark character and not the closing quotemark for the string. 2. The brackets I used help the PHP parser identify the variables you want interpreted. For example, if the variable $b_x contained the value '5' and you used this line: echo " style='top:$b_xpx' " The result would fail and produce this echo " style='top:' " because the PHP parser was trying to interpret the variable $b_xpx - which did not exist. You can overcome this by enclosing variables within double quoted text with curly braces such as this echo " style='top:{$b_x}px' " This would generate the correct output echo " style='top:5px' "
  15. OK, here are some edits to your code and some pointers: 1. Do not use PHP short tags (i.e. '<?') they have been deprecated and will not work on all servers 2. Create your code in a modular fashion so that maintenance/edits is easier. For example, you do not need two different blocks of code for opening in a separate or the same window. 3. As SergeiSS stated you do not need to exit/enter PHP tags like that. You can, but it makes the code more difficult to read. 4. Do not put "code" into your JavaScript event handlers. Create functions and then call the functions. So, here is what I would do. Put this PHP code at the top of your script. <?php //PHP configuration variable $newWindow = true; //Determines if the link will open in a new window //Generate a variable for the javascript code $newWindowJS = ($newWindow) ? 'true' : 'false'; //Create the options for the destinations select field $destOptions = ''; foreach ((array)$node->field_buy_at as $item) { $destOptions .= "<option value='{$item['display_url']}'>{$item['display_title']}</option>\n"; } ?> Add this javascript function to the HEAD of the page <script type="text/javascript"> function openURL(selObj, newWindow) { urlValue = selObj.options[selObj.selectedIndex].value; if(newWindow) { selObj.form.WINDOW_NAMER.value++; window.open(selValue, 'Window_Name'+urlValue); } else { window.location = '<?php echo $url; ?>' + urlValue; } } </script> Lastly, create the form using this <form action="../"> <select name="myDestination" onchange="openURL(this, <?php echo $newWindowJS; ?>);"> <?php echo $destOptions; ?> </select> <input name="WINDOW_NAMER" type="HIDDEN" value="1"> </form> Note: all the above was written on-the-fly and is not tested. So, there may be some errors or a couple minor bugs. But, with that logic you can easily change the behavior by simply changing the variable $newWindow to true or false based upon your needs.
  16. Maybe I'm just totally lost, but I don't understand why you are joining the wp_usermeta table on itself. Even more perplexing is how you are joining the wp_users table JOIN wp_users u ON um1.user_id = um2.user_id It is being joined based upon a relationship between the two instances of the wp_usermeta table and there is no criteria of the wp_users table. Can you please describe the relevant fields from the wp_usermeta and wp_users tables? EDIT: OK, after looking at the code a little more I *think* there is a simple solution. I don't see any reason to JOIN the wp_usermeta table on itself or even to JOIN the wp_users table. Without knowing the DB structure this is sort of a guess, but I think you were just over complicating it. Give this a try: $query = "SELECT meta_value FROM wp_usermeta WHERE meta_key = 'wp_s2member_custom_fields' AND meta_value LIKE '%s2member_level%'"; $result = mysql_query($query); $regions = array(); while($line = mysql_fetch_assoc($result)) { $meta_value = unserialize($line['meta_value']); if(!isset($region[$meta_value['county']])) { $regions[$meta_value['county']] = 1; } else { $regions[$meta_value['county']]++; } }; foreach ($regions as $region => $value) { echo "Region $region: $value members<br>"; }
  17. Yeah, it can be confusing when echoing content that includes tags with quotes (or even quoted content within those quoted content). The first thing to do is to generate the content without PHP so that it works. Then, determine how you will generate the content with PHP. I assume this is what you want your link to look like <td><a href='planet_profile.php?planet=ADDRESS_VALUE'> <img src='images/star.jpg' id='ID_VALUE' style='position:absolute; left:X_VALUE px; top:Y_VALUE;'></a></td> The problem is that you were trying to put each value in the style parameter within single quote. All the values go within one set of quotes <td><?php echo "<a href='planet_profile.php?planet={$address}'> <img src='images/star.jpg' id='{$cos}' style='position:absolute; left:{$b_x} px; top:{$b_y} px;'></a>"; ?></td>
  18. imagegrabscreen() grabs a screenshot off the server that is running PHP not the client or some remote page. In order to print a web page, the page has to be rendered. This can either be by loading the file into a browser or another application that can read and interpret HTML/CSS (and possibly JavaScript) in order to determine what the page would look like. You can probably find some way to load the remote page into a browser window on the PHP server and then take a screenshot - but it would be a SS of the entire desktop. There are plenty of options for grabbing an external web page via the URL and converting it into a PDF or other format, which you can then serve to the user. Just do a Google search for "HTML to PDF" - plenty of results worth looking at.
  19. Try taking out the timediff() part of the query and do the calculation in PHP. Also, what is the purpose of the ORDER BY `time` since time isn't even in the result set? Also, as I stated before, you should NOT be using 'ON'/'OFF' for the `device one` and `device two` field values. You should change those fields to tiny ints and use 0 and 1. Those values can logically be interpreted as true/false and it will be much faster for the MySQL engine to do those comparisons.
  20. The browser can only print the page if the page has been rendered. A web page has no "display" in a sense since each display device (browser, mobile phone, screen reader, etc. may display the page differently. What you are asking is kinda possible, but it requires special software for you to purchase and install on your server. There are packages that allow you to pass the URL of a page you want to generate a printable file for. Typically the output will be in PDF. But, unless you are willing to spend money and have a dedicated server that you can install the software on, you may be out of luck.
  21. If it is getting to the successful message then the first query is getting run successfully. So, if the record is not getting updated then the 2nd query is likely failing and you aren't checking if it failed or not. But, the logic you have is flawed anyway. instead of running one query to check if the record exists and another to update the record, just run the query to update the record. Then check if any records were updated. This fixes some of the logic and should tell you what the error is. <?php //Prepriocess GET data $id = isset($_GET['id']) ? intval($_GET['id']) : false; $code = isset($_GET['code']) ? mysql_real_escape_string($_GET['code']) : false; if (!$id || !$code) { $output = "ID and/or Activation code not sent!"; } else { $query = "UPDATE users SET group='1' WHERE id='$id' AND actcode='$code'"; $result = mysql_query($query); if(!$result) { $output = "Error running query"; //This line for debugging only $output .= "<br>Query: {$query}<br>Error:<br>" . mysql_error(); } elseif(mysql_affected_rows()==0) { $output = "Invalid ID or activation code."; } else { $output = "Your account is activated. You may now log in."; } } $title = "Account Activation"; require_once('header.php'); echo $output; require_once "footer.php"; ?>
  22. No, that's not it. You need to use curly braces {} around the variable $searchSoftware, NOT parens () $sql = "SELECT softwareID, softwareName, softwareType, softwareDesc, softwarePath, ITOnly FROM software WHERE softwareName LIKE '%{$searchSoftware}%' ORBER BY softwareName"; $result = mysqli_query($cxn, $sql) or die(mysqli_error());
  23. I can answer that for him. Yes, the ampersand is supposed to be there. When you pass a parameter into a function, if you preface the parameter with the ampersand it is passing the actual reference of the variable. So, instead of being a copy of the original value - it IS the original value. It can be a difficult concept to grasp, but it's sort of like declaring the variable as global. You can see the manual on passign by reference here: http://php.net/manual/en/language.references.pass.php. $key is simply the POST field name. "key" is synonymous with the index of an array. Int he example given the function would be called using somethign such as $part = cleanPostVar($dbc, 'part'); 'part' is the key. So, the function would return the value for $_POST['part'] (if it existed)
  24. Psycho

    Question

    There are 101 ways to build the functionality for a form. You can have everything update on the page without an actual page refresh using AJAX. But, that is something you should implement AFTER you have a fully working page without AJAX. Also, a good reason why you would want to redirect the user after a successful form submission is that it will clear the POST data. Otherwise you have to handle the situation of users clicking the refresh button and preventing duplicate entries. A redirect is an easy way yo prevent this.
  25. Psycho

    Question

    I think you are mixing up the concept of pages and scripts. For example, you say the tutorial said you would need a separate "page" for the database connection. Well, a user would not navigate to a URL to do that. It is all handled int he PHP code. For the purposes of clean/efficient code you want to break down the functionality into separate scripts (files) that do specific tasks. If you have a site that is going to be interacting with the database a lot you don't want to write your database connection routine on every single "page". instead you create the script once and include() it on the pages you need it. A simple login "page" can use many different files/scripts. I suggest you read those tutorials a little more in-depth and actually try to understand the flow of the logic. Here is a rogh exampl of a possible login "page": <?php ]//Check if form was posted if($_SERVER['REQUEST_METHOD'=='POST') { //Insert code to validate the posted data if($valid) { include('form_processing_script.php'); include('confirmation_message.php'); exit(); } else { //Create error message to show in form } } include('form_script.php'); ?>
×
×
  • 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.