-
Posts
5,449 -
Joined
-
Days Won
174
Everything posted by mac_gyver
-
Calculating values returned from checkboxes using array_sum()
mac_gyver replied to terungwa's topic in PHP Coding Help
also, the $intval = function ($val)... callback function you have defined in your code has two three problems - 1) is_numeric() will allow a lot of values that aren't unsigned positive integers, which is what your query expects. in fact, it will allow a hexadecimal value which mysql happily converts to a string of characters corresponding to the hexadecimal value (depending on context) and may allow sql injection. your callback function should only allow positive integers greater than zero. is_numeric() - 2) you should not be adding the , (comma) after each value as that will leave an extra comma at the end and putting the commas between values is what the implode() statement is for. 3) when the value isn't numeric, you are returning the value as is, allowing direct sql injection. -
Should I escape values from radio input fields?
mac_gyver replied to eldan88's topic in PHP Coding Help
any value you dynamically put into an sql query statement can be anything and could be used to inject sql. if you are using the value from your radio/checkbox, such as an 'on' value or an id..., in an sql query statement, it can be anything that a bot/hacker chooses to submit and could contain sql. if on the other hand, all you are doing is testing if a radio/checkbox is set and using that logic condition to cause your code to use a value in an sql query statement that is solely dependent on your code for that value, then no, submitted sql cannot be injected in this way. also, escaping string data will only protect against sql injection in values that are used as strings in the sql query statement, i.e. enclosed by single-quotes within the sql statement. values that are used as numerical data in the sql query statement need to be validated that they are only of the expected numerical type, since sql can be injected that contains no characters that the string escape function will protect against. of course, the problem of sql injection goes away if you use prepared sql queries, where the data values are bound to place-holders in the sql query statement. in this case, your code is only concerned with application level validation, i.e. telling the user if something he submitted cannot/won't be used since it was empty, not of an expected value or format... -
those are actually alternative syntax, they are by no means shorthand (they require more typing then the traditional syntax.) simply 'read' any : as an opening { and any endwhile;, endif;, ... as a closing } and any else;, elseif(): also counts as it's parent's closing }.
-
you won't know who someone is until they successfully login. ALL your code trying to use the student_id (auto-increment value from the database table) doesn't have a value until the login is successful and at that time you should be getting the value from the row you have retrieved from the sql query. the only things you should be doing for/with the student_id are - 1) upon a successful login, retrieve that student_id from the row from the database table. 2) store this in a session variable to identify who the current logged in visitor is. 3) if you want to redirect to a page that requires the student_id on the end of the url to determine what to display on that page, use the student_id you have just retrieved from the database query. you should have no other code, either in your login form (there's none anyway) or your login form processing logic that references the student_id.
-
i was going to write a bunch of verbiage about the posted code, but it will be simpler to just post an example - session_start(); // define these values up front $mainpage = "main.php"; $hard_user = 'admin'; $hard_pwd = 'admin'; if(isset($_SESSION['logedin'])) { header("Location: $mainpage"); // already logged in, go elsewhere and don't run the following code die; } $IPaddress = $_SERVER["REMOTE_ADDR"]; // not sure why would use the ip, it's the username you are counting bad attempts against // i'm guessing you are using the $fields['Counter'] value later to control the display of the captcha? $dblogin = new PDO("sqlite:LoginAttempts.db"); $CounterCheck = $dblogin->query("SELECT IP, Counter FROM LoginAttempts WHERE IP = '$IPaddress'"); $fields = $CounterCheck->fetch(PDO::FETCH_ASSOC); if(isset($_POST['submit'])) { // form was submitted $errors = array(); // set values using $errors[] = "the error message you want"; // if you want to use and test for specific errors, you would use a specific index name $errors['some_index'] = "the error message you want"; // for form fields, the index name would typically be the form field name so that you can match up errors with the specific location in the form // you would filter/validate the submitted username/password (empty, min/max length...) and set any $errors[] elements as needed $username = $_POST['username']; // in lieu of actual filter/validation code, get a copy for demo purposes $password = $_POST['password']; // if there are $errors at this point, the username/password values are bad (empty, min/max length...) if(empty($errors)) { // no errors, check if the captcha was required // if attempt 3,4,... this form submission requires the captcha value and it must match before attempting to login if($fields['Counter'] >= 3){ $imagetext = trim($_POST['imagetext']); // check for empty if(empty($imagetext)) { $errors[] ="The captcha phrase cannot be empty"; } else { include "captcha/securimage.php"; $img = new Securimage(); $valid = $img->check($imagetext); // check if it matches the expected value if(!$valid) { $errors[] = "Invalid Captcha"; } } } } // if there are $errors at this point, the username/password values are bad and/or the captcha was required but did not match if(empty($errors)) { // no errors, attempt to authenticate the user if($username == $hard_user && $password == $hard_pwd) { // login worked $_SESSION['logedin'] = 'success'; $dblogin->query("UPDATE LoginAttempts SET Counter = '0' WHERE IP = '$IPaddress'"); // Redirect to the page header("Location: $mainpage"); exit(); } else { $errors[] = 'Invalid Username or Password'; } } // at this point, login was unsuccessful, either due to bad username/password values, a bad captcha (when required), and/or wrong username/password $query = "INSERT OR IGNORE INTO LoginAttempts (IP, Counter) VALUES ('$IPaddress', 0)"; // start at zero $dblogin->exec($query); $query = "UPDATE LoginAttempts SET Counter = Counter + 1 WHERE IP = '$IPaddress'"; $dblogin->exec($query); } ?>
-
the mysql_ functions will be removed in a future (not yet specified) php version. at that point in time, you will not be able to upgrade the php version (or hope your web host doesn't have a habit of upgrading versions without telling you) until you redo your code to use either the mysqli or PDO database functions. the point of officially depreciating the mysql_ functions now, in favor of the msyqli or PDO functions, is to give everyone a warning that they need to start switching over their code so that there won't be a mad scramble later when the actual date that the mysql_ functions are removed gets announced. all new code should use either the msyqli or PDO functions to avoid wasting time later redoing it just to get it to work again. short-answer: the mysql_ functions will be available for some amount of time (likely a few years), but if you know they are obsolete and are going to be removed, why continue to use them knowing you will have to rewrite any code that uses them? just write your code now to use one of the replacements and save all the time it will take to redo code again in the future or at least abstract your database layer so that at most all you will need to do is replace the underlying database functions.
-
it's easiest to use exceptions with pdo statements to catch errors and handle logging/displaying error messages. the connection always throws an exception if it fails and once you have created a connection, you can configure the pdo instance to throw exceptions, which you can use a try/catch block around to handle, for all other statements that fail. see this link on how to use a try/catch block for the connection and how to configure pdo statements to throw exceptions - http://us3.php.net/manual/en/pdo.error-handling.php
-
1) all of the super-global variables are set on every page request. they may be empty, but they are always set, so, isset($_GET) will always be true. 2) by definition all the super-global variables are arrays, so, is_array($_POST) will always be true. 3) you shouldn't escape the data and leave it in the $_POST array itself as that will alter it, so if you are echoing it back in the form fields it won't necessarily be the same as what was submitted. if you are going to escape all the $_POST data, you should escape a copy of the data and only use that escaped copy in sql query statements. i also hope you are properly validating numerical data since using a string escape function on them won't protect against sql injection. 4) you shouldn't be using the mysql_ functions any more since they are depreciated and will be removed in an upcoming php version. you should be using mysqli or PDO functions, where you can use prepared queries and avoid the need to do any escaping of data. 5) to do what you want, would require either using a function like array_walk_recursive() and let php do the work for you or you would loop over the $_POST array and detect if each element (the $value variable in your) is an array or not.
-
the destination parameter of the move_uploaded_file() function must include the file name. yours only has the path.
-
you would probably want to start by checking if your form tag has a method='post' attribute and if your form fields have name attributes and with those specific names for values.
-
you probably shouldn't assume that the data in the csv is in any particular order and pre-processes the data by storing it in an array using the username as an array key and storing each booking id as a sub-array under the username it belongs with.
-
you would implement some type of a selection menu, either a search text box for part/all of a team name and produce link(s) for the matching team(s) or just make a <select><option></option>....</select> menu with all the teams listed. if you then select one of the teams, via a link or the select menu, you would request the same page you are on and pass the team id in the url. if the $_GET parameter containing the team id is set, you would use that id in a WHERE clause in your query to match only the rows you want. if the $_GET parameter is not set, you would not add that WHERE clause to the query and it would then match all the rows.
-
this is the second thread you have started for this task. in your previous thread, you were shown how you can run ONE query, with no loops. i am merging your two threads together so that anyone currently replying will have the information presented in the previous thread. if your $content string you are showing use is what you are really doing, you would form that expression in the SELECT part of the INSERT ... SELECT Syntax you were given in the previous thread
-
you need to do some investigating and find out exactly what is occurring and when it is occurring in the process. 1) when you change the language setting to specific language, is a cookie being set in your browser with the correct value in it? 2) after you refresh the page or redirect does the cookie still exist in the browser with the correct language set in it or has the cookie in the browser been changed to English? 3) does the variation of the sub-domain/host-name (i.e. www. vs no www.) in the url in your browser's address bar change when you refresh or redirect? 4) does the url have any ?language=xxxxxxxx value it in after you refresh the page or redirect and if so, what is the xxxxxxx value? 5) do you have php's error_reporting set to E_ALL and display_errors set to ON so that you would know if there are any php detected errors affecting the setcookie() statement? 6) do you have any code that's testing the language setting that could be setting it vs testing it (i.e. one = an assignment, vs two == a comparison)? short-answer - you need to pin down at what point the value is correct, both in the cookie in your browser and in the $_COOKIE that's sent (or not sent) from the browser to the server-side php code, and where it changes to an incorrect value in order to find where and what's causing the problem.
-
code to set the cookie - $cookie_name = 'defaultLanguage'; // set cookie only when the url contains a value if(isset($_GET['language'])){ // note: you should validate $_GET['language'] to insure it contains exactly only one of the permitted values before using it at all setcookie($cookie_name, $_GET['language'], time() + (86400 * 30), '/'); } code to get the cookie value - $cookie_name = 'defaultLanguage'; // get cookie value or a default $cookie_value = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : 'English'; // note: you should validate $cookie_value to insure it contains exactly only one of the permitted values before using it at all
-
the logic setting the cookie to a default of English is ran unconditionally, so any time you visit the page where the setcookie() code is at, it will set the cookie using whatever $_GET['language'] is, even it if there's no $_GET['language'] on the end of the url. you should actually only set the cookie when $_GET['language'] is not empty and use the absence of the cookie to default to English.
-
array_filter and count not acting as expected
mac_gyver replied to davidannis's topic in PHP Coding Help
in your form field names, because you have single-quotes around the new, 75, 79, ... index names, the names will also include those single-quotes. remove the single quotes. your print_r() should show the following (with no quotes around the index names) - Array ( [new] => Array ( [0] => EE ) [75] => Array ( [0] => EE [1] => DCF ) [78] => Array ( [0] => EE ) ) -
the symptom is that of a form tag that doesn't have the enctype attribute in it. it's likely that you have multiple forms on the page and are ending up with an extra opening <form ...> tag or a missing closing </form> tag, resulting in your upload form being nested inside of a non-upload form. you would need to post your complete code that's producing the page with the form. the snippets of code you have been posting don't show anything to do with code using session variables and aren't the full story.
-
and, even if the session variable are being set as expected in the login() function, if the session start on that page has failed (there would be php errors), the login isn't actually working because the session variables will only exist as local variables and won't be propagated between pages. did you set the error_reporting/display_errors settings on each page or better yet those should be set in your php.ini on your development system so you don't need to remember to put them into code for debugging and remove them when you put your code onto a live server.
-
some points about your code - 1) Please use the forum's bbcode tags (the edit form's <> button) around code when posting it in the forum. 2) you have repeated code in several places, your database connection and the ->setAttribute() statement (which should actually be in with your connection code). you are also opening/closing your database connection inside of loops. in addition to cluttering up your code with unnecessary lines of code that make it harder for us to even see what your code is doing, this repetitive opening and closing database connections in one instance of your script results in a noticeable performance loss. you should open one database connection and use that one connection throughout the code. 3) in the cases where you need to run a prepared query inside of a loop, the prepare statement belongs outside of and before the loop. the only thing inside the loop is the code that gets each set of data values and the ->execute(...) statement. 4) you need to solve one problem at a time and only post the code relevant to one problem at a time. if your upload is not working, there's no point in trying to display anything. your upload form(s), assuming they are on the same page, need different names in the name='...' attribute for the different purposes so that you will know what to do with the different types of uploaded images - agent, logo, and property. your upload form processing code is trying to use a nonexistent php variable - $_FILES1. $_FILES is the only variable name that php puts uploaded file data into. also, i'm guessing there can only be multiple images for the properties? that would be the only field you would use an array name for.
-
a symptom of variables changing value/having unexpected values in them, that are not due to program logic errors, is usually due to php's register_globals being on and having same names for $_GET, $_POST, $_COOKIE, $_FILES, $_SESSION variables. what php version are you using and is the register_globals setting ON?
-
the display strings you have created/defined for categories/subcategories... need to each have a unique id (automatically) assigned to them and be stored in a database table (the database table will also have a 'parent' column that relates subcategories to the corresponding parent category. main categories will have a parent id of zero.) your program logic should only be referencing the id's (this will allow the names to be changed at any time and will actually result in the fastest running code.) then, to add a unique program operation, like a size check reminder pop-up, you would simply test for the id(s) that correspond to that operation.