Insert large blocks of code into MySql - php

I'm currently stuck trying to insert a particular type of user input into my MySQL database. I'm creating a form that allows the user to input Title, Requirements, Description, and PowerShell Script code into a database. I need to be able to then display the new input.
I started by converting all my $_POST data into htmlentities before inserting it and everything seemed to be working perfectly. All the short PowerShell scripts were inserting into the database and then displaying appropriately. But, when I tried to insert a long PowerShell script, it just left the table column blank.
// Create Insert SQL prepared statement
$insertSql = $pdoConn->prepare('INSERT INTO scripts (ScriptID, script_name, script_requirements, script_description, script_code) VALUES (NULL, :scriptName, :scriptRequirements, :scriptDescription, :scriptCode)');
// Create htmlentity variable
$htmlName = htmlentities($_POST['scriptName']);
$htmlReq = htmlentities($_POST['scriptRequirements']);
$htmlDesc = htmlentities($_POST['scriptDescription']);
$htmlCode = htmlentities($_POST['scriptCode']);
// Execute Insert SQL prepared statement
$insertSql->execute(array(
'scriptName' => $htmlName,
'scriptRequirements' => $htmlReq,
'scriptDescription' => $htmlDesc,
'scriptCode' => $htmlCode));
// Display success message and page return
echo "New script uploaded successfully.<br>";
echo "<a href='newScript.html'>Upload another script</a><br><br>";
// Create new query to display new data
$displaySql = $pdoConn->prepare('SELECT * FROM scripts ORDER BY ScriptID DESC LIMIT 1');
// Execute SELECT query and display results
$displaySql->execute();
foreach ($displaySql as $row) {
echo "<button class='accordion'>
<h3>".$row['script_name']."</h3>
</button>
<div class='panel'>
<p class='requirements-p'>Requirements: ".$row['script_requirements']."</p>
<p id='description-p'><span>Description: </span>".$row['script_description']."</p>
<code>".$row['script_code']."</code>
</div>";
}
The form I'm using to upload data looks like this:
<article id="main-article">
<h1>Add New Script</h1>
<div id="form-envelope-div">
<div id="envelope-inner-div">
<form id="script-form" action="uploadNewScript.php" method="post" enctype="multipart/form-data">
<div id="script-div">
<label class="input_label">Title: </label>
<input class="text_input" id="title-input" type="text" placeholder="Title *" name="scriptName" required>
<label class="input_label">Requirements: </label>
<textarea class="textarea_input" id="requirements-textarea" placeholder="Requirements *" rows="10" cols="30" name="scriptRequirements" required></textarea>
<label class="input_label">Description: </label>
<textarea class="textarea_input" id="description-textarea" placeholder="Description *" rows="10" cols="30" name="scriptDescription" required></textarea>
<label class="input_label">Script: </label>
<textarea class="textarea_input" id="code-textarea" placeholder="Script *" rows="10" cols="30" name="scriptCode" required></textarea>
</div>
<div id="submit-div">
<input id="button-input" type="submit" name="submit_btn" value="Upload New Property">
</div>
</form>
</div>
</div>
</article>
Here are two examples of the user input. The first example script is short and has no problem inserting into the database. Example 1:
Name: SSL CSR Requests
Requirements: PowerShell v3 and up.
Description: This uses PS to return all CSRs generated on the server as well as the Creation Date.
Code: Get-ChildItem cert:\LocalMachine\REQUEST\ | Sort-Object -Property Subject | fl Subject,#{n='Creation Date';e={$_.'geteffectivedatestring'()}}
The second example script is much more complex and will not insert at all if I use htmlentites. If I try skipping htmlentities and insert directly from $_POST, it will only insert the beginning: $source = Also, when I inserted the script directly into the database using PhpMyAdmin, I had no problems whatsoever. It even display in HTML correctly. Example 2 Code input:
$source = “C:\inetpub\logs\LogFiles\”
$destination = "E:\IISLogBackups_$(Get-Date -format M).zip"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
$logs = ls –Path “C:\inetpub\logs\LogFiles\*” –Recurse | Where-Object{$_.LastWriteTime –lt (Get-Date).AddDays(-14)}
$logs | Remove-Item

