Data in a Form

Hello, I have a Credit Authorization form I made
for a website and I was wondering if it is possible
to have the form save the data to a file and store it on a specific folder
in the server?

1 Like

Yes, that’s quite simple. I haven’t done it for a long time, though, so I’ll let someone else provide the details. You could save the files to a location above the root for better security. Security would be my main concern here.

2 Likes

+1 for security.

It is recommended that if you want to save user credentials in a file, you should move those files above the root folder. However, you can also do this via database as well. Doing it the database way is the most used option. So I’m not sure which one you want to go with. Both still need a security check.

Ill do it database way. Do you know how?

Above the root folder meaning outside of the folder
my code files are in?

I created my database this is my php:

<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "creditcardautho.db.6870551.hostedresource.com";
$username = "creditcardautho";
$dbname = "creditcardautho";

//These variable values need to be changed by you before deploying
$password = "IOGdevices2015!";
$usertable = "DataTable";
$yourfield = "your_field";

//Connecting to your database
mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysqli_select_db($dbname);

//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysqli_query($query);

if ($result) {
while($row = mysqli_fetch_array($result)) {
$name = $row["$yourfield"];
echo "Name $name<br>";
}
}
?>

Should their be more than one $yourfield = "your_field";?
depending on the amount of fields I have in my table?

You need to fix the database calls - all the mysql_ calls were removed from PHP earlier this month.

Use mysqli or PDO instead.

1 Like

Do you have error reporting on? If not, you should enable it. Just from the looks of it, you should be getting a lot of fatal error. You should also change change your password if that is your actual password for your database. It’s too late now to make an edit since your password will still show up in the edit history.

I havent tested it yet its not on my server…so I take out my actual password? should
it just be blank?

Im using this code sample from godaddy:

<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "creditcardautho.db.6870551.hostedresource.com";
$username = "creditcardautho";
$dbname = "creditcardautho";

//These variable values need to be changed by you before deploying
$password = "your password";
$usertable = "your_tablename";
$yourfield = "your_field";

//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);

//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);

if ($result) {
    while($row = mysql_fetch_array($result)) {
        $name = $row["$yourfield"];
        echo "Name $name<br>";
    }
}
?>

is this the right code? should I add or remove anything?

You should actually change your database password on Godaddy then. You just showed everyone on this forum your password here.

By making an edit to that post or by posting a new snippet with your password removed, it won’t help since everyone on this forum already knows your password. It is highly suggested to change it now.

You should remove everything. The logic is flawed and not to mention the mysql_* functions have been deprecated (meaning no longer supported and or obsolete) since PHP Version 5.5. In the recent PHP 7 release, mysql_* functions have been removed completely and will no longer exist in newer versions. However, you can use either mysqli_* or PDO. If you choose to use mysqli_* however, I recommend reading how to use it. You can’t just simply go to your IDE software, click on Find & Replace All, and replace all old mysql_* functions to mysqli_* functions. That’s NOT how it works. There are some things that need more work if you use mysqli_*. So simply appending an i at the end of mysql will not work.

Now, besides the deprecated functions and the logic, there are still some flaws like not escaping data that is being displayed such as $name = $row["$yourfield"];. Also, not to mention $row["$yourfield"]; will probably throw you a fatal error. Should actually be $name = $row["yourfield"];.

Then the asterisk (*) wild card. It’s best practice to specify which column you want to display instead of using the asterisk (*) wild card. It is easier to use the asterisk (*) wild card if you don’t know what the table will hold, but if you are already doing something like $name = $row["yourfield"];, then you already know that the column you want is yourfield. Which in this case means that using the asterisk (*) wild card is pretty much useless. Unless you’re a lazy developer which you shouldn’t be since programming takes a lot of work and effort.

Alright I changed my password…

How about this logic:

<?php 

if (isset ($_POST['submit'])) {}

$con = mysqli_connect("host","my_user","my_password","my_db");

// Check connection
if (!$con)
  {
  die("Can not connect: ") . mysql_error());
  }

mysqli_select_db("dt_name", $con);

$sql = "INSERT INTO table_name (ex1, ex2, ex3) VALUES ('$_POST[topic]','$_POST[topic]','$_POST[topic]')";

mysqli_query($sql,$con); 
mysql_close (&con);

?>

Nooooo. Don’t use that logic. It is pure flawed. As I have said to many other users. When you use if(isset($_POST['submit'])), if(isset($_POST)), if(isset($_POST['button'])), it’s actually very flawed. In some browsers (only heard in IE), when a user types something into the text field and hits the “Enter” key on their keyboard on that text field or on a different text field, the form will fail simply because the “submit” button was not clicked on. That is why it is flawed. Proper way to check for form submission is if($_SERVER['REQUEST_METHOD'] == 'POST').

Also, you are prone to SQL Injection (highly recommend using prepared statements when insert or selecting using the WHERE clause) and you are displaying the connection errors to the user. This is a bad idea because they can gain control of your database with ease.

is sending the form data to a file a similar approach? Im a novice
at this not sure what the right code should be. Sucks that godaddy
sql section gives the wrong code and has not updated based
on what you have told me…

