Jump to content

Psycho

Moderators
  • Posts

    12,159
  • Joined

  • Last visited

  • Days Won

    130

Everything posted by Psycho

  1. Well, you did a piss poor job of explaining what you are trying to accomplish. You stated that you wanted "the user" to select a directory. ftp_get() downloads a file from an FTP file onto the web server. If "the user" is selecting a folder to save a file using ftp_get() then you are apparently wanting the user to select a folder on the web server. I am assuming then, that "the user" is operating on the server. This is NOT the common configuration for a web application - the user is always assumed to be on a remote computer. You should have stated that the user was operating on the server and/or you wanted a remote user to select a folder on the server. Perhaps instead of criticizing people for what you perceived to be a lack of ability, you should have taken a closer look at the responses and your requests. Then you might have identified that the problem was your inability to properly explain yourself. I have an application for browsing/playing my mp3 collection and the management functionality has a feature that allows me to select the source folders for the mp3's on the server. Here is an old copy of that code, so it probably has some cleanup needed (and I have only used it on Windows, so not sure if it works on Linux). <?php session_start(); $drives_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $_DS_ = DIRECTORY_SEPARATOR; //Set the default drive $drive='C'; if(isset($_POST['drive']) && strpos($drives_list, $_POST['drive'])!==false) { $drive = substr($_POST['drive'], 0, 1); //Reset path $_SESSION['path'] = ''; } else if(isset($_SESSION['drive']) && strpos($drives_list, $_SESSION['drive'])!==false) { $drive = substr($_SESSION['drive'], 0, 1); } //Set the saved path $savedPath = (isset($_SESSION['path'])) ? $_SESSION['path'] : ''; if(isset($_GET['updirectory']) && strpos($savedPath, $_DS_)!==false) { $savedPath = substr($savedPath, 0, strrpos($savedPath, $_DS_, -2)+1); } //Set the newFolder directory $newFolder = (isset($_GET['folder'])) ? $_GET['folder'].$_DS_ : ''; //Determin the current path $path = ''; if(is_dir("{$drive}:{$_DS_}{$savedPath}{$newFolder}")) { $path = $savedPath.$newFolder; } else if (is_dir("{$drive}:{$_DS_}{$savedPath}")) { $path = $savedPath; } //Save current drive and path to session $_SESSION['drive'] = $drive; $_SESSION['path'] = $path; //Create select options of valid drives $drive_options = ''; for ($i=0; $i<strlen($drives_list); $i++) { $drive_letter = $drives_list[$i]; if (is_dir("{$drive_letter}:{$_DS_}")) { $selected = ($drive_letter==$drive)?' selected="selected"':''; $drive_options .= "<option value=\"{$drive_letter}\"{$selected}>{$drive_letter}:</option>\n"; } } //Get the current folder path $full_path = "{$drive}:{$_DS_}{$path}"; //Get the list of subfolders for the current folder $folder_list = ''; $upDirectory = "<img style=\"border:0px;\" src=\"{$_PATHS['images']}up_directory.gif\" alt=\"Up One Directory\">Up One Directory"; if($path!='') { $folder_list .= "<a href=\"{$_PATHS['current_web']}?action=browseFolder&updirectory=true\">{$upDirectory}</a><br />\n"; } else { $folder_list .= "<span style=\"font-style:italic;\">{$upDirectory}</span><br />\n"; } $folders = glob($full_path."*", GLOB_ONLYDIR); foreach($folders as $folderPath) { $folder = substr($folderPath, strrpos($folderPath, $_DS_)+1); $folderURL = rawurlencode($folder); $folder_list .= "<a href=\"{$_PATHS['current_web']}?action=browseFolder&folder={$folderURL}\">$folder</a><br />\n"; } ?> <html> <body> <div style="width:300px;"> <form name="drive_select" action="<?php echo $_PATHS['current_web'].'?action=browseFolder'; ?>" method="post"> Drive:<br> <select name="drive" style="width:300px;align:right;" onchange="this.form.submit();"> <?php echo $drive_options; ?> </select> </form> <form name="folder_select" action="<?php echo $_PATHS['current_web'].'?action=addFolder'; ?>" method="post"> Current folder: <br /> <textarea name="currentFolder" style="width:300;height:60px;background-color:#cecece;"><?php echo $full_path; ?></textarea> <br /> Select a subfolder: <br /> <div style="width:300px;height:200px;border:1px solid black;overflow:auto;padding:2px;"> <?php echo $folder_list; ?> </div> <button type="submit" name="action" style="float:right;">Cancel</button> <button type="submit" name="action" style="float:right;">Add Current Folder</button> </form> </div> </body> </html>
  2. You need to stop obsessing over needing an array - at least not in the manner you are thinking. Just because there is an existing piece of code that does something similar to what you want doesn't necessarily mean you have to do it exactly how that code was written. By dumping the results into an array and then processing the array you are making the server do twice as much work as needed. Instead you just need to modify the processing script for the db results - which is very easy using the existing code you have as a model. The example below does use an array - but not how you have it above - it is only a temporary container. By the way, that code you just posted has a flaw if you wanted to use it with a multidimensional array since it wouldn't take into account the headers. I even added logic to add the alternating background colors as shown in the image you first posted. <?php //Run the query $query = 'SELECT u.name FROM users as u JOIN groups as g ON u.Group_ID = g.id JOIN simulationgroups as sg ON sg.Group_ID = g.id WHERE sg.Simulation_ID = 5 AND g.kind_of_user NOT IN (1,2) ORDER BY g.id'; $result = mysql_query($query); //Process the results into table cells $bgColors = array('#00FFFF', '#FF8040', '#FFFF00', '#FF00FF'); $groupCount = 0; $current_groupID = false; $cells = array(); while($row = mysql_fetch_assoc($result)) { if($current_groupID != $row['Group_ID']) { $current_groupID = $row['Group_ID']; $bgColor = $bgColors[$groupCount%count($bgColors)]; $groupCount++; $cells[] = " <th style=\"background-color:{$bgColor};\">Group {$current_groupID}</th>\n"; } $cells[] =" <td style=\"background-color:{$bgColor};\">{$row['name']}</td>\n"; } //Ouput into multi-column table $columns = 4; //Set the number of columns to use $tableOutput = ''; $cellsPerCol = ceil(count($cells)/$columns); for($row=0; $row<$cellsPerCol; $row++) { $tableOutput .= " <tr>\n"; for($col=0; $col<$columns; $col++) { $index = ($col*$cellsPerCol+$row); $tableOutput .= (isset($cells[$index])) ? $cells[$index] : ''; } $tableOutput .= " <tr>\n"; } ?> <html> <body> <table border="1"> <?php echo $tableOutput; ?> </table> </body> </html>
  3. Your form is posting to a page called "bestellen.php". Is that the form page? If not, you want the form page to post to itself. You can do this by simplyleaving the action attribute blank. Then, just add logic at the top of the page to perform the validation. If validation fails, generate the error messages and redisplay the form. If validation passes include the processing page (order.php). Here is a rewrite of the form page which will do the validation as well. I only included validation for the first three fields. Note: I used an include to add the page to process the data after validation passes, using header() would remove all the data. But, using header after processing the data (for example taking the user to a thank you page) is a great idea. That way if a user refreshes the page it won't process the data a second time. <?php //Values for select lists $productList = array( 'proefmonster' => 'Proefmonster (Gratis!)', '1kartalin' => '1x Kartalin - €30,00', '2kartalin' => '2x Kartalin - €58,00', '3kartalin' => '3x Kartalin - €80,00' ); $verzendingList = array( 'proefmonster' => 'N.v.t. bij proefmonster', 'dhl' => 'DHL (binnen 2 á 3 werkdagen) - €4,95', 'tnt' => 'TNT-Post (volgende werkdag) - €6,50' ); function createSelectOptions($optionList, $selectedValue=false) { foreach($optionList as $value=>$text) { $selected = ($value===$selectedValue) ? ' selected="selected"' : ''; echo "<option value=\"{$value}\"{$selected}>{$text}</option>\n"; } } function is_email($email) { $formatTest = '/^[\w!#$%&\'*+\-\/=?^`{|}~]+(\.[\w!#$%&\'*+\-\/=?^`{|}~]+)*@[a-z\d]([a-z\d-]{0,62}[a-z\d])?(\.[a-z\d]([a-z\d-]{0,62}[a-z\d])?)*\.[a-z]{2,6}$/i'; $lengthTest = '/^(.{1,64})@(.{4,255})$/'; return (preg_match($formatTest, $email) && preg_match($lengthTest, $email)); } //Create initial variables $naam = (isset($_POST['naam'])) ? trim($_POST['naam']) : ''; $achternaam = (isset($_POST['achternaam'])) ? trim($_POST['achternaam']) : ''; $email = (isset($_POST['email'])) ? trim($_POST['email']) : ''; $straat = (isset($_POST['straat'])) ? trim($_POST['straat']) : ''; $huisnummer = (isset($_POST['huisnummer'])) ? trim($_POST['huisnummer']) : ''; $postcode = (isset($_POST['postcode'])) ? trim($_POST['postcode']) : ''; $plaats = (isset($_POST['plaats'])) ? trim($_POST['plaats']) : ''; $telefoon = (isset($_POST['telefoon'])) ? trim($_POST['telefoon']) : ''; $product = (isset($_POST['product'])) ? trim($_POST['product']) : ''; $verzending = (isset($_POST['verzending'])) ? trim($_POST['verzending']) : ''; $opmerkingen = (isset($_POST['opmerkingen'])) ? trim($_POST['opmerkingen']) : ''; $errorText = ''; if(isset($_POST)) { //User submitted data - perform validation $errors = array(); if(empty($naam)) { $errors[] = "Name is required."; } if(empty($achternaam)) { $errors[] = "Achternaam is required."; } if(empty($email)) { $errors[] = "Email is required."; } else if(!is_email($email)) { $errors[] = "Email is not valid."; } if(count($errors)>0) { $errorText .= "<span style=\"color:#ff0000;\">"; $errorText .= "The following errors occured:<ul>\n"; foreach($errors as $errorMsg) { $errorText .= "<li>$errorMsg</li>"; } $errorText .= "</ul><span style=\"color:#ff0000;\">"; } else { //Form validation passed include page to process the data include('order.php'); exit(); } } ?> <html> </head></head> <body> <?php echo $errorText; ?> <form action="" method="post"> <table border="0"> <tr> <td align="right">Naam:</td> <td><input name="naam" size="25" type="text" value="<?php echo $naam; ?>" /></td> </tr> <tr> <td align="right">Achternaam:</td> <td><input name="achternaam" size="25" type="text" value="<?php echo $achternaam; ?>" /></td> </tr> <tr> <td align="right">Email:</td> <td><input name="email" size="25" type="text" value="<?php echo $email; ?>" /></td> </tr> <tr> <td align="right">Straat & huisnummer:</td> <td> <input name="straat" size="16" type="text" value="<?php echo $straat; ?>" /> <input name="huisnummer" size="4" type="text" value="<?php echo $huisnummer; ?>" /> </td> </tr> <tr> <td align="right">Postcode:</td> <td><input name="postcode" size="7" type="text" value="<?php echo $postcode; ?>" /></td> </tr> <tr> <td align="right">Plaats:</td> <td><input name="plaats" size="25" type="text" value="<?php echo $plaats; ?>" /></td> </tr> <tr> <td align="right">Telefoon:</td> <td><input name="telefoon" size="12" type="text" value="<?php echo $telefoon; ?>" /></td> </tr> <tr> <td align="right">Product:</td> <td><select name="product" size="4"> <?php createSelectOptions($productList, $product); ?> </select> </td> </tr> <tr> <td align="right">Verzenden:</td> <td><select name="verzending" size="1"> <?php createSelectOptions($verzendingList, $verzending); ?> </select> </td> </tr> <tr> <td align="right">Opmerkingen:</td> <td><textarea name="opmerkingen" rows="5" cols="29" value="<?php echo $opmerkingen; ?>"></textarea></td> </tr> <tr> <td></td> <td><input name="verzenden" value="Verzenden" type="submit"> <input type="reset" value="Opnieuw"></td> </tr> </table> </form> </body> </html>
  4. Seems like a lot of work when you could simply set the session timeout period to whatever value you wanted. Then just ckeck if there is an active session on each page load.
  5. Once you have all the data, why would you need to get them into an array? Just process the db results into the output you want. Here is some sample code. I made some assumptions on a copuple db fields $query = 'SELECT u.name FROM users as u JOIN groups as g ON u.Group_ID = g.id JOIN simulationgroups as sg ON sg.Group_ID = g.id WHERE sg.Simulation_ID = 5 AND g.kind_of_user NOT IN (1,2) ORDER BY g.id'; $result = mysql_query($query); $current_groupID = false; while($row = mysql_fetch_assoc($result)) { if($current_groupID != $row['Group_ID']) { $current_groupID = $row['Group_ID']; echo "<h2>{$current_groupID}</h2>\n"; } echo "{$row['name']}<br />\n"; }
  6. Seriously? I just rewrote that code (which originally worked for mm-dd-yyy) to work for dd-mm-yyyy as you asked. I don't have the time to review and update the code again, but I think all you need to do is change day = matchArray[1]; month = matchArray[3]; year = matchArray[5]; To month = matchArray[1]; day = matchArray[3]; year = matchArray[5]; And var dateObj = new Date(matchArray[4], matchArray[3]-1, matchArray[1], 12, 0, 0); To var dateObj = new Date(matchArray[4], matchArray[1]-1, matchArray[3], 12, 0, 0);
  7. md5() is more than adequate for hashing a password. Although you should use a salt just as you should for any hashing algorithm. The "flaw" in the md5() algorithm is around the ability to knowingly create a collision. FOr the purposes of a password (which is made up of a limited range of characters and from a specific list of characters) a collission would be nearly impossible. Even if it was possible the "hacker" would have to know the md5() hash which they were trying to duplicate. The purpose of hashing a password is in protecting the password. Creating a collision does not expose the password. Plus, to create a collision, the hacker would need access to the hashes (i.e. the database). But, then there is no purpose to tryng to create a collision since the hacker already has access to all the data anyway (except the passwords which are hashed). The threat is a user who gets a copy of your database and then tries to obtain users's actual passwords. That is why you use a salt so the user cannot simply use a rainbow table. That is also why you should never use a simple word as your password since malicious users will typically start with a dictionary attack.
  8. You should only be using ONE query with a JOIN statement between the two tables. Then you just need to order by group and the records will be automatically "grouped" by the group value.
  9. PHP is as secure as YOU make it. The answers to your questions could (nad have) fill entire books. Trying to answer them in a forum post cannot be done in an adequate manner. There are plenty of articles out there on different aspects of security (file locaitons, database, encryption, etc.). You will need to do research on each type of security to decide how best to approach it. however, if you have questions about a specific "piece" then by all means aska question here to get answers/opinions.
  10. Well, the code you have is flawed to begin with. For example: var years = Math.floor( diff / secPerYr ) That assumes that there are the same number of seconds per year. But, that is not the case with leap years and you would get inaccurate results. Here is a rewrite of what you had plus some code of mine modified for a date in the format you specified. I did some testing but not comprehensive <html><head><title>Datediff</title><script type='text/javascript'>//****************************************************************//// FUNCTION: isDate (dateStr) //// //// This function takes a string variable and verifies if it is a //// valid date or not. Dates must be in the format of dd-mm-yyyy //// or dd/mm/yyyy. It checks to make sure the month has the proper //// number of days, based on the month. The function returns true //// if a valid date, false if not. //// //// Day/Month must be 1 or 2 digits, Year must be 2 or 4 digits. ////****************************************************************//function isDate(dateStr){ var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/ var matchArray = dateStr.match(datePattern); //Check valid format if (matchArray == null) { return false; } day = matchArray[1]; month = matchArray[3]; year = matchArray[5]; // check month range if (month < 1 || month > 12) { return false; } //Check day range if (day < 1 || day > 31) { return false; } //Check months with 30 days if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; } //Check Feb days if (month == 2) { var leapYr = (year%4 == 0 && (year%100 != 0 || year%400 == 0)); if (day > 29 || (day==29 && !leapYr)) { return false; } } return true;}function getDateObj(dateStr){ var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/ var matchArray = dateStr.match(datePattern); var dateObj = new Date(matchArray[4], matchArray[3]-1, matchArray[1], 12, 0, 0); return dateObj;}//***************************************************************//// FUNCTION: dateDiff(Date1Obj, Date2Obj, [units], [precision]) //// //// Returns the difference between two date objects in the units //// specified (optional, default is days). The optional precision //// parameter determines the number of decimal places the result //// will be rounded to. Note: When the 'days' units is used and //// precision is 0, then output will be in calendar days. //// //// The units parameter includes the following: d=days (default), //// h = hours, m = minutes, s = seconds, ms = milliseconds ////***************************************************************//function dateDiff(date1Obj, date2Obj, units, precision){ //set the default untis var units = (units)?units:'d'; var calcPrecision = (precision)?Math.pow(10, precision) : 1; //Calculate the units divisor switch (units) { case 'ms': //Milliseconds var units = 1; break; case 's': //Seconds var units = 1000; break; case 'm': //Minutes var units = 1000 * 60; break; case 'h': //hours var units = 1000 * 60 * 60; break; case 'd': //Calendar Days default: var units = 1000 * 60 * 60 * 24; //Normalize time to 12:00am to count calendar days if precision = 0 if (precision==0) { date1Obj.setHours(0); date2Obj.setHours(0); } break; } //Convert dates to milliseconds var date1ms = date1Obj.getTime(); var date2ms = date2Obj.getTime(); //Calculate the difference in selected units var difference = (date2ms - date1ms) / units; //Convert to precision parameter difference = (Math.round(difference*calcPrecision))/calcPrecision; return difference;}function CalculateDiff(date1ID, date2ID){ var date1Val = getVal(date1ID); var date2Val = getVal(date2ID); if(!isDate(date1Val) || !isDate(date2Val)) { return false; } setVal('days', dateDiff(getDateObj(date1Val), getDateObj(date2Val))); return;}function field(id){ var ele = document.getElementById( id ); if ( !ele ) { alert( 'Element not found. id="' + id + '"' ); } return ele;}function setVal(id, val){ var ele = field(id); if (ele) { ele.innerHTML = val; }}function getVal(id){ var ele = field(id); var result = null if (ele) { result = ele.value; } return result;}</script></head><body><form name='' action=''> <br>Date 1 <input type='text' value='11/01/2006' id='date1'/> <br>Date 2 <input type='text' value='12/29/2007' id='date2'/><br> <input type='button' value='Calculate difference' onclick='CalculateDiff("date1","date2");'><br> Calculated Difference <table border='1'> <tr> <th>Days </th><td><textarea name='days' rows='1' cols='8' id='days'> </textarea></td> </tr> </table></form></body></html>
  11. You are taking the wrong approach. If a product and/or sub-product can belong to multiple categories then you should use an associative table to associate a product to one or many categories. If you duplicate products (for the same product) you are going to run into serious problems at some point. For example, if you need to manage inventory it would be very difficult if you are duplicating products. Here is a quick example of the DB structure (with only the relevant fields for identifying categories) Table: products - prod_id Table: categories - cat_id - cat_description Table: Prod_cat - prod_id - cat_id
  12. OK, I know that is only mock code, but there are some issues with it. 1. Declare the $my_array as gloabl before you start the loop. Having it in the loop causes unnecessary processing. 2. Do you actually use $my_array in second_function() at all? In the code above it serves no purpose to even use $my_array in that function.
  13. Your answer is in the manual. In other words, if you are using a PHP version prior to v5 then it is only using the first character. Looking at your logic though, are you really wanting to use strpos()? Or are you wanting to see if the $cat_id value is equal to $allcat?
  14. That will work fine as long as you want the comparisons to be case sensitive. i.e. "wood" != "Wood". If you need the comparison to be case insensitive you can do something similar to what you had before using strcasecmp() if(strcasecmp($q, 'the')==0 || strcasecmp($q, 'wood')==0 || strcasecmp($q, 'host')==0)
  15. I don't know that you can use global for a variable while at the same time setting a valule for it. It may work, not sure. If not just do it this way: global $my_array; $my_array = array[];
  16. To get the functions working as you apparently want them to, you can simply define $my_array as global in second_function().
  17. Your results make perfect sense. When you create "$my_array" in second_function() it is local to that function. Using global $my_array; in third_function() does not give you access to $my_array; from second_function(). In order to access a global variable the variable must first exist in the global scope, i.e. it has to be defined outside any functions. Example: $globalA = "A"; function createLocalVar() { $localB = "B"; } function outputVarsFromLocal() { global $globalA, $localB; echo "GlobalA: {$globalA}<br />\n"; echo "LocalB: {$localB}<br />\n"; $localB = "C"; } createLocalVar(); outputVarsFromLocal(); echo "LocalB (second time): {$localB}<br />\n"; Output GlobalA: A LocalB (first time): LocalB (second time): C The variable $localB was defined in a local scope so it cannot be accessed from the global scope (first time). However, by defining the variable as Global in the function, that variable is now also accessible in the global scope. So, we can modify the value in the function and access it while in the gloable scope (i.e. outside any functions).
  18. Try rephrasing your question, I don't understand what you are asking. If you don't want there to be line breaks in an element then just use the CSS property "white-space" with a value of "nowrap"
  19. I knew there had to be a function for doing that but couldn't find it.
  20. I stated previously that the regex code for a word boundry was "\b", but that you would need to add a second backslash to escape the first backslash. So.... If you need to escape another character (such as the ":" or ")") then the same logic would apply - wouldn't it? searchWord[0] = "\\:\\)"; I'm pretty sure you only need to escape the paren and not the colon, but it doesn't hurt to escape them both.
  21. Might I suggest an alternative solution that "may" fit your needs better? The values you specified in your example may just be "mock" data that is not representative of the values you are really using. But, at first I thought that the first list of values were "labels" and the second list were "values", but I'm not sure. At the very least you are creating a one-to-one relationship. In that case, a better approach may be to create a single dimension array where one list is used as the keys and the other list is used as the values: $final = array(); for($i=0, $count=min(count($path), count($location)); $i<$count; ++$i) { $final[$path[$i]] = $location[$i]; } Content of $final Array ( [base] => india [category] => USA [subcategory] => UK [item] => RUSSIA )
  22. Just to second what BlueSkyIS stated, you state you want to update the second select list dynamically. You should know that once a page is delivered to the browser PHP has no way of interacting with the page by itself. You either need to utilize JavaScript (which can initiate a PHP call) or you can have the user make a selection from the primary drop-down and manually submit the page. AJAX IS the solution you are looking for - you just don't know it.
  23. Hint:
  24. Not quite! That query would match ALL records in the table because it is using OR. Change the OR's to AND's to get the results you are looking for.
  25. Sorry for your loss, but I have to agree with CV. I'm also curious as to why you did have time to post a reply and ask an additional question about something that apparently wasn't important to you at the time. I really don't care about an answer, just thinking out loud. In any event, you have your solution and you've at least said "thank you" (which is more than many people do these days). So, I have all I need from this thread.
×
×
  • 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.