After a LOT of debugging, I finally figured out how to solve my problem. For whatever reason, the $_POST variable for the textarea field was having a problem reading the hyphens in the user input. Once the input reached the $_POST variable, it was already too late to fix the problem using htmlentities or any equivalent PHP function. So, I created a JavaScript function that automatically replaces all the hyphens with the HTML entity &#8221 before the user input is submitted. Here's what that JavaScript looks like:
document.getElementById('code-textarea').value.replace('-', '–');

Related

Insert Hierarchical numbering to MySql

How to allow user to insert hierarchical numbering like below. As for now, i'm using textbox and user will enter the number such as 1, 1.1, 2, 2.1, 2.1.1. And I can only display the data plainly, with no indent. I'm using PHP and MySql as database.
1 List item
1.1 List item
1.1.1 List item
2 List item
2.1 List item
2.1.1 List item
My form.
<form action="basicview.php?id=<?php echo $p_aid; ?>&&do=insert" method="post">
<div style="padding-bottom:5px">
<div style="float:left;width:5%;padding-top:7px"><label style="color:blue">No</label></div>
<div style="float:left;"><input class="text-input" type="text" name="t_no" size="10" value="" /></div>
<div class="clear"></div>
</div>
<div style="padding-bottom:5px">
<div style="float:left;width:15%;padding-top:7px"><label style="color:blue">Deliverables</label></div>
<div style="float:left;"><textarea class="text-input textarea" name="t_deliverables" cols="70" rows="2"></textarea></div>
<div class="clear"></div>
</div>
PHP.
if ($_GET['do'] == 'insert')
{
$t_no = $_POST['t_no'];
$t_deliverables = $_POST['t_deliverables'];
$sql = "INSERT INTO tbl_detail (p_aid,t_no,t_deliverables) ";
$sql .= "VALUES ($p_aid,'$t_no','$t_deliverables')";
mysql_query($sql);
redirect("basicview.php?id=$p_aid&type=success&msg=new+row+added");
}
If you want the users be able to post html data rather than plain text, you may use ckeditor or other similar tools. these tools convert textarea to a box like this one in stackoverflow.
But bear in mind that to prevent XSS attacks, you must verify posted data in server-side.
More importantly, the way you have scribed your sql query, it is highly vulnerable to sql injection. use prepared statements instead. For example if a malicious user post these data, you lose all data in the tbl_detail table:
$_POST['t_no']="1"
$_POST['t_deliverables']="1'); drop table tbl_detail;--"

I'm having some issues using Html value

I've a column inside my table to put Html codes, I will use this table for email templating.
I have inside my page, all the templates inside my table, with two buttons, one to remove, and another one to edit.
The edit button shows the code inside a textbox, and to do the preview I did an echo to the code column.
<div class="tempcolumn">
<div><textarea name="ai" rows="15" cols="100" name="code" placeholder="Code">
<?php echo $get_temp; ?></textarea></div>
</div>
Preview
<div class="tempcolumn">
<p><?php echo $get_temp; ?></p>
<div></div>
</div>
To recognize the code and the id i created an hidden input
<input type="hidden" name="temp_id" value="'.$val['template_id'].'">
<input type="hidden" name="temp_code" value="'.$val['text'].'">
The script is working, but when i insert inside the code column some "<" or "=" doesn't work
Is inferfering because it reads the input value like this:
<input type="hidden" name="temp_id" value=" Value here + 'random character that closes the tag' ">
Is there a easier way to do that?
Thanks
You can try;
htmlspecialchars($value)
This will convert html characters to their non-interfering cousins.
See http://docs.php.net/manual/en/function.htmlspecialchars.php as I can't post the equivalents without them becoming characters.

PHP form post to MySQL error

I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}

Posting form string to php - causes mysql_real_escape_string() to break

