PHP - Safely Outputting Fields
On my website, I have Sticky Forms that use the following style code...
<input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlspecialchars($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> Do I need to use htmlspecialchars($firstName, ENT_QUOTES); anytime I output data to the screen?? For example, in this code do I need to wrap $username?? echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . $username . '</strong> </a>'; Debbie Similar TutorialsI built a basic form with certain fields required. When a required field isn't filled, the errors are echoed but not in the best area. I'd like for each error message to be displayed underneath their respected input fields. What do I need to look into? <?php if(!empty($_POST['submit'])) { // set variables $name = mysql_real_escape_string($_POST['name']); $email = mysql_real_escape_string($_POST['email']); $email2 = mysql_real_escape_string($_POST['email2']); $age = mysql_real_escape_string($_POST['age']); $city = mysql_real_escape_string($_POST['city']); $state = mysql_real_escape_string($_POST['state']); // 1A. REQUIRED FIELDS VERIFICATION if(!empty($name) && !empty($email) && !empty($email2) && !empty($city) && !empty($state)) { // 1B. END REQUIRED FIELDS VERIFICATION } else { echo '<img src="images/icon_error.png" alt="" title="" /> Please fill out the required fields.<br />'; if (empty($name)) { echo 'Whats your name?!<br />'; } if (empty($email)) { echo 'No email given.<br />'; } if (empty($email2)) { echo 'Please verify your email<br />'; } if (empty($city)) { echo 'What city are you from?<br />'; } if (empty($state)) { echo 'What State!<br />'; } echo '<br /><br />'; } // 1B. END REQUIRED FIELDS ERROR CODES } ?> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <div class="formSec"><label for="name" class="required">Full Name:</label> <input type="text" name="name" id="name" value="" /></div> <div class="formSec"><label for="email" class="required">Email:</label> <input type="text" name="email" id="email" value="" /></div> <div class="formSec"><label for="email2" class="required">Confirm Email:</label> <input type="text" name="email2" id="email2" value="" /></div> <div class="formSec"><label for="age" class="required">Age:</label> <input type="text" name="age" id="age" value="" /></div> <div class="formSec"><label for="city" class="required">City:</label> <input type="text" name="city" id="city" value="" /></div> <input class="submit" type="submit" name="submit" value="Submit" /> </form> I just finished adding the ability to add Comments after Articles on my website. Now it would be nice if people could Quote other Posts/Comments juts like you can do here on PHPFreaks. The problem is that I have this code to eliminate any security issues with HTML... echo ' <div class="userPost"> <span class="commentDate">Posted on: ' . date('Y-m-d g:ia', strtotime($createdOn)) . '</span> <span class="commentNo">#' . $commentCount . '</span> <p>' . nl2br(htmlentities($comments, ENT_QUOTES)) . '</p> </div>'; Any suggestions to have it both ways? Thanks, Debbie What do I need to do to *safely* capture and store User Passwords in a Registration Form? There was a thread that I started a few months ago where someone had given a really good response talking about "Salt" and so on, but for the life of me I cannot find that info. Nonetheless, I need some help getting my head back into this topic! My Registration Form is complete, and the last thing I need to do is make sure Users enter a "Strong Password" and then I need to store that somewhere, somehow, in the most *secure* manner possible... Thanks, Debbie I produce a series of php variables in a php strict (mostly come from mysql), and I want to save them as a php file. To be use for "include". What is the safest way to write them in a php file? I tried to save them in the manner of saving a text file with fwrite as Code: [Select] $data='<?php $cat=array('array created in the text'); $string='some value';?>'; $fh = fopen("file.php", 'w'); fwrite($fh, $data); Now, file.php is a normal php file and I can call it with "include"; but the problem is that this method is not safe. For example, if the string is "There's something", php gives error for the presence of ' in the string. I can skip ' and " by backslash; but this method is costy, as I need to perform this process for all strings to be saved. Moreover, there might be other source of errors too (that I have not encountered yet). Is there a safe way for writing a php code to file? What is the latest and greatest way to hash data in PHP? Hey guys,
Thank you in advance... here is my situation, I have a form with three (3) fields in it, the 'student name' is unlimited textfield with an "add more" button to it and I have two select fields ('number of shirts' and 'trophies') that depend on the number of entries for 'student name'...
I want to create the select fields based on this math, for as many 'student name' entries:
1- i want to have the select form for 'number of shirts' to be 0 up to that number... so if there are 6 'student name' entries, the select options will be 0,1,3,4,5,6,7
2- I want to have the select form for 'trophies' to be 5 'student name' entries to 1 'trophies', for example if there are 6 'student name' entries, the select options will be 0,1... if there are 13 entries, options will be 0,1,2... So if there are less than 5 'student name' entries, the select field will not show (hidden)
of course if there are no 'student name' entries, these two fields won't show up (hidden)
let me know if that make sense and ANY help or directions will be GREATLY APPRECIATED.
Thanks guys!
Hello, I'm trying to echo an additional variable using this: $numincorrect = '<div id="incorrectnum">Sorry, that number was not correct.</div>'; I want to incorperate: $code from require('send.php'); I've tried $numincorrect = '<div id="incorrectnum">Sorry, that number was not "$code".</div>'; However, it literally displays $code on output. Many thanks I have mysql table with Type, Month, Date, and Quantity. I am doing query, and writing to xml which will pass to chart. My error is coming because for each <row> I need to have same number of child tags. For instance, if there are six months represented in first row (<header>), I need to have six <number> tags in all the following rows, even when there may not be any Quantity for that particular month in mysql table. Right now, if a particular Type in my table doesn't show quantity for some months, than I end up with fewer <number> tags. My php is here, and xml structure below: Code: [Select] //start the XML output print "<chart>"; print "<chart_data>"; //output the first row that contains the years print "<row>"; print "<null></null>"; $category = mysql_query ("SELECT prMonth FROM table1 GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($category); $column++ ) { print "<header>".mysql_result ( $category, $column, "prMonth")."</header>"; } print "</row>"; //output row 2 to 4. Each row contains a type name and its data (Qty, Prem, Comm ...) $series = mysql_query ("SELECT prType FROM table1 GROUP BY prType ORDER BY prType"); for ( $row=0; $row < mysql_num_rows($series); $row++ ) { print "<row>"; $type = mysql_result ( $series, $row, "prType"); print "<string>$type</string>"; $data = mysql_query ("SELECT SUM(prQty) FROM table1 WHERE prType='$type' GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($data); $column++ ) { // Need to do something here to // get number tags to show zero // when there's no data for that // month print "<number>".mysql_result($data,$column)."</number>"; } print "</row>"; } //finish the XML output print "</chart_data>"; print "</chart>"; XML structu Code: [Select] <chart> <chart_data> <row> ----this row will be the head row---- </null> <header>Month name</header> <header>Month name</header> ... </row> <row> ----this row will start body rows---- <string>Type name</string> <number>total quantity for month, for this type</number> <number>total quantity for month, for this type</number> ... </row> ... </chart_data> </chart> I'm doing the following query where "ctext" comes from the clues table and "answerid" and "atext" come from the answers table... Code: [Select] $sql = "SELECT * from clues, answers WHERE clues.quizid = '{$_GET['quizid']}' AND answers.quizid = '{$_GET['quizid']}'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($info=mysql_fetch_array($result)) { echo "<tr><td>" . $info['answerid'] . "</td>"; echo "<td>".$info['ctext']."</td>"; echo "<td>".$info['atext']."</td>"; } echo "</tr>"; } } But when this displays in the browser, it's outputting each result set twice and kinda mixed up. For example, it looks like this... 1 monkey funny 1 cat funny 2 monkey boring 2 cat boring But I want (i.e. was expecting) it to display as... 1 monkey funny 2 cat boring Can anyone tell me why it's showing TWO rows for each and seemingly mixing up the returned results? Ultimate question is this. Do I have to break apart the mysql queries in order to get PHP to display the results how I want? I gotta think there is a way to do just one query and do what I want, but I obviously can't figure it out Hi there i have a basic query that is simply not outputting, i just dont get it. Im pretty sure the query is sound. If you can spot anything wrong here please let me know. Code: [Select] $colname_RecordSet1 = "-1"; if (isset($_SERVER['MM_Username'])) { $colname_RecordSet1 = (get_magic_quotes_gpc()) ? $_SERVER['MM_Username'] : addslashes($_SERVER['MM_Username']); } mysql_select_db($database_swb, $swb); $query_resultp = sprintf("SELECT PlayerName, PlanetName, Class1, Class2, Class3, Class4 FROM planet WHERE PlayerName = %s", GetSQLValueString($colname_RecordSet1, "text")); $resultp = mysql_query($query_resultp, $swb) or die(mysql_error()); $row_resultp = mysql_fetch_assoc($resultp); $totalRows_resultp = mysql_num_rows($resultp); <?php do { echo 'Class: '; echo $row_resultp['PlanetName']; echo $row_resultp['Class1']; echo $row_resultp['Class2']; echo $row_resultp['Class3']; echo $row_resultp['Class4']; ?> <?php } while ($row_resultp = mysql_fetch_assoc($resultp)); mysql_free_result($resultp); ?> Thanks At the moment I have multiple pages with different HTML tables coded in (some have 5 columns and some 6 etc) and PHP echoing out data to populate from the database. The table in each page holds different data. It looks messy to me to code a different table for every page so I'm wondering if it's possible to create a function to do this? The function would have to print tables with different amounts of columns and echo out different data depending on what the page is along with table headers etc. How would I go about that? Hi
I have a self calling script which does the following:
Stage 1: First run, it detects that $_POST is empty, and so displays a chunk of html which prompts for a password.
Stage 2: When resubmitted, it detects $_POST and displays another chunk of html which prompts the user for some values
Stage 3; When resubmitted the second time, $_POST is detected, along with the user values and some php is executed and a menu displayed.
So, question is this, what is the best method to output the html at stage 1 and stage 2?
I have tried using echo statements and wrapping each chunk in a function = messy.
I have tried using HEREDOCS (<<<VARNAME), better but ties my HTML to my script which is a pain
I am thinking to use file_get_contents("../html/chunk1.htm") this seems quite elegant and allows me to get someone else on our team to design the HTML keeping it out of my script
Thoughts and suggestions?
Thanks as ever
p.s. who pays for this site, are donation accepted?
Hello guys. I am facing a little problem on my website when I am trying to output the data from the database in the form of a table. If you go to http://sigmalogistix.com/track-trace/ and enter any on of the following B/L No's: 123456789 987651234 543216789 You can see that the table is being created but the data is not being shown to the user. If I switch back to the old code in which there was no table, then the data is being shown to the user upon entering the B/L No. Please help me guys. Attached below are the codes which I have inside the function.inc.php file and the index.php file. function.inc.php Code: [Select] <?php include 'db.inc.php'; function search_results($keywords) { $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword){ $where .= "`keywords` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; } } $results = "SELECT `Bill_No`, `Origin_City`, `Origin_Country`, `Destination_City`, `Destination_Country`, `Status`, `Current_Location` FROM `billoflading` WHERE $where"; $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0; if ($results_num === 0) { return false; } else { while ($results_row = mysql_fetch_assoc($results)) { $returned_results[] = array ( 'Bill_No' => $results_row['Bill_No'], 'Origin_City' => $results_row['Origin_City'], 'Origin_Country' => $results_row['Origin_Country'], 'Destination_City' => $results_row['Destination_City'], 'Destination_Country' => $results_row['Destination_Country'], 'Status' => $results_row['Status'], 'Current_Location' => $results_row['Current_Location'] ); } return $returned_results; } } ?> index.php Code: [Select] <?php include 'func.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>search</title> </head> <body> <form action="" method="POST"> <p> <input type="text" name="keywords" size="17" maxlength="9" value="Enter B/L No." onfocus="if(this.value == 'Enter B/L No.'){this.value = '';}" /> <input type="submit" class="formbutton" value="Track" /> </p> </form> <?php if (isset($_POST['keywords'])) { $suffix = ""; $keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords']))); $errors = array(); if (empty($keywords)) { $errors[] = ''; } else if (strlen($keywords)<9) { $errors[] = '<br><strong>Your Bill of Lading Number must contain 9-digits.</strong>'; } else if (search_results($keywords) === false) { $errors[] = '<br><strong>Please enter a valid Bill of Lading Number.</strong>'; } if (empty($errors)) { $results = search_results($keywords); $results_num = count($results); $suffix = ($results_num !=1) ? 's' : ''; foreach($results as $result) { echo '<br><table> <thead> <tr> <th><strong>B/L No.</strong></th> <th><strong>Origin City</strong></th> <th><strong>Origin Country</strong></th> <th><strong>Destination City</strong></th> <th><strong>Destination Country</strong></th> <th><strong>Status</strong></th> <th><strong>Current Location</strong></th> </tr> </thead> <tbody> <?php while ($row = mysql_fetch_assoc($results) { ?> <tr> <td><?php echo $row["Bill_No"]; ?></td> <td><?php echo $row["Origin_City"]; ?></td> <td><?php echo $row["Origin_Country"]; ?></td> <td><?php echo $row["Destination_City"]; ?></td> <td><?php echo $row["Destination_Country"]; ?></td> <td><?php echo $row["Status"]; ?></td> <td><?php echo $row["Current_Location"]; ?></td> </tr> <?php } ?> </tbody> </table>'; } } else { foreach($errors as $error) { echo $error, '</br>'; } } } ?> </body> </html> The code below is in a PHP file, but is really HTML with nested PHP. <img src="<?php echo WEB_ROOT; ?>images/BeachSunset.jpg" width="200" alt="Pictu Beach Sunset." title="Pictu Beach Sunset." /> I want to put it in a MySQL record and output it using PHP. So how do I re-write this code so that it can be displayed with the same end effect using a PHP Echo statement?? (I seem to be having trouble figuring things out with MySQL in the way?! Thanks, Debbie What is the proper way to output the contents of a class? (We will assume that Getters and Setters are evil...) Let's say I have the following class... class FormHandler2 { // Define Variables. private $myFormArray; // Constructor. public function __construct($param){ $this->myFormArray = $param; } } ...and I want to be able to output its contents either via a variable dump OR by printing something to the screen. How would I do that? TomTees This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=320494.0 Hi guys, I am very simply inserting text into a table with php and mysql, and outputting it, it all works fine but when I use paragraphs when inserting it, and then try to ouput it, all the paragraphs are gone and it looks like one big block of text, I suppose the way to go around this is to use <br> instead of just enters as it probably doesnt read this, but is it possible to make this text area do read and insert <br>'s where people use enter to make paragraphs? Much help appreciated, I realize this must be a very beginner question but I am not really sure how to word this so I wasn't sure on specific search on this. I have converted xml into an array with no problems, however I'm having difficulty outputting the various attributes. Here is a sample: Code: [Select] [0] => Array ( [@attributes] => Array ( [YourId] => 1082-1 [Name] => Woodwards Metals [Description] => ) ) The bit that is confusing me is the @attributes part. How would I output the 'Name' element for example? Hello guys i am doing a search function whereby users can check whether a setting is Pass or Fail. After user press the search button, it will return the file which contain the settings the user wants. However i have encountered a problem, currently i am using if statement and && operator to search for file so if the file is missing a string whereby the preg_match function couldn't find it, it will not output the file if i check another setting. Hence i am interested on what other options can i use. Also, Is it possible to use while loop? I tried for awhile and my browser just keeps loading and loading. Thanks for the help! Example: I want to check File 1 for Maximum Password Age settings but it does not contain Service Pack Requirement string... if ((preg_match("/\bService Pack Requirement:(.*)./", $allFiles)) && (preg_match("/\bMaximum Password Age Requirement:(.*)./", $allFiles)) && (preg_match("/\bMinimum Password Length:(.*)./", $allFiles)) && (preg_match("/\bAudit Account Logon Events:(.*)./", $allFiles)) { echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />"; } Hi All, I'm working on an X-Cart site. Looking through the pages, any page with an apostrophe in the content is being loaded as an � instead. The sites' char set is UTF-8. Changing it to ISO then creates an issue in itself with bulleted lists. Just wondering if anyone has had the problem in the past and if they have solved it? Any help appreciated. Cheers |