Separating php form values - php

I have a form and on submit, it goes to submit.php.
The input text looks like this:
<input name="hpno[1]" type="text" maxlength="3" size="3" /> - <input name="hpno[2]" type="text" maxlength="8" size="13" />
I need to store the data as per this format (010) 5839539.
Tried putting this in the submit.php
$hpno = implode('-', $_POST['hpno']); but this gives the output 010-5839539.
Any help would be much appreciated.

$(hpno) = '(' . implode(') ', $_POST['hpno']); ?
Sorry, rusty with my PHP. Let me know what that puts out, especially if it's just an error.

If you want it to be in the format (xxx) xxxxxxx, you'll have to do something like this:
$hpno = '('.$_POST["hpno[1]"].') '.$_POST["hpno[2]"];
You mentioned that you would be storing the data, so be careful if you're storing this in a database, you're clearly vulnerable to an injection attack this way.

You could help to prevent an SQL injection like this:
$hpno = mysql_real_escape_string("(" . $_POST['hpno[1]'] . ") " . $_POST['hpno[2]']);
This will give you the formatting you need and scrub the input (though it's not perfect, or bullet-proof).

Related

PHP /MySQL update form from within results

I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)

How to escape MS-SQL output in html/php?

Sounds very simple, but I'm kinda confused at the moment.
I have this DB object which includes some values that I want to output in an html form.
Simplified Problem:
$result is my db object and this is the html input where I want to output some text which can include double or single quotes.
<input class="someclass" name="desc" id="descID" type="text" value="<?=$result['desc'];?>" placeholder="<Description>" />
So if $result['desc'] contains text like this: 'Did you hear about "foobar"?'
everything after the first double quote gets cut off and ends up like this: 'Did you hear about '.
What i have tried already without success:
htmlspecialchars like this value="<?=htmlspecialchars($result['desc']);?>" or like this value="<?=htmlspecialchars($result['desc'], ENT_QUOTES);?>"
addslashes
Note: My DB(mssql) saves the string properly. Only have the problems in my html.
I would be glad if you could help me out here. Thanks.
Thanks for the help so far, but i managed to find a solution to this:
<?$descEscaped = str_replace('"', '"', $result['desc']);?>
<input class="someclass" name="desc" id="descID" type="text" value="<?= htmlspecialchars($descEscaped);?>" />
htmlspecialchars replaces quotes with """.
I am using my simple function htmlliteral:
function htmlliteral($s){
return '"'.htmlspecialchars($s).'"';
}
With this function you can use:
$descEscaped = htmlliteral($result['desc']);
print "<input class=someclass name=desc id=descID type=text value=$descEscaped />";

Can I safely output data to the user using this sanitize

So im trying to work out the best way to sanitize xss for safe output to the user.
More or less, when storing values from a form, im using strip_tags(); then bind_params();
And when Im about to output the data to the user Im also using htmlentities();
The data will only be shown inside <p> and <a> tags.
eg:
<p> Some data from user </p>
<a href=""> Some data from user </p>
Should this work?
Index.php
<form action="sante.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
And then sante.php
<?php
$name = $_POST["fname"];
$age = $_POST["age"];
$namn = strip_tags($name); // then storing into mysql with bind_param
$older = strip_tags($age); // then storing into mysql with bind_param
// before output, htmlentities
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return $value;
}
// Now showing values
echo safe($namn). "<br>";
echo "<p>" .safe($older) . "</p>";
?>
Yes, you can use this code safely. I see you're already using bind_param (and I assume either the mysqli or PDO library), which prevents SQL injection (damage to you), and htmlentities, which prevents cross-site scripting (damage to the user).
You don't even need to call strip_tags before writing to the database, although it's a fine idea if you don't want user input to contain any JS/PHP/HTML tags at all (and also if you forget to call your safe function on output).
When you insert data to database you must use mysql_real_escape_string or use PDO,
if you display data you must use htmlspecialchars

PHP: Form variables not registering

I have an HTML form for a limo company's info, kind of like this:
<td>
<input type="text" name="sedan-number-fleet" />
</td>
<td>
<input type="text" name="sedan-year-range" />
</td>
and so on. When I put them into PHP, like so:
$input_sedan_number_fleet = strip_tags($POST['sedan-number-fleet']);
$input_sedan_year_range = strip_tags($POST['sedan-year-range']);
it comes out with no result when I try to echo it. Does it have to do with the strip_tags function? If you know, let me know. That would be great! Thanks!
You don't access form-submitted data through $POST, but $_POST. Change your code to
$input_sedan_number_fleet = strip_tags($_POST['sedan-number-fleet']);
$input_sedan_year_range = strip_tags($_POST['sedan-year-range']);
And also, I hope you do more input validation than just strip_tags.
replace $POST with $_POST. This should do the job. Additionally, use $_GET instead of $GET and so on (read more here)
I was having trouble with this too. Try using " instead of '.
For example:
$input_sedan_number_fleet = strip_tags($_POST["sedan-number-fleet"]);
$input_sedan_year_range = strip_tags($_POST["sedan-year-range"]);
For some reason that worked for me.

Single quotes and addslashes in php forms (option value escaping on space?)

I cannot get my addslashes function and html option value to play nice together. My initial problem was the single quote in the option but by solving that I seem to have created another issue whereby $titleunit_name only comes through with the first word.
This is what I want to come out:
baroffice=O'Fallon & Highway K&N
titleunit_name=O'Fallon & Highway K&N
cleantitleunit_name=O\'Fallon & Highway K&N
This is what I get:
baroffice=O'Fallon
titleunit_name=O'Fallon & Highway K&N
cleantitleunit_name=O\'Fallon & Highway K&N
I don't know if it matters but the values are normally coming from and being sent back to ms sql.
<form method="post" action="formtest.php?" id="searchform" target="" autocomplete="off">
<div id="office">
<font style="font-size:12px; font-weight:bold;" color="#002EB8" face="Verdana">
Closing Office:</font>
<select name="baroffice" style="width:90px">
<?php
$titleunit_name= "O'Fallon & Highway K&N";
$cleantitleunit_name=addslashes("$titleunit_name");
echo "<option value=$cleantitleunit_name name= '$titleunit_name'>";
echo "$titleunit_name</option>";
?>
</select></div><br>
<br><Br>
<input type="submit" name="submit" value="submit" style="position:relative;z-index:3">
<br><Br>
</form>
<?php
$baroffice = str_replace("\'","'",($_POST['baroffice']));
if (isset($_POST['submit']))
{
echo "baroffice=$baroffice<br>";
echo "titleunit_name=$titleunit_name<br>";
echo "cleantitleunit_name=$cleantitleunit_name<br>";
}
else
{echo "";
};
?>
Thanks for any help in advance.
First of all, you don't need double quotes around variables. Just $titleunit_name is correct, not "$titleunit_name".
Second, never use addslashes. If you're escaping content to go into MySQL use the more robust mysql_real_escape_string function. addslashes misses cases and leaves your script every bit as open to attack as if you hadn't used it at all.
And finally, slashes do not belong in HTML output. You're looking for the htmlspecialchars function, which prepares a string to be written into an HTML document.
echo '<option value="' . htmlspecialchars($titleunit_name) . '" name="' . htmlspecialchars($titleunit_name) . '">' . htmlspecialchars($titleunit_name) . '</option>';
Note that all uses of $titleunit_name (or any other variable) must be escaped in this way before writing them out to the page.
Now, I'm guessing from context that you have "magic quotes" turned out, so PHP is automatically performing an addslashes on incoming POST data. If so, turn off magic quotes, and when it's time to insert a string into the database perform the appropriate escaping then. If this is not possible, then use stripslashes to strip the slashes from all POSTed data at the beginning of the script execution so that you're getting the data as submitted.

Categories