Found these:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

and

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

You’re on the right path, but it’s still prone to SQL Injection. You must use prepared statements to avoid this. You should also stop stuffing the actual data into the INSERT query string.

I have found this book by Murach to be a good read for this subject

https://www.murach.com/shop/murach-s-php-and-mysql-2nd-edition-detail

See Chapters 5 and 19 for great help.

You can download the code without buying the book, however I have purchased this book and found it one of the best books around on Php and Mysql

what does this mean?

[quote=“spaceshiptrooper, post:15, topic:209661”]
You must use prepared statements to avoid this.

[/quote]prepared statements?

You mean not do this? VALUES ('John', 'Doe', 'john@example.com')";

how about? VALUES ('$_POST[topic]', '$_POST[topic]', '$_POST[topic]')";

simple example

$_POST['textinput'] = "' OR 1 = 1";
... WHERE somefield = '" . $_POST['textinput'] . "'; ";

WHERE somefield = '' OR 1 = 1'

more … https://www.owasp.org/index.php/Guide_to_SQL_Injection

http://php.net/manual/en/mysqli-stmt.bind-param.php

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
1 Like

SQL Injection is an exploit via many ways. It can either be through $_GET or $_POST params. As shown by @Mittineague, you can exploit the data to display what ever you want. Mostly, it relies on guessing the user’s table since sometimes the tables aren’t named the same.

Prepared statements can be used in both mysqli_* and PDO. @Mittineague has given a good example of mysqli_* prepared statements.

Here’s one with PDO

$stmt = $pdo->prepare("INSERT INTO CountryLanguage VALUES (:code, :language, :official, :percent)");
$array = array(':code' => $code, ':language' => $language, ':official' => $official, ':percent' => $percent);
$stmt->execute($array);

That snippet, we use an array to bind our placeholders instead of using bindValue() for each value. This takes less time and less lines, but you can use either or.

Yes, that is how SQL Injections start in the first place. When you stuff raw value like that into the query string, you aren’t telling PHP that what the user types in is just a string and not part of the query string. Mostly, SQL Injections is the exploit in which data can be passed as code. So if you insert raw data into your query string, it can be misinterpreted by PHP. This applies with any kind of query string if it relies on client input. Mostly for SELECT, UPDATE, and DELETE, it’s when you start to use the WHERE clause should you use prepared statements. For INSERT, you should always use prepared statements.

1 Like

So I guess ill do it this way:

<?php
$mysqli = new mysqli('creditcardautho.db.6870551.hostedresource.com', 'creditcardautho', 'my_password', 'creditcardautho');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO DataTable VALUES (CompanyName, CardName, BillingAddress, CardCheck, CardNumber, ExpDate, CardID, Initials, Date, Notes)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table DataTable */
$mysqli->query("DELETE FROM DataTable WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Im not sure what goes here though?:

$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

This is where I put my table fields correct? from my database?

$stmt = $mysqli->prepare("INSERT INTO DataTable VALUES (CompanyName, CardName, BillingAddress, CardCheck, CardNumber, ExpDate, CardID, Initials, Date, Notes)");

This is my user form: (HTML)

<form id="offer-form" class="cc-form" action="info.php" method="post">
                        <fieldset>
                            <legend>Please Complete Credit Card Form Below</legend>
                            <h5>*Required Fields</h5>
                           <input type="text" name="CompanyName" placeholder="*Company Name" required="required">   
                           <input type="text" name="CardName" placeholder="*Cardholder Name" required="required"> <br>  
                           <input type="text" name="BillingAddress" placeholder="*Billing Address" required="required">     
                          <br>  
                           <label for="My goods are transported by:">Credit Card Type: <br> <input type="radio" name="CardCheck" value="Visa" required="required">&nbsp;&nbsp;<label> <i class="fa fa-cc-visa fa-2x"></i> <input type="radio" name="CardCheck" value="Mastercard" required="required"><i class="fa fa-cc-mastercard fa-2x"></i> <input type="radio" name="CardCheck" value="AmEx" required="required"> <i class="fa fa-cc-amex fa-2x"></i></label>
                             
                           </label><br>
                            <input type="text" name="CardNumber" placeholder="*Credit Card Number" required="required">     
                            <input type="text" name="ExpDate" placeholder="*Expiration Date mm/yy" required="required">     
                            <input type="text" name="CardID" placeholder="*Card ID Number" required="required"><strong>(Last 3 digits on the back of the credit card.)</strong>     
                           <br>
                            <p>I authorize <em>Impact-O-Graph Devices</em> to charge my credit card provided herein. I agree that I will pay for this purchase in accordance with the issuing bank cardholder agreement. Inital below.</p>
                            <input type="text" name="Initials" placeholder="*Authorization Initials" required="required">
                              <label>Date: <input type="date" name="Date" placeholder="*Date" required="required"></label>
                            <textarea name="Notes" class="cc-notes-area" placeholder="Notes"></textarea>
                            <br><br>
                            <input id="btn-success" class="hvr-skew-forward contact-sub" type="submit" name="submit" value="Submit"/>
                            
                        </fieldset>
                    </form>