I have a form with a hidden field that looks something like this:
<form id="myform" method="post" action="/myphp.php">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" />
</div>
<div>
<input type="hidden" id="id" name="title" value="Bob's Group (test)" />
</div>
<div>
<input type="submit" value="Sign up" class="send_button" />
</div>
</form>
The hidden value 'title' get's its value from a Perch CMS php inline script and in this case it's "Bob's Group (test)".
The php script to process this form looks like this:
<?php
// Get and check input
$title = check_input($_POST['title']);
echo "title: $title<br>";
$name = check_input($_POST['name']);
$title = mysql_real_escape_string($title);
// Some sql queries that use $title
?>
The output looks like this:
title: Bob's Group (test)
title:
In other words, mysql_real_escape_string causes title to become a blank string.
Is there a way to handle this form value and generate a safe sql string to use?
mysql_real_escape_string() is MySQL server-side. It requires an active DB connection. Check if you have one in the moment of check.
Just a note, not an advice: mysql_escape_string() is client-side, i.e. works in PHP even without active MySQL connection.
You have to have an active connection to MySQL for msyql_real_escape_string() to work. You're most likely getting back a boolean FALSE from m_r_e_s() because you haven't connected, and it's issuing an error. If you do
$title = mysql_real_escape_string($title) or die(msyql_error());
^^^^^^^^^^^^^^^^^^^^^^
you'll most likely get a "not connected" error message.
The connection is required so m_r_e_s can properly escape things - it basically asks the server what its must-be-escaped metacharacters are so it can do its job properly.

when i refresh the page the text removes by itself , php?

When I type something in a text box and save it in mysqli it works perfectly but when I refresh that same page the text that i wrote stuff, it disappears for no reason. I also I have another text box in that page and it works perfectly fine. How can I fix that? The bio text box is the one I'm having issues.
$getpro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));$pro = $getpro;
$bios = $pro["bios"];
$realtionship = $pro["realtionship"];
$impmessage = $pro["impmessage"];
if ($_POST['bio']){
$bio = $_POST['bio'] ;
$query;
}
if ($_POST['impmessage']){
$impmessage = $_POST['impmessage'] ;
$query;
}
$query = mysql_query("UPDATE `profile` SET bios ='$bio', impmessage = '$impmessage' WHERE username = '".$user_data['username']."'");<form name="bio"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="bio" rows="7" ><? echo $bios; ?></textarea><br />
<input type="submit" value="change">
</form><hr /><form name="impmessage"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="impmessage" rows="7" ><? echo $impmessage; ?></textarea><br />
<input type="submit" value="change">
</form>
I have rearranged & removed some of the code and tried tidying it a bit:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) // if form is submitted using POST method
{
if ( isset( $_POST['bio'] ) ){
$bio = mysql_real_escape_string( $_POST['bio'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET bios ='$bio' WHERE username = '".$user_data['username']."'"); //update bios
}
if (isset( $_POST['impmessage'] ) ){
$impmessage = mysql_real_escape_string( $_POST['impmessage'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET impmessage = '$impmessage' WHERE username = '".$user_data['username']."'"); //update impmessage
}
}
$pro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));
?>
<form name="bio" action="" method="post">
<p>Bios</p>
<textarea cols="50" style="resize:none" name="bio" id="bio" rows="7" ><?php echo $pro["bios"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
<hr />
<form name="impmessage" action="" method="post">
<p>Important Message</p>
<textarea cols="50" style="resize:none" name="impmessage" id="impmessage" rows="7" ><?php echo $pro["impmessage"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
Some notes for you:
First of all avoid mysql_* functions. Instead use mysqli or PDO
I would always prefer writing the code for processing of user inputs in the very beginning of the page, ie. before outputting anything. Because, if the user inputs makes any changes on the output, it would easily display the updates since we are doing the processing before outputting anything. So, when we query the db, it would fetch the updated data. Also, if we wanted to redirect to another page or have to send some other headers to the browser, we could do it, as the headers should always be sent before outputting anything.
Another thing is, always escape user inputs. Otherwise, prone to sql injections. Best thing would be to use prepared statements which is available in mysqli & PDO.
When you name id of elements in your HTML, make sure that it is unique. Because no same ids could occur twice. But class names can occur for any number of times.
Also make sure that your PHP code doesn't get mixed up with the HTML. Properly enclose the PHP code with the <?php & ?> tags. I would always prefer avoiding shorthands.
Since you are using two forms, both the input won't reach the server side. Only a single one. If you wanted to both inputs to be reached at the same time, then use a single form.
I have also avoided unwanted assignment operations from the fetched data, to other variables.
Also, you should always properly indent your code for better readability.
I hope this would help. Wish you good luck. :)
Looks like you're running your update query every page load. If the post value isn't filled and you refresh it's going to update with empty values.
Ps sberry is right lots of other things to fix before this goes production.

Categories