Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
What are the best security functions for registering?
Psycho replied to iStriide's topic in PHP Coding Help
To add to Nightslyr's comments, in your first post you made the statement There is no technical limitation to allowing such characters in a username. In fact, if you search the member list on this site you will see plenty of people with such characters in their usernames. As long as you are properly validating/escaping the data there is no risk. No matter if you allow the characters or don't allow the characters you still have to create code to handle either situation. So, it is really only a matter as to whether you feel it is appropriate for users to have usernames with such characters. Your two options are 1) Don't allow those characters, which means you need to generate code to either strip those characters out or reject the form submission when they do. Stripping out characters without the user's knowledge is typically a bad idea. But, even then you will want to escape the data before running it in a query. 2) Allow those characters. In that case you only need to escape the data. Of course, that only applies to string data. If any input is meant for numerical data you need to handle that by validating/enforcing int or float type values. -
You don't. What he is stating has nothing to do with what you want to accomplish. Can you give some details about the values that you want to hash/encrypt? If it is a relatively small finite list, then you could build a lookup list of the values and their hash values. But, if the list of possible values is large then you could use Mcrypt (http://php.net/manual/en/book.mcrypt.php). But, depending upon how "secure" this value needs to be you could also consider building yourself a simple ceasar cypher. It would be helpful to know how the value of "$random" is determined.
-
That quote is regarding using punctuation in the "base" url - in that case the file name. The OP's question is regarding parameters on the URL. Even Google uses the plus symbol for spaces in the search term. Do a google search for multiple words and check the URL that is generated when you click the search button. Granted there are a ton of parameters generated, but the parameter for "q" will show the search terms separated by a plus symbol. It is inadvisable to come up with your own logic for this. The plus symbol is the internet standard. If you ever wanted to pass information to another service or receive information from another service more work would be required to do so if you aren't following standard protocol.
-
Actually deleting the record or only marking it as deleted is about the same amount of work and is not necessary. In fact, logically (at least how I read this) the records shouldn't be deleted so much as they should "expire". And, even so, having a process to explicitly "expire" the records is unnecessary. By changing the SELECT queries you don't need any automated processes to delete/expire the records.
-
I think you are putting more work into this than you need to. There is already a function in PHP to convert a vaue into an URL acceptable value. urlencode(). You would then use the opposite command, urldecode() on the values passed through $_GET to convert them back to their original value. Using the urlencode() function, spaces are converted to plus signs. Other "special" characters are converted into appropriate codes.
-
You know, there really is no need to DELETE the rows to get what you want to accomplish. In fact, there are very good reasons NOT to delete the data (e.g. historical purposes). Instead of deleting the records, just set up your SELECT queries to only get the records that are less than 10 minutes old, for example SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE, `time`, NOW()) < 10
-
Fatal error call to undefined function imagecreatejpg()
Psycho replied to Techmate's topic in PHP Coding Help
From the manual: http://www.php.net/manual/en/function.imagecreatefromjpeg.php Check phpinfo() to verify jpg support is enabled and what version of GD you are using. -
What do you mean by it "it will not work"? You have to give us some information to go on. Are you getting errors, is it doing something differently than you expect? If so, what is it doing and what is it supposed to do. EDIT: This is probably your problem $run_gamerscore = mysql_fetch_array(mysql_query($find_gamerscore)) or trigger_error(mysql_error()); Runt he query first THEN fetch the results $result = mysql_query($find_gamerscore) or trigger_error(mysql_error()); $run_gamerscore = mysql_fetch_array($result) or trigger_error(mysql_error());
-
Fatal error call to undefined function imagecreatejpg()
Psycho replied to Techmate's topic in PHP Coding Help
Perhaps that is because there is no function called imagecreatejpg(). There is an imagecreate() and an imagecreatefromjpg() -
Assuming you are calculating the distance in PHP logic the solution is to order the results in PHP. Do a pre-processing of the data and dump the results into a multi-dimensional array. Then create a function to sort the array using usort() Example code: //Create and run query $query = "SELECT * FROM table_name"l $result = mysql_query($query); //Process the results into array $resultAry = array(); while($row = mysql_fetch_assoc($result)) { //calculate the distance // - insert code here to get distance //Put record + distance into array $resultAry = array_merge($row, array('distance'=>$distance)); } //function to custom sort the array function sortByDistance($a, $b) { if ($a['distance'] == $b['distance']) { return 0; } return ($a['distance'] < $b['distance']) ? -1 : 1; } //Sort the results array usort($resultAry, 'sortByDistance'); //Use foreach to iterate through the sorted array to output results foreach($resultAry as $record) { //Insert code to create HTML output }
-
Added logic to alternate between row1 and row2. Also cleaned up the code. Change the header cells from TD to TH (they will be bold automatically) echo "<table border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"100%\">"; if(!count($Post)) { print 'no records'; } else { echo "<tr class=\"rowhead\">\n"; echo " <th>Image</th>\n"; echo " <th>Title!</th>\n"; echo " <th>Type</th>\n"; echo " <th>State </th>\n"; echo " <th>City/Town</th>\n"; echo " <th>Posted</th>\n"; echo "</tr>\n"; $rowClass = ''; foreach($Post as $p) { $rowClass = ($rowClass!='row1') ? 'row1' : 'row2'; $link = "<a href=\"details.php?name={$Name}&ID={$p['id']}\">{$p['title']}</a>"; $state = str_replace('_', ' ', $p['state']); if(empty($p['image'])) { $image = 'no image'; else { $image = "<a href=\"{$p['image']}\"><img src=\"{$p['image']}\" width=\"50px\" height=\"50\" alt=\"{$image}\"/></a>"; } echo "<tr class=\"{$rowClass}\">\n"; echo " <td>{$image}</td>"; echo " <td>{$link}</td>"; echo " <td>{$p['adtype']}</td>\n"; echo " <td>{$state}</td>\n"; echo " <td>{$p['location']}</td>\n"; echo " <td>{$p['time']}</td>\n"; echo "</tr>\n"; } echo "</table>"; }
-
How to print nothing if doesn't exist in database
Psycho replied to iseriouslyneedhelp's topic in PHP Coding Help
Here's what I would do. This will make the address display correctly if any piece is missing <?php require("xxxx.php"); $ID = $_GET['ID']; $sql = "SELECT * FROM contacts ORDER BY firstname ASC"; $query = mysql_query($sql) or die ('Error: ' .mysql_error()); while ($row = mysql_fetch_array($query)) { $space = (!empty($row['firstname']) && !empty($row['lastname'])) ? ' ' : ''; $name = $row['firstname'].$space.$row['lastname']; $address = $row['address']; $address .= (!empty($row['suite'])) ? " Suite #{$row['suite']}" : ''; $address .= (!empty($row['zipcode'])) ? ", {$row['zipcode']}" : ''; ?> <tbody> <tr> <td><input type="checkbox" name="" id="" value="<?php echo $row['ID']; ?>"></td> <td><a href="/backend/contacts/editcontact.php?ID=<?php echo $row['ID']; ?>"><strong><?php echo $name; ?></strong></a></td> <td><?php echo $address; ?></td> </tr> </tbody> <?php } mysql_close(); ?> -
MySQL JOIN + OR to show my posts and my friends' posts?
Psycho replied to zac1987's topic in PHP Coding Help
You "hear" me, but you are not "listening" to me. I was only providing some examples of why it is a poor design to use the user ID as the foreign key. Just because the example doesn't apply to your particular situation doesn't make it a good solution. I have spent several years involved in the development of a multi-million dollar application. We have encountered numerous issues because of poor decisions related to database schema issues. For example, the software will support multiple customers using different accounts. So, all the data needs to be separated by account. There is a table to hold the basic account info: acct no, company name, etc. The table also contains a unique guid for each company. However, some teams used the account number as the foreign key reference instead of the unique guid since the account number will also be unique. There are two problems with that. 1) The account number can have a leading zero so it should be treated as a string. Otherwise you lose the leading zero. There have been numerous application errors when this has happened. 2) Initially all the account numbers would all be 6 digit numbers. But, now we need to support longer account numbers and/or characters. That is now becoming a very expensive project as there are numerous tables and queries that need to be modified. Had the unique guid been used as the foreign key then changing the allowed account numbers would have only required changing one field in one table and a handful of queries. However, you only want to rationalize your poor implementation. You state that using the user_id would be a redundancy. But, that is not what that statement is about. It is talking about removing the redundancies of "data". The user_id is not part of the data per se, the user_name is. You obviously didn't read the article I linked, so there is no use trying to go into details. But, one issue I didn't mention was performance. JOINing tables on a primary index will take much less time than the username. You would now need to index that column in all your tables which is a waste. From the linked document Additionally, MySQL does support foreign key constraints for InnoDB databases. That would only work by using the primary index from one table in another. There are tremendous benefits of that such as cascading updates and deletes. I.e. you delete a record and all references to that record in other tables are also deleted. And, lastly let's not forget storage size. An integer value will take much, much less space to store than even a short username. This isn't what you think. The list of allowed emails is enforced in the development environments to prevent applications emails from being sent to unintended users. We have a white list of domains and also the ability to add additional allowed email addresses. So, now we can test with live data without emails going to a customer. For example, if a customer has a bug we cannot reproduce we can copy their data to a dev environment and replicate the issue without affecting their production data and ensuring they don't get emails from the dev environment. It's your project. Do what you want. I only provided some constructive criticism for you to consider. -
MySQL JOIN + OR to show my posts and my friends' posts?
Psycho replied to zac1987's topic in PHP Coding Help
May I know why should save id of user instead of username? For me, it is easy to know who is the user by looking at his username in table in database, and it save 1 more step when I want to show the username, I don't need to query user table anymore since friend table has the username already. A forum post isn't really an appropriate place to teach you all the best practices for database design. I would suggest you read up on database normalization to start. But, I'll provide some details. When designing a database design, the goal is not to make the data easy to understand for someone looking directly into the database, the goal is to make sure it works efficiently. One of the main purpose (if not the only purpose) of having an auto-incrementing, unique id is to use that value as the foreign key in other tables. That value should typically never be exposed to the user and should never be changed. UserIDs, on the other hand, can be changed based upon the business requirements of the application. If you are using the UserID as the foreign key you could have many tables to "fix" in order for the user ID to be changed. But, even if your requirements are that the User ID can't be changed, doing a JOIN on an integer ID will be much, much more efficient than varchar fields. Now, I understand why you did what you did. It makes it easier to display records, such as the messages and who created the message, without having to do a JOIN. But, that is just being lazy. If there is a piece of "data" that should be associated with a record, that data should only be stored in one place. If I wanted to display a list of messages along with the user and the user's join date, I wouldn't add a column to the messages table to copy the user's join date into. The join date should be a field in the user table. I did a quick search and this seems to be a good, concise 1-page tutorial to give you some basic info: http://www.atlasindia.com/sql.htm I have tested it, it works! WOW. I never know IN can function like this, learn a good stuff from u, thanks. Yeah, it is unintuitive based on how we normally use the condition operators. It's usually the field followed by the values, such as: field = $somevalue. I actually stumbled upon doing it in reverse when I was trying to use a LIKE in reverse. I wanted to store values to be used in comparisons and have those values use replacement characters. The purpose was for restricting emails. I could either have an explicitly defined email that would be allowed, such as "me@here.com" or I could use wildcard characters such as "*@here.com". To make it work I had to use the LIKE condition in the opposite way as I normally would. SELECT * FROM allowed_emails WHERE $user_value LIKE email_field -
Or, if the variable check will be different throughout the page, create a function and pass it a string function varCheck($variable, $allowed) { return (in_array($variable, explode(',', $allowed))); } if(varCheck($variable_check['variable'], 'a,b,c')) { //code here }
-
You *should* ideally be using an associative table with individual records for each value. Alternatively you could use a binary value where each bit represents a 0 or 1. E.g. the number "13 is equivalent to the binary value of "01101" which would represent 5=false, 4=true, 3=true, 2=false, 1=true. This gives you the ability to query the records based upon certain values being set or not using bit-wise operators. However, if you really are determine to store multiple values as a single string, then you simply need to use implode. Replace all of this foreach($_POST['hear'] AS $heard){ $heard = $heard.'|'; if($heard == '5'){ $heard = $heard; } } //end foreach With just this $heard = implode('|', $_POST['hear']);
-
Never, ever run queries in a loop. 95% of the time there is a way to do the same thing with a single query. The other 5% of the time you are doing something you shouldn't be doing.
-
MySQL JOIN + OR to show my posts and my friends' posts?
Psycho replied to zac1987's topic in PHP Coding Help
Yeah, I forget the proper order and I just wrote that on-the-fly without testing it since I don't have your database. Sure. First of all you should have a unique ID for all the user records and use that as the foreign key reference in the other tables. I assume you have a user table, but I don't know if you have an id column in that table. If so, THAT is what you should use in the two tables above to reference the user - not the username. Also, I would not name the id fields as "id" since it becomes ambiguous as to which id is which when joining tables. Instead, I would name the fields "user_id", "message_id", "friend_id", etc. Then use that same name when using that id in another table. It then becomes intuitive as to the associations. Also, I think there is a way to simplify the query above a little bit, but not 100% sure it would work. Why don't you give this a try: SELECT p.message FROM messageslive p JOIN friendship f ON p.username IN (f.frenusername, f.username) WHERE '{$username1}' IN (p.username, f.username, f.frenusername) ORDER BY p.id DESC GROUP BY p.id LIMIT 0,16 -
MySQL JOIN + OR to show my posts and my friends' posts?
Psycho replied to zac1987's topic in PHP Coding Help
Your JOIN is backwards. You should be selecting on the message table and then JOIN the friends table. To be blunt, your database structure sucks. But, with what you have, this query shoudl work: SELECT p.message FROM messageslive p JOIN friendship f ON p.username = f.frenusername OR p.username = f.username WHERE p.username = '{$username1}' OR f.username = '{$username1}' OR f.frenusername = '{$username1}' ORDER BY p.id DESC GROUP BY p.id LIMIT 0,16 -
MySQL does not have a unix timestamp type field. It has "DATETIME", "DATE", and "TIMESTAMP" (which is not a unix timestamp). If you are simply storing a unix timestamp value from PHP into a numeric type field in MySQL you cannot group by dates without more work - if at all. It *may* be possible using MySQL's FROM_UNIXTIME, but I've never tried it and don't know if you can use MySQL's other data functions on top of that one. So, please be specific in the exact field type you are using to store the date value in MySQL.
-
I changed the variable name that the query is stored in from $q to $query, but didn't change the variable name in the mysql_query() function. As my sig states, I don't always test my code - especially when the code requires specific input or me having to create a db. NOTE: I also changed the name of the variable that I assigned the result of mysql_query(). It was $rw and I meant to change it to $result, but instead made it $esult. Although, since you have an "or die" clause on teh query call, there is really no point in assigning the result of an INSERT query to a variable.
-
This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=340553.0
-
What field type are you using for the date?
-
I'll start with a suggestion. Give your variables meaningful names. Names such as "$tmp", "$q", and "$newwx" tell me nothing about what the variable is for or what kind of value it holds. Second, add comments to your code. It may seem more efficient not to do those things but, believe me, it will save countless hours in the long run. In this case it makes it more difficult for us to help you as we have to read each line and interpret what it is doing to understand the next line. For this, the problem is that you are trying to do a shortcut my just adding the values without any validation. Always validate data before using it in your code - especially queries. Interestingly, I would think the array_filter() function would cause an error since you are only passing one parameter and it requires two. In the code below I have only provided a means to validate the "predft" value, but you shoudl do an appropriate validation of each piece of data to ensure it is the appropriate type using functions to convert to an appropriate numeric type or use mysql_real_escape_string() on string data. Also, you have separate fields for date, day and time. I expect you are storing those as string values. You should consider having a single datetime or timestamp field in the database and then use those three values from the input to generate an appropriate value. That will give you a lot more functionality when querying the data. include "connect.php"; if (!$con) { die('Could not connect: ' . mysql_error()); } function getFileAry($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $file = curl_exec($ch); curl_close($ch); return explode("\n", $file); } //Get the file as an array $fileAry = getFileAry("http://www.mysite.net/tides.txt"); //extract out only lines 12 - 249 $dataAry = array_slice($fileAry, 12, 249); //Process each line in the data array foreach($dataAry as $dataLine) { $dataAry = array_filter(explode(',', $dataLine), 'trim'); list($date, $day, $time, $predft, $predcm, $highlow) = $dataAry; //Validate each data for the type of value expected //Only providing a validation for $predft $predft = intval($predft); //Convert value to in integer $query = "INSERT INTO tides (`Date`, `Day`, `Time`, `Predft`, `Predcm`, `HighLow`) VALUES ('$date', '$day', '$time', '$predft', '$predcm', '$highlow')"; $esult = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error()); }
-
Question about Array/Other functions to compare data.
Psycho replied to Travis1128's topic in MySQL Help
"So far"? No confidence huh? You're welcome. I'm marking this as solved. Please do so in the future with the button at the bottom when your posts are solved.