PHP - Scanning General Text - User Inputs - For Bad Coding.
My current function for checking over user inputs is below, email and phone numbers work just fine.
I'm more worried about the insufficiency of text and textarea, this isn't being used live anywhere atm while i remake it and i'm out of ideas on how to scan general data. Fields passing through text, textarea might be full names, addresses, subjects basically general things. I've been stumbling on ideas of what would be best practice to do this. Any ideas? # $tbc = data to be cleaned # $type = email, phone, text, textarea function escape_data($tbc, $type='text') { switch($type) { case 'email': if(preg_match('/(\w+\.)*\w+@(\w+\.)*\w+(\w+\-\w+)*\.\w+/', $tbc)){ $op = $tbc; } else { $op = false; } break; case 'phone': if (!empty($tbc)) { preg_match_all('/[0-9\(\)+.\- ]/s', $tbc, $cleaned); foreach($cleaned[0] as $k=>$v) { $ready .= $v; } if ((strlen($ready) > 10) && (strlen($ready) <=25)) { $op = $ready; } else { $op = false; } } else { $op = false; } break; case 'text': case 'textarea': if (!empty($tbc)) { $op = strip_tags($tbc); } else { $op = false; } break; default: $op = false; } return $op; } Similar TutorialsSorry for the non code lingo, but I am wondering if I can pull a word from an array and use it to get a value from another array.
I am making a simple dodgeball game engine. I want the coaches strategy to pick a certain attribute to base who to throw to. Here is the team array:
//silverbacks I'm trying to learn how to code the proper way. There's a few things im worried about,but overall im worried about clogging up the server. so what should i keep in mind while coding, to avoid this? I'm thinking, keep insert and update to a minimum? as in, when possible, use session to keep track of data until i absolutly have to add that data to a database? is that a correct thought? what about once the data is in the database, how much trouble is it to ask for the selected data inside a database? should i be worried about overdoing request of data from databases? on the other hand, should i be worried about having too many sessions travelling around with a user. why? Im just asking to get a better feel for how to do things the proper way, i would hate to have a website built, only to find out that what i built is only a bat, that would bash the hell out of a server i wanted to put it on. Hi, I built this reg-login file. Note, login.php asks for your login details. The webform (so to speak) uses SELECT sql query to check your login credentials. The reg.php asks for your new acc details. The webform (so to speak) uses INSERT sql query to add your details to db. I got my webform not displayed to you either as registration form or login form. It is a neutral form. It justs asks you for your email. Then checks against db. If it exists, it assumes you existing member and login() function takes over and logs you in. Else, registration() functions takes over and registers you. Note:
On the login(), at the end when user is logged into his member account, his personal details get displayed on screen. if($row = mysqli_fetch_array($result_3,MYSQLI_ASSOC))
1. I want you to see if there any errors in my code that will result in malfunction or hacker sql injecting or hacking. 2. I need you to show me how to VALIDATE user input. VALIDATE email using 1). html5 & 2). php 7 email validation function plus 3.) with REGEX so nothing but email is inputted. Show me these 3 ways to check for email. I need you to show me how to VALIDATE user password. VALIDATE password using 1). html5 & 2). php 7 & 3.) with REGEX so nothing but password (A-Z, 0-9 ONLY) is inputted. And no other chars. Show me these 3 ways to check for password. From there, I should pick on fast from you and manage to VALIDATE username input.
I don't know how to do these above 2 so kindly teach me by showing snippet with comments so i understand your snippet. NOTE:
I did not complete the password prompt because I have forgotten how to do it with SHA256. Can someone show me a typical example how to query for password with SHA256 or whatever the latest strong algorithm is ? Show me code with comments so I understand what you doing with your code.
Thank You!
<?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'POST') { if(!isset($_POST['email_account']) || !isset($_POST['email_service'])) { $email_error = "<font color='red'>Input Email Address!</color>"; } else { //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME). $conn = mysqli_connect("localhost","root","","powerpage"); $conn->set_charset('utf8mb4'); //Always set Charset. if($conn === false) { die("ERROR: Connection Error!. " . mysqli_connect_error()); } else { //Set Parameters. $email = trim($_POST["email_account"]) . '@' . trim($_POST["email_service"]); $_SESSION['email'] = trim($_POST["email_account"]) . '@' . trim($_POST["email_service"]);//If this fails on test then replace it with above line echo "line 25 triggered: $email<br>"; $sql_query = "SELECT COUNT(personal_email) FROM users WHERE personal_email = ?"; $stmt = mysqli_prepare($conn,$sql_query); if($stmt == False) { //Close Connection. mysqli_close($conn); echo "Line 33<br>";//DELETE THIS die("<pre>Mysqli Prepare Failed!\n".mysqli_stmt_error($stmt)."\n$sql_query</pre>"); } else { mysqli_stmt_bind_param($stmt,'s',$email); if(!mysqli_stmt_execute($stmt)) { //Close Connection. mysqli_close($conn); die("Could not mysqli_stmt_execute! Please try again later!"); } $result = mysqli_stmt_get_result($stmt); if(mysqli_fetch_array($result, MYSQLI_NUM)[0])//WHY THIS NOT WORK UNLESS NUM ARRAY GIVEN ? { echo "Line 57 triggered: Function login() will trigger!<br>"; //DELETE THIS $_SESSION['session_type'] = 'login'; login(); } else { echo "Line 61 triggered: Function register() will trigger!<br>"; //DELETE THIS $_SESSION['session_type'] = 'register'; register(); } } } } } function register() { //if(!isset($_SESSION['session_type'] or $_SESSION['session_type'] != 'registration')//Nog Dog's copied & pasted line if(!isset($_SESSION['session_type']) || $_SESSION['session_type'] != 'register') { //Close Statement. mysqli_stmt_close($stmt); //Close Connection. mysqli_close($conn); die("Line 86: Could not check email! Please try again later!"); } //$email = trim($_POST["email_account"]) . '@' . trim($_POST["email_service"]); $email = $_SESSION['email'];//If this fails on test then replace it with above line //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME). $conn = mysqli_connect("localhost","root","","powerpage"); //Prepare an INSERT Statement. $sql_query_2 = "INSERT INTO users (personal_email) VALUES (?)"; if(!$stmt_2 = mysqli_prepare($conn,$sql_query_2)) { //Close Connection. mysqli_close($conn); die("Could not register! Please try again later!"); } else { //Bind Variables to the Prepared Statement as parameters. mysqli_stmt_bind_param($stmt_2,'s',$email); //Attempt to execute the Prepared Statement. if(!mysqli_stmt_execute($stmt_2)) { //Close Statement. mysqli_stmt_close($stmt_2); //Close Connection. mysqli_close($conn); die("Could not register! Please try again later!"); } mail(); } } function login() { if(!isset($_SESSION['session_type']) || $_SESSION['session_type'] != 'login') { //Close Statement. mysqli_stmt_close($stmt); //Close Connection. mysqli_close($conn); die("Could not check email! Please try again later!"); } //$email = trim($_POST["email_account"]) . '@' . trim($_POST["email_service"]); $email = $_SESSION['email'];//If this fails on test then replace it with above line //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME). $conn = mysqli_connect("localhost","root","","powerpage"); //Prepare a Select Statement. $sql_query_3 = "SELECT id,username,first_name,middle_name,surname,gender,age_range FROM users WHERE personal_email = ?"; if(!$stmt_3 = mysqli_prepare($conn,$sql_query_3)) { //Close Statement. mysqli_stmt_close($stmt_3); //Close Connection. mysqli_close($conn); die("Could not check email! Please try again later!"); } else { //Bind Variables to the Prepared Statement as parameters. mysqli_stmt_bind_param($stmt_3,'s',$email); //Attempt to execute the Prepared Statement. if(!mysqli_stmt_execute($stmt_3)) { //Close Statement. mysqli_stmt_close($stmt_3); //Close Connection. mysqli_close($conn); die("Could not check email! Please try again later!"); } //mysqli_stmt_bind_result($stmt,$email); $result_3 = mysqli_stmt_get_result($stmt_3); //if(mysqli_fetch_array($result_3, MYSQLI_NUM)) //Fetch result row as an associative array. Since the result set contains only one row, we don't need to use the 'While loop'. //mysqli_stmt_fetch($stmt);//use this if you use 'mysqli_stmt_bind_result($stmt,$email). if($row = mysqli_fetch_array($result_3,MYSQLI_ASSOC)) //Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of 'mysqli_stmt_bind_result($stmt,$email)'. { //Retrieve Values. $id = $row["id"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $username = $row["username"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $first_name = $row["first_name"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $middle_name = $row["middle_name"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $surname = $row["surname"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $gender = $row["gender"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; $age_range = $row["age_range"];//Use this if you use '$result = mysqli_stmt_get_result($stmt)' instead of //'mysqli_stmt_bind_result($stmt,$email_count)'; echo "Id: $id<br>"; echo "Username: $username<br>"; echo "First Name: $first_name<br>"; echo "Middle Name: $middle_name<br>"; echo "Surname: $surname<br>"; echo "Gender: $gender<br>"; echo "Age Range: $age_range<br>"; //Close Statement. mysqli_stmt_close($stmt_3); //Close Connection. mysqli_close($conn); } } } //DO NOT NEED TO REDO THE HTML CODE BELOW AS WAS NOT COPY & PASTE FROM ELESEWHERE .... ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta name="viewport" content="width=device=width, initial-scale=1"> </head> <body> <form action="" method="post"> <label for="email_account">Email:</label> <input type="text" name="email_account" id="email_first_part" placeholder="Email Address before '@'"> <label for="email_service"><b>@</b></label> <input type="text" name="email_service" id="email_last_part" placeholder="Email Address after '@'"> <?php if(!empty($email_error)){echo $email_error;}?> <br> <button type="submit" class="login_register" name="login_register">Register/Login</button> </body> <html> <?php ?>
Is there a way I can scan one of my websites for directories and files if it is not on the same server? I can scan just fine on the same server but not if it is on another server/website. since it is not the same server I tried to give the full path: http://www.site.com but it would not work. can this even be done? So I've been scanning forms with checkboxes the same way for years and I can't help but think there's a better way. Sometimes when testing, it get caught in infinite loops the way I do it because basically I'll have it like so: formpage.php Code: [Select] <form action=processform.php> a1 <input type=hidden name=id value='1'> <input type=checkbox name=a1> <br> a2 <input type=hidden name=id value='2'> <input type=checkbox name=a2> // etc etc for all checkboxes and then, <input type=hidden name=tracker value='-1000'> <input type=submit value='Submit'> </form> processform.php Code: [Select] while(current($_POST) != '-1000') { // do stuff with current($_POST) to check the id and the value of the $_POST after it and then call next($_POST) to go to the next line } The reason I do this is because if a user clicks the a1 box, there is a value in the $_POST['a1'], but all boxes that are not checked do not pass through a variable. There must be a better way to do this Hey guys i need to create a function that scans the whole website and gets the total used size for each extenssion inside an array to then be able to use it this way <?php echo 'Total space used for MP3 '.$scan[mp3][size].' bytes'; echo 'Total space used for JPG '.$scan[jpg][size].' bytes'; echo 'Total space used for PHP '.$scan[php][size].' bytes'; /// [...] ?> How is it possible, in PHP, to display an error message next to a form input text field if a user is attempting to submit a form with empty fields? Moreover, how is it possible to remove the same error message when the user fills in the input field with the required data and/or refreshes the page? I have 2 files that I am working with: application.php and process.php.
application.php mainly has the HTML of the form. I am very new to learning PHP (I started learning it last week) and I have been searching for hours for a clear answer. I have already tried different methods for generating the error message including: using empty(), !isset, $_POST["name"] = "", etc, and have tried using session_start();, $row, echo, print, and other variables to try and display error message on the page, and I have tried using unset();, and = null, to try and remove the error message once the input field has been filled but all to no avail. Either the method I try only half works, or nothing works, and I cannot pinpoint which is the part that is not working. I only have 2 files to work with, and as an example of what I want to do is:
1. If the first name field is empty when the user clicks submit, an error message should appear next to the input. Is this possible with PHP?
Hi all dear
<!DOCTYPE html> <html> <body> <?php function generatePermutation($string,$start,$end){ if($start == $end-1){ echo "$string - "; } else{ for($i = $start; $i < $end; $i++){ $temp = $string[$start]; $string[$start] = $string[$i]; $string[$i] = $temp; generatePermutation($string,$start+1,$end); $temp = $string[$start]; $string[$start] = $string[$i]; $string[$i] = $temp; } } } $str = "ABC"; $n = strlen($str); echo "All the permutations of the string a "; generatePermutation($str,0,$n); ?> </body> </html>
Code what i made so far.
$inputText = 'This is testing http://www.youtube.com'; $allowedDomains = 'www.google.com youtube.com/ http://www.test.org'; $array = preg_split('/[\s]+/', $allowedDomains); $regex = '';//Need this line if(preg_match($regex, $inputText)){ print 'Domain match!'; }else{ print 'Domain not match!'; } Edited by jacob21, 16 October 2014 - 08:31 AM. Hi to all the members of this great community, This is my first post here and I am new in PHP and in general web programming, my background is in C and C++ programming languages that's why I want to make some comments with regards to PHP and getting your feedbacks. In C++ one exercise considered that someone knows the basics of the language is to implement a general dynamic queue that is the client programmer can put an arbitrary number of objects into a queue and using templates you can instantiate different queues holding different kind of objects. I have grasped the most important parts of the language and I am pondering if you can effectively implement something like the above using PHP. I have googled this, and I have seen so far just a very simple implementation in PHP. He has defined his queue using an array having a fixed size and he just moved an index up and down through the array while inserting and poping elements from the queue. if you want to implement a dynamic queue the only way it comes to my mind just off the top of my head is to use the the construct [] to add dynamically element at the end of the queue and when you want to pop up an element you just have to unset(your current queue which is an array) create another array (smaller by one element than the previous one) copy the elements at the appropriate positions I just wanted, people with a C++ programming experience to give me some feedback about this topic and to give me some basic idea how could we implement a general queue in PHP. For example could we implement a queue w/o using an array? I would appreciate any comment. Greetings from Greece Hello,
I went through the forum, its geat but I think missing one feature,
There should be a forum about having general conversations and if someone wanted to talk about taking suggestions to help him/her across the world of programming, that would be very great.
Thanks.
Hi, I am really plugging into how to write functions in PHP. But I was going to delve into a user management program and try to create it, but dont want to be the older version of what I was before if you like, where I just type in for the sake of typing in code so I thought I would question what their doing. But a peice of code, a very small snippet, this came up: @mysql_connect What does this actually mean with the @ sign infront of the mysql_connect function? Seen this a few times but just never appreciated what the at sign means, any help is wonderfully appreciated of course. Thanks, Jeremy I have a general questions. 1. I have a list of products. 2. I have a list of each of the 50 states. 3. I have a list of "professions". I need to setup something called "State Verbiage". However, this is going to be on a per product, per state, per profession level. So each profession is mapped up to each state and product. So product #1, in State #4, for profession #2 would have verbiage. Any combination of the three would have different verbiage. Any advice on the easiest way to set this up, would be appreciated. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=321915.0 Hi there just wanted to ask you a general question regarding referenced variables and functions in PHP. I have this code: function theRefFunction(&$var){ $var = $var +1; return $var; } $a = 50; echo $thisvalue = theRefFunction($a); Just for learning purposes, as allot of times beginning PHP seriously developers who want to improve on memory consumption in PHP find this tricky, is there any point in using an example like this? I.e. would I really need the &$var as the parameter for the function called 'theRefFunction()'? Just wondered thats all, if not what would be a better way for really using it? It's just so I can go onto maybe doing a loop in it and setting it as a real example like working out tax and stuff like that, just for learning purposes, won't yet be using it. Just wanted to build up as I said earlier a library of things I have done and make maybe my own tutorial site. I look forward to any replies, Jeremy. I'm ready for the next step on my site, which is learning how to filter results down with a second search. The scenario is: A viewer searches for a plant by 4 variables to describe the leaf. After submit, they go to the results page, with 200 paginated results. (This is where I've gotten to) Now, on that same page, they choose to further narrow their results by searching those 200 results for plants that have purple flowers. Maybe they get 40 results and can use another variable to narrow further - and so on. What's the best way to set this up? I've been looking into temporary tables, but it seems to be a challenge because the table deletes the moment they leave that page or close the connection? Sessions seem like another possibility, but I read there's security issues. What's the best way to set this up? Just re-query the database with the entire set of variables from both the first and second searches? is it quicker to build some type of permanent table with a timestamp that I can use to delete it after the user has gone away? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=326040.0 i've been able to load up a csv file and display it as a html table but what i'm having trouble with is sorting it out with headings a to z but what i am trying to do is have 4 columns like this. Surgestions about how to do what im after i was hoping i could span the say A across all columns and centering them in the future also but thats not really the problem mainly the getting the array of the csv file and code right iguess. any help would be appreciated Code: [Select] <table> <tr> <th>A</th> </tr> <tr> <td>Apple1</td> <td>Apple2</td> <td>Apple3</td> <td>Apple4</td> <td>Apple5</td> <td>Apple6</td> </tr> <tr> <th>B</th> </tr> <td>Banana1</td> <td>Banana2</td> <td>Banana3</td> <td>Banana4</td> <td>Banana5</td> <td>Banana6</td> <tr> <th>C</th> </tr> <td>Cold1</td> <td>Cold2</td> <td>Cold3</td> <td>Cold4</td> <td>Cold5</td> <td>Cold6</td> </table> This is the code for inputting of the csv file i also have some other code i was wanting to use for the sorting of the array data from the csv file i'll past below.... Quote <?php $file = "widgets.csv"; $delimiter = ","; $enclosure = '"'; $column = array("", "", "", ""); @$fp = fopen($file, "r") or die("Could not open file for reading"); while (!feof($fp)) { $tmpstr = fgets($fp, 100); $line[] = preg_replace("/r/", "", $tmpstr); } for ($i=0; $i < count($line); $i++) { $line[$i] = explode($delimiter, $line[$i]); } ?> <html> <head> <title>Albert's Delimited Text to HTML Table Converter</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="1" cellpadding="5" cellspacing="0"> <tr> <?php for ($i=0; $i<count($column); $i++) echo "<th>".$column[$i]."</th>"; ?> </tr> <?php for ($i=0; $i < count($line); $i++) { echo "<tr>"; for ($j=0; $j < count($line[$i]); $j++) { echo "<td>".$line[$i][$j]."</td>"; } echo "</tr>"; } fclose($fp); ?> </table> </body> </html> Heres the code for the sorting of the table data from the array Quote <?php echo "QUERY_STRING is ".$_SERVER['QUERY_STRING']."<p>"; $rev=1; $sortby=0; if(isset($_GET['sortby']))$sortby = $_GET['sortby']; if(isset($_GET['rev']))$rev = $_GET['rev']; //Open and read CSV file example has four columns $i=-1; $ff=fopen('widgets2.csv','r') or die("Can't open file"); while(!feof($ff)){ $i++; $Data[$i]=fgetcsv($ff,1024); } //Make columns sortable for each sortable column foreach ($Data as $key => $row) { $One[$key] = $row[0]; // could be $row['Colname'] $Two[$key] = $row[1]; //numeric example $Three[$key] = $row[2]; $Four[$key] = $row[3];} //numeric example //Case Statements for Sorting switch ($sortby){ case "0": if($rev=="1")array_multisort($One, SORT_NUMERIC, $Data); //SORT_NUMERIC optional else array_multisort($One, SORT_NUMERIC, SORT_DESC,$Data); $rev=$rev*-1; break; case "1": if($rev=="1")array_multisort($Two, $Data); else array_multisort($Two, SORT_DESC, $Data); $rev=$rev*-1; break; case "2": if($rev=="1")array_multisort($Three, SORT_NUMERIC, $Data); else array_multisort($Three, SORT_NUMERIC, SORT_DESC,$Data); $rev=$rev*-1; break; case "3": if($rev=="1")array_multisort($Four, $Data); else array_multisort($Four, SORT_DESC, $Data); $rev=$rev*-1; break;} echo ("<table border=2>"); //$rev is reverse variable echo ("<th><a href=\"SortTable.php?sortby=0&rev=$rev\" title=\"Click to Sort/Reverse sort\">One</a></th>"); echo ("<th><a href=\"SortTable.php?sortby=1&rev=$rev\" title=\"Click to Sort/Reverse sort\">Two</a></th>"); echo ("<th><a href=\"SortTable.php?sortby=2&rev=$rev\" title=\"Click to Sort/Reverse sort\">Three</a></th>"); echo ("<th><a href=\"SortTable.php?sortby=3&rev=$rev\" title=\"Click to Sort/Reverse sort\">Four</a></th>"); $i=0; foreach($Data as $NewDat){ if($NewDat[0]!=""){ //error trap $str="<tr>"; foreach($NewDat as $field)$str.="<td>$field</td>"; $str.="</td>\n"; echo $str;}} fclose($ff); echo "</table>"; Hi I am currently mostly learning procedural PHP but had a question about security.
Are hackers able to see connections to databases in procedural programming? Would connections to databases need to be called from classes and methods instead? Or does it not matter that much? I have set up a site for a local orchestra. I have a simple mysql db from which 'News' items are pulled using php. I have set up the following pages: 1. view_news.php 2. insert_news_item.php 3. delete_news_item.php 4. edit_news_item.php All pages are working fine. Now, rather than continually having to do news updates for the orchestra myself, I want to give a person on the orchestra committee access to the above pages so that he/she can do news updates for the orchestra, as required. What is the best way of proceeding from here? I thought about creating a password protected directory and putting pages 2, 3 and 4 above into that directory and then giving the committee member the protected directory password. Is that the way to go? What is the conventional way of doing this sort of thing? Two things to note: I'm new to php and the job is non-paying. I've set up the site as the willing parent of kids in the orchestra. Any advice will be much appreciated. |