Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=323161.0
-
You are not getting the alert?! Then there is likely a javascript compile error. What browser are you using? It should have an error icon to indicate a JS error. I see a couple of problems function getFile (url) { var url = "AJAX/get_Bank.php?dealType="+ this.value; if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();} You are passing a value to this function - but it is not being used. You are overwriting the value passed to the function on the first line. I think you mean to append the passed value on the end of that string. I don't even think this.value would work in that context. So, use a different var name for the input var and do something like this function getFile (urlInput) { var url = "AJAX/get_Bank.php?dealType="+ urlInput; if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();} Also, the page get_Bank.php defines a variable $bank, but doesn't do anything with it. You need to echo the variable to have it passed back to the JavaScript code.
-
Ah, sh*t. Yes, you are correct. Anyway, everything I staded previously about strip_tags() still applies. As for strip_tags(), yes you should use that. But, it is debatable about where and how you should use it. There are reasons why a user may use "tags" in their input. For example, someone may put their nickname within their real name such as "Bob <The Boss> Davidson". By using strip_tags() before saving the the database the nickname would be removed without any knowledge of the user. My preference is to always save exactly what was entered. Then when using/displaying the data, escape it as necessay. For example, before saving to the database, use mysql_real_escape_string(). BUt, if I was displaying the data to the page I would use htmlentities() or htmlspecialchars() to ensure the data down not break the HTML code. But, if the data was being used to populate a form field so the value can be edited I would take a different approach. If you escape data in any manner before saving it, you can not restore it (with any confidence) back to its original status.
-
Try the following $ip = $_SERVER['REMOTE_ADDR']; $httpref = trim($_POST['httpref']); $httpagent = trim($_POST['httpagent']); $name = trim($_POST['name']); $email = trim($_POST['email']); $phone = trim($_POST['phone']); $debtor = trim($_POST['debtor']); $agree = trim($_POST['agree']); $employee = trim($_POST['employee']); $formcontent = "From: $name \n Email: $email \n Phone: $phone \n Debtor: $debtor \n I hear by agree that the information I have provided is true, accurate and the information I am submitting is not fraudulent. Please click the agree button that you adhere to Commercial Recovery Authority Inc.'s terms: $agree\n Employee ID: $employee \n IP: $ip"; $recipient = "mail@crapower.com"; $subject = "Online Authorization Form"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo "Thank You! -<a href=\"index.php\" style=\"text-decoration:none;color:#ffcb00;\">Return Home</a>"; //$ip = $_POST['visitoraddress'];
-
First of all, you should not populate the IP address in the form and then use the posted values. Users can easily modify any data they want in a form - even hidden fields. Just get the IP address on the page that processed the data, then the user cannot modify it. Of course, they can always spook their IP address, but there is nothing you can do about that.
-
strip_tags() has nothing to do with security. You are already "securing" the data from sql injection by using mysqli_real_escape_string() which is exactly what you should be doing. The reason you would use strip_tags() on user input is that some servers have "magic quotes" turned on. The purpose of magic quotes was to automatically escape the data. But, it has several problems. For one, it modifies the input data before you have a chance to do validations. For example, it could screw up a date inputand even prevent it from being inserted into the db correctly. Second, it is a generic escape procedure that does not apply to all contexts. There can be differnt procedures for escaping data for different databases - or you might be sending the data to an entirely different system. So, magic quotes - as a rule - should be disabled on the server. But, because a lot of people are on shared servers we do not always have the option to turn it off. So, IF the server has magic quotes turned on THEN you should use strip_tags() ont he input. As I said in the first post, look at the manual for strip tags. There is a snippet of code that you can call in the head of any page that receives user input. IF magic quotes are enabled, strip_tags() will be applied to all of the input values. Plus, if you were to apply strip_tags() when the server is not using magic quotes you can potentially remove some of the user input! That way you will always be dealing with the original input by the user. Then you modify the data as needed based on the context you will use it in.
-
I would also suggest changing those echo statements to something like this echo "Postcheck: [$postcheck]<br>"; echo "Post: [$post]<br>"; It could be something as simple as a leading/trailing space, which the brackets should make apparent. You should also view the HTML source code to see if there is anything different.
-
Because you are not checking the LENGTH of the password. Your condition is trying to compare a string to a number. I think a string will resolve to 0 in that instance. Here is some revised code. There is a lot more I would do with this though. A couple of changes I made are: 1. Moved the code to process the input to be after the condition check to see if data was posted. No need to try and process the data if you haven't even verified there was posted data. 2. Compared the password and repeat password before hashing it. You only need to hash the password once. No need to hash before comparing. 3. Implemented elseif statements to remove all the nested loops. Other things you could/should do. 1. Do NOT use striptags on input unless magic quotes is turned on. Look at the manual for strip_tags() for code you can implement to automatically strip tags only when needed. 2. You could set a flag at the start - then determine ALL the errors and display them to the user. As you have it now after the first error is encountered it only gives the user that particular message even if other errors exist. 3. Add more error handling for the data - such as checking the date field to ensure it is really a date value. include('connectvars.php'); if (isset($_POST['submit_signup'])) { $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = strip_tags($_POST['password']); $repassword = strip_tags($_POST['repassword']); $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); //Check that all required fields were posted if ((empty($user_email)) || (empty($firstname)) || (empty($lastname)) || (empty($nickname)) || (empty($password)) || (empty($dob))) { echo "Please fill out all the fields!"; } //Check length of data elseif (($nickname > 30) || ($firstname > 30) || ($lastname > 30) || ($user_email > 50)) { echo "Your nickname, first- and/or lastname seem to be too long, please make sure you have them below the maximum allowed length of 30 characters!"; } // check password char length elseif (strlen($password)>25 || strlen($password)<6) { echo "Your password must be between 6 and 25 characters!"; } //Check that passwords match elseif($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { // encrypt password $password = sha1($password); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = sprintf("INSERT INTO user (firstname, lastname, nickname, password, email, dob, doj) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $firstname), mysqli_real_escape_string($dbc, $lastname), mysqli_real_escape_string($dbc, $nickname), mysqli_real_escape_string($dbc, $password), mysqli_real_escape_string($dbc, $user_email), $dob); mysqli_query($dbc, $query); mysqli_close($dbc); echo "You have been successfully registered!"; } } } } }
-
@james: There is no reason to "exit" a double quoted string to include variables. One of the features of using a double quoted string is that variables within the string will be interpreted. However, one problem with the original code posted is the array value. The key for the array was NOT enclosed in quotes. It will work, but is not correct. The parser will first try to find a constant named "username" before it treats it as a string. When using variables in double quotes you can use curly braces around variables so that you can use quotes around keys and to solve other problems where the variable may be misinterpreted due to the context it is used in. Here is a another method of defining that code: if (isset($_POST['submit'])) { $xx = 'lol'; echo "{$xx}, yo dawg!"; mysql_query("INSERT INTO xx (xx, xx) VALUES ('{$xx}', '{$user['username']}')"); } @Toy: This is a shot in the dark, but are you running this code from an AJAX request? If so, your javascript code needs to have a handler to receive the input from the PHP page and do something with it. If this page is being called to be loaded in the browser and that message is not being displayed, one possible reason would be if there is a redirect OR the output is placed within other HTML code such that it is not being rendered correctly.
-
displaying links depending on ID from another table
Psycho replied to xox's topic in PHP Coding Help
If he was referencing fields that do not exist, his queries would be failing. -
displaying links depending on ID from another table
Psycho replied to xox's topic in PHP Coding Help
Learn how to do JOINS - never run queries in a loop - it is a huge performance hit on the server. Below is a much better approach, but I don't know why your code wasn't showing the sub categories. Most likely, the data is not properly "linked" in the database. $query = "SELECT c.ID, c.name, sc.name_subcategory FROM `categores` AS c JOIN `subcategories` AS sc ON sc.id_main_category = c.ID"; $result = mysql_query($query) or die(mysql_error()); //Flag to determine change in category $currentCatID = false; //Process the records while($row = mysql_fetch_array($result)) { //Test if this is a new category from the previous if($currentCatID != $row['ID']) { //Display the category name and set flag echo "<br /><b>{$row['name']}</b><br />\n"; $currentCatID = $row['ID']; } //Display the subcategory echo "{$row['name_subcategory']}<br />\n"; } -
There is an easy answer regarding very long words. Take a look at the manual for wordwrap() - specifically the 4th parameter! http://php.net/manual/en/function.wordwrap.php However, that code will not work as you intend it to. the wordwrap() function doesn't take into consideration existing line breaks. So, if your first line has 64 characters and a pre-existing line break (6 characters), the wordwrap function will attempt to add a line break after the 10th character on the next line. What I think you want is to only wrap lines that are greater than the width, but leave existing lines that already have line breaks alone. The only way I can think of to do that is to process the text line by line. There may be a more efficient way to do this, but I think this will do as you are looking for function wordWrapPreserve($inputText, $maxWidth) { $inputLines = explode('<br />', nl2br($inputText)); foreach($inputLines as $key => $line) { $inputLines[$key] = wordwrap($line, $maxWidth, "<br>\n", true); } $outputText = implode("<br />\n", $inputLines); return $outputText; } //Usage echo wordWrapPreserve($text, 80);
-
First of all you want to start by writing valid HTML code. That is not even close. There is no value parameter for a select tag. And the selected option in your example doesn't have a value. The code we provided will do as you ask - but YOU need to determine how you are going to identify the "selected" option. As stated in our previous posts you need to set a value some how. But, here is a more length code example. I will leave it to you to figure out how to implement in your specific code; <?php //Set $pageName to the value that should be pre-selected //In this example I am hard coding the variable because I //don't know how it should be determined in your code $pageName = 'Home'; //Create array of values for select list - loop uses foreach //This can also be done with a DB query and using do/while loop // as shown in previous responses above $optionsAry = array('Home', 'About'); //Create the HTML for the options $menuOptions = ''; foreach($optionsAry as $optionValue) { $selected = ($optionValue==$pageName) ? ' selected="selected"' : ''; $menuOptions .= "<option value=\"{$optionValue}\"{$selected}>{$optionValue}</option>\n"; } ?> <select name="menuName" value="options"> <?php echo $menuOptions; ?> </select>
-
To expand on that, I find it prefereable to set the selected value independantly of the echo statement. Makes the code cleaner and more readable. Your original code doesn't state the value that the options are being checked against to determine the selected value. ChemicalBliss used $pageName in his example, you will need to determine what that value is and set it accordingly. Anyway, here is my take (assuming this is performed in a loop from a DB query) <?php $menuOptions = ''; while($row = mysql_fetch_assoc($result)) { $selected = ($row["menuName"]==$pageName) ? ' selected="selected"' : ''; $menuOptions .= "<option value=\"{$row["menuName"]}\"{$selected}>{$row["menuName"]}</option>\n"; } ?> <select name="menuName" value="options"> <?php echo $menuOptions; ?> </select>
-
How you store the data is not the problem. When retrieveing the text from the database, you *could* partially truncate it using MySQL substring function (getting it slightly larger than what the maximum is you would allow) and then use PHP code to further refine that output. That *might* be more efficient since not as much data would have to be managed in memory. I don't know, but it might be worth testing. But, no matter if you do that or not, you are going to want to use PHP to determine the final output. The problem you have, however, is that PHP cannot determine how wide the text will be displayed on the page (see excpetion below). The number of characters is not definitive in determining this since each character has a different width: a "W" is much wider than the letter "i". One workaround is to use a fixed-width font, but that is not a pleasing display to the user With a fixed width font every character has the same width So, you can go with a fixed-width font and determine how many characters you want to display on a line or you have to come up with some limit of characters that you think will apply to 99% of input using a non fixed-width font. And, as for this $content = str_replace("\n","<br />",$content); That is NOT what you want to do, because a line break is treated differently based upon the server. Could be "\n", "\r" or "\n\r". That is why PHP has the function nl2br(); which will convert line breaks into BR tags for you. $content = nl2br($content);
-
Without seeing your code we really can't help you. Also, I'm not sure what "login" has to do with your problem. Anyway, here is a small function that will truncate a line of text to a specified number of characters (if needed). It will only truncate on whole words, so if the max characters falls within a word it will truncate to the previous word. Also, there is an optional parameter to add ellipses (or any other value) to the end of the text if it is trucated: //Return a string up to a certain number of characters //but will break on a space function truncateString($string, $maxLength, $ellipse='...') { if (strlen($string) <= $maxLength) { return $string; } return array_shift(explode("\n", wordwrap($string, $maxLength))) . $ellipse; }
-
Building upopn BlueSkyIS's response, if you just do an include it will output any code to the page that time.php produces. However, if you want to set a variable then you can just set up time.php to do a return just like you would do in a function. Example time.php file <?php $time = date('H:m:i'); return $time; ?> Then in the page that calls time.php use something similar to what you have $file = include('./time.php'); echo $file; Note that file_get_contents() by passes the PHP parser and you will get the actual contents of the file (i.e. the code). To get the PHP parser to process the file you need to use include(), require() or one of the variants.
-
include() makes much more sense.
-
AHH GOING CRAZY! WHILE LOOP INSIDE OF WHILE LOOP
Psycho replied to innopar's topic in PHP Coding Help
The loop has an IF condition to test if the parent record is different from the last one. I used the flag $currentCatID. If the value of the current record's parent ID is different from the last one, then show the parent record details and set $currentCatID to the parent's ID. Then on the next iteration of the loop, if the parentID of the record is the same it doesn't show the parent data. However, in your modificaion of the database field names you used one value to do the test and another when setting the value! if($currentCatID != $row['id']) { $currentCatID = $row['pid']; A couple other things. There are some problems with the HTML content you are creating that will generate orphaned HTML tags and invalid markup. I *think* I know what you are trying to achieve. It seems the parent record should be part of a list since it starts with an LI tag. But, there is no ending LI tag. It looks like you are trying to put that closing LI tag for the parent code at the end of the code for the sub category tag. But, that won't work because you would generate multiple closing LI tags for each sub category. In this situation, where you need some closing code after all the child records have been displayed, I prefer to take a different approach. I will create a function to display the parent and all the child records at once. Then in the loop I will create an array to hold all the values. Once a parent and all the child records have been added I run the function. I also think this method makes it much easier to visually "see" how the code is produced Also, you are using SELECT * in your function. Unless you really need all of the fields, it is more efficient to only query for the data you need. Lastly, since you have fields in the two tables that are "similar", instead of calling one "name" and the other "title", just name them something like "cat_name" and "subcat_name". (Also, unless you changed it you also have a problem where the ID field for both tables is named the same). It may seem redundant to reference a field such as "cat.cat_name", but it is very helpful when you have foreign IDs to be able to tell what table the ID is linked to. So, if you used cat_id in the cat table and the subcat table, you could JOIN the two tables using the USING statement, such as SELECT * FROM cat JOIN subcat USING cat_id Anyway, here is some revised code. Note: I put the comment "//DB NAME" after each line where the code references a field from the query. If you need to modify the query make sure you modify these lines as necessary. Also note that this is not tested since I don't have your DB to run against and I wasn't going to create a db table and mock data just to test it. So, there might be some syntax errors, but the logic should be good. //Function to generate HTML output for category and its subcategories function categoryHTML($subcatList) { //Start parent category output (get name/id from first record) $categoryName = $subcatList[0]['cat_name']; //DB NAME $categoryID = $subcatList[0]['cat_id']; //DB NAME $htmlOutput = "<li class=\"level0 nav-2 parent\" onmouseover=\"toggleMenu(this,1)\" onmouseout=\"toggleMenu(this,0)\">\n"; $htmlOutput .= " <a href=\"product.php?cat={$categoryID}\"><span>{$categoryName}</span></a>\n"; $htmlOutput .= " <ul class=\"level0\">\n"; //Create subcategory ouput foreach($subcatList as $subcat) { $subCatName = $subcat['subcat_name']; //DB NAME $subCatID = $subcat['subcat_id']; //DB NAME $htmlOutput .= " <li class=\"level1 nav-2-1 first\">\n"; $htmlOutput .= " <a href=\"product.php?cat={$categoryID}&subid={$subCatID}\"><span>{$subCatName}</span></a>\n"; $htmlOutput .= " </li>\n"; } //Close parent category output $htmlOutput .= " </ul>\n"; $htmlOutput = "</li>\n"; } //Create and run query $query = "SELECT cat.id as cat_id, cat.name as cat_name, subcat.title as subcat_name, subcat.id as subcat_id FROM cat LEFT JOIN subcat ON subcat.pid = cat.id"; $result = mysql_query($query); //Process the output $categoryID = false; //Flag to determine change in category while($row = mysql_fetch_assoc($result)) { //Check if new category from last record if($categoryID != $row['cat_id']) //DB NAME { //New category - set flag $categoryID = $row['cat_id']; //DB NAME if(isset($subcategoryList)) { //Get content for previous category/subcategory data $output .= categoryHTML($subcategoryList); } //Reset list $subcategoryList = array(); } $subcategoryList[] = $row; } //Get content for last category/subcategory data $output .= categoryHTML($subcategoryList); -
AHH GOING CRAZY! WHILE LOOP INSIDE OF WHILE LOOP
Psycho replied to innopar's topic in PHP Coding Help
I don't see anything abvious. But, you only need one while loop and, more importantly, you only need one query $query = "SELECT c.name as cat_name, c.id as cat_id, sc.name as subcat_name FROM cat JOIN subcat as sc ON c.id = sc.pid"; $result = mysql_query($query); $currentCatID = false; while($row = mysql_fetch_assoc($result)) { if($currentCatID != $row['cat_id']) { $currentCatID = $row['cat_id']; $output .= "<li class=\"level0 nav-2 parent\" onmouseover=\"toggleMenu(this,1)\" onmouseout=\"toggleMenu(this,0)\"> <a href=\"product.php?cat={$row['cat_id']}\"> <span>{$row['cat_name']}</span> </a>\n"; } $output .= "<ul class=\"level0\"> <li class=\"level1 nav-2-1 first\"> <a href=\"product.php?cat=$catid&subid={$row['subcat_id']}\"> <span>{$row['subcat_name']}</span> </a> </li> </ul> </li>"; } -
From the manual: http://php.net/manual/en/function.file-get-contents.php
-
You're right. He did say I totally missed that. That is actually very simple: SELECT ( IF(field1='CHECKED', 1, 0) + IF(field2='CHECKED', 1, 0) + IF(field3='CHECKED', 1, 0)) as counter FROM db1 WHERE row_name = 'science'
-
There's no need to run a query to return back a large result set just to count the records. That is a waste of server resources. That is what COUNT() in queries is for.
-
SELECT COUNT(field1) as field1MaxCount FROM table WHERE field1 = 'MAX' GROUP BY field1
-
COUNT() only works if you use GROUP BY. Can't tell from your current query what the GROUP BY clause should be.