0

Well I have most of the code working now. The point of the application is to store information from a contact form to a text file. So basically the point of the application is to take in information inputted by the user, store the information in a text file and allow the user to go back to the homepage.

It doesn't necessarily have to be a script to generate the contacts, it can be PHP, Bash, Script, HTML, etc. I just don't know how to do it!

Here is the code I have so far, I just need help with randomly generating the 100 contacts without manually inputting them, if I could get some input that would be appreciated :)

HTML CODE:

<form action="Registered.php" method="post">
     <p>
        <label>First Name:</label>
        <input name="fName" type="text">
    </p>
    <p>
        <label>Last Name:</label>
        <input name="lName" type="text">
    </p>
    <p>
        <label>Address:</label>
        <input name="address" type="text">        
    </p>
    <p>
        <label>State:</label>
        <select name="statedropdown">
<option value="Al"> Al </option>
<option value="AK"> AK </option>
<option value="AS">AS</option>
<option value="AR">AR</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DE">DE</option>
<option value="DC">DC</option>
<option value="FL">FL</option>
<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="ID">ID</option>
<option value="IL">IL</option>
<option value="IN">IN</option>
<option value="IA">IA</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="ME">ME</option>
<option value="MD">MD</option>
<option value="MA">MA</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MS">MS</option>
<option value="MO">MO</option>
<option value="MT">MT</option>
<option value="NE">NE</option>
<option value="NV">NV</option>
<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NY">NY</option>
<option value="NC">NC</option>
<option value="ND">ND</option>
<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>
<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="UT">UT</option>
<option value="VT">VT</option>
<option value="VA">VA</option>
<option value="WA">WA</option>
<option value="WV">WV</option>
<option value="WI">WI</option>
<option value="WY">WY</option>
</select>       
    </p>
    <p>
        <label>ZIP Code:</label>
        <input name="zip" required="required" placeholder="12345" type="text">        
    </p>
    <p>
        <label>Email:</label>
        <input name="email" required="required" placeholder="fake@email.com" type="email">
    </p>
    <p>
        <label>Phone Number:</label>
        <input name="phone" required="required" placeholder="912-555-1234" type="text">
    </p>
    <p>
        <input value="Submit" type="submit">
        <input type="reset" value="Reset">
 </p>
    <p>
        <td align="center"><a href="http://web-students.armstrong.edu/~tp2283/FormData.txt"> View contacts in database </a></td>
    </p>
    <p>
        <td align="center"><a href="http://web-students.armstrong.edu/~tp2283/contactsFile.htm"> View contacts in file </a></td>
    </p>
</body>
</html>

PHP CODE:

 <html>    
   <head>
      <title> Thank You </title>
   </head>
   <body>
   <?php
            $username="tp2283";
            $password="tootandnut";
            $database="tp2283";

                #declare variables
                $fName = $_POST['fName'];
                $lName = $_POST['lName'];
                $address = $_POST['address'];
                $statedropdown = $_POST['statedropdown'];
                $zip = $_POST['zip'];
                $phone = $_POST['phone'];
                $email = $_POST['email'];
                $DOCUMENT_ROOT = $SERVER['DOCUMENT_ROOT'];


                mysql_connect(localhost,$username,$password);
                mysql_select_db($database) or die( "Unable to select database");
                //$query = "SELECT * FROM contacts";
                //$result = mysql_query($query);
                //$num = mysql_num_rows($result);

$sql = mysql_query("SELECT * FROM contacts");
$file = "FormData.txt";
$fh = fopen($file, 'a') or die("can't open file");

while($row = mysql_fetch_array($sql)){
  $username = $row['user'];
  $password = $row['pass'];

  $accounts = "$username:$password\n";

  fwrite($fh, $accounts);
}   
                mysql_close();
    fclose($fh);

?>
      <h1 align = "center"> Thanks for Registering! </h1> <br /><br />
         <p align = "center"> Your information is: </p>
            <table align = "center">
               <tr>
                  <td> First Name: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $fName ?> </td>
               </tr>
               <tr>
                  <td> Last Name: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $lName ?> </td>
               </tr>
               <tr>
                  <td> Address: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $address ?> </td>
               </tr>
               <tr>
                  <td> State: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $statedropdown ?> </td>
               </tr>
               <tr>
                  <td> Zip: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $zip ?> </td>
               </tr>
               <tr>
                  <td> Telephone: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $phone ?> </td>
               </tr>
               <tr>
                  <td> E-mail: </td>
                  <td> &nbsp </td> 
                  <td> <?php echo $email ?> </td>
               </tr>
            </table>

<?php
    $outputstring =
     "First Name: $fName \n
     Last Name: $lName \n
     Address: $address \n
     State: $statedropdown \n
     Zip: $zip \n
     Telephone: $phone \n
     Email: $email \n
     -----------------------\n";

    file_put_contents("FormData.txt", $outputstring, FILE_APPEND | LOCK_EX);

?>
      <p align="center"><a href="Assignment3.html"> Return to Main Page </a> </p>
      <p align="center"><a href="FormData.txt"> View Contacts in Database </a> </p>
   </body>
</html>

3 Answers3

1

Sooo... I know there's already an answer, but I decided to have a little fun with this.

My approach uses cURL and PHP and posts to the form via HTTP. This way, you can test that your PHP code works as well, beyond just testing the SQL schema. I also wanted to get kind-of real-world data. This will open and close a curl session every time (the same session is not reused). Anyways, like I said, just for fun:

<?php

$numPosts = 100;
$sleep = 0.1; // seconds
$postUrl = 'http://web-students.armstrong.edu/~tp2283/Registered.php';

$firstNames = array(
    'Bill','William','Joe','Bob','David','Jerome','Shane','Matt','Michael','Andrew',
    'Sally','Sue','Courtney','Olya','Kristin','Theresa','Cheri','Melony','Alex','Cindy'
);

$lastNames = array(
    'Smith','Dobson','Johnson','Zammit','Brown','Jones','Miller','Garcia','Wilson','Martinez',
    'Anderson','Taylor','Thomas','Moore','Martin','Jackson','Lopez','Lee','Harris','Clark'
);

$streets = array(
    'Central Ave','Broadway','1st St','2nd St','3rd St','Washington St',
    'Jefferson Ave','Woodcreek Blvd','Pines Dr','Big Cr','Tennis Ct'
);

$stateList = array(
    'AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY',
    'LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH',
    'OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'
);

$domains = array(
    'yahoo.com','mail.com','gmail.com','example.net','host.org',
    'stuff.im','aol.com','hostmail.com','msn.com'
);

for ( $i = 0; $i < $numPosts; $i++ ) {
    $data = array(
        'fName' => generateFirst(),
        'lName' => generateLast(),
        'address' => generateStreet(),
        'statedropdown' => generateState(),
        'zip' => generateZip(),
        'email' => generateEmail(),
        'phone' => generatePhone()
    );
    $result = postData($postUrl,$data);
    var_dump($result);
    usleep($sleep/1000000);
}

function postData($url,$data) {
    $ch = curl_init();
    $opts = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_URL => $url
    );
    foreach ( $opts as $key => $value ) {
        curl_setopt($ch,$key,$value);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function generateFirst() {
    global $firstNames;
    return $firstNames[array_rand($firstNames)];
}

function generateLast() {
    global $lastNames;
    return $lastNames[array_rand($lastNames)];
}

function generateStreet() {
    global $streets;
    $houseNumber = mt_rand(1,3000);
    $street = $streets[array_rand($streets)];
    return $houseNumber.' '.$street;
}

function generateState() {
    global $stateList;
    return $stateList[array_rand($stateList)];
}

function generateZip() {
    return str_pad(mt_rand(0,99999),5,'0',STR_PAD_LEFT);
}

function generateEmail() {
    global $domains;
    $randomCharacters = md5(mt_rand());
    $firstIndex = mt_rand(3,7); // length
    $user = substr($randomCharacters,0,$firstIndex);
    $domain = $domains[array_rand($domains)];
    return $user.'@'.$domain;
}

function generatePhone() {
    $areacode = mt_rand(100,999);
    $first3 = mt_rand(100,999);
    $last4 = mt_rand(1000,9999);
    return $areacode.'-'.$first3.'-'.$last4;
}

?>

It is split up into functions, so adding random variance with regard to input format should be pretty easy to do, if you want to also consider server-side form validation.

I also added a sleep time (in seconds, but using usleep which is in microseconds) so as not to overload the server.... I suppose if you distributed this, you could also performance test.


Usage (tailored to OP):

  1. Create a new/blank file called populate.php
  2. Copy the code contents in this post (including the <?php and ?> tags) and paste into the populate.php file
  3. Change the value of $numPosts (currently 100) to 2 for the purpose of testing: $numPosts = 2;
  4. If you a remotely accessing the server web-students.armstrong.edu (via FTP, SCP, a file management system in your browser, etc.) upload the populate.php file to your directory (~tp2283). Depending on the software and configuration this directory could be hidden in which case just upload to the top-most directory.
  5. In a browser, navigate to http://web-students.armstrong.edu/~tp2283/populate.php
  6. Wait for the script to finish...
  7. Notice the output: it should be HTML markup from the Registered.php page twice (one time for each of the $numPosts
  8. Once successful, update $numPosts to 100 (edit locally, then reupload and overwrite, if necessary)
  9. Refresh the http://web-students.armstrong.edu/~tp2283/populate.php page in your browser. You should now have the HTML from Registered.php x100.
  10. Check your database, there should be 102 (2 + 100) new entries.

This may not work if cURL is not enabled/installed: how to check if curl is enabled or disabled. In which case a different method using file_get_contents will be required, in which case it will only work if allow_url_fopen is enabled.

If you are running PHP locally, you can always change/update these features to allow the functionality. These specifics are outside the scope of this question.

Community
  • 1
  • 1
zamnuts
  • 9,492
  • 3
  • 39
  • 46
  • Thank you so much! Now is this replacing my current file Registered.php or is this going to be a new file itself? I am currently getting this error: **The requested URL /~tp2283/Registered.php was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache Server at web-students.armstrong.edu Port 80 " string(415) "** – user3009883 Nov 26 '13 at 03:02
  • This isn't supposed to add functionality to your code, instead it is intended to simulate a user (client) submitting the form (or rather a number of them as specified by `$numPosts`); in other words not a replacement, but a new *temporary* file for testing with. You'll have to update the value of `$postUrl` to whatever the absolute URL is to your form submission handler. I only guessed what the URL is based on your question. I ran a few test from my local, and successfully submitted 4 results (the first 2 were bad, but the 2nd two were good): `Thanks for Registering! Your information is:` – zamnuts Nov 26 '13 at 03:05
  • So do I just need to keep entering in random data and it will generate more for me or what? – user3009883 Nov 26 '13 at 03:12
  • It is a stand-alone script. You don't need to enter any random data unless you want to change some of the values that are randomized already. The script randomizes itself based on the values in the array and the `mt_rand` calls. Set `$numPosts = 10;` and access the PHP page in your browser. It will make 10 posts to your Register.php script, then check your database and you should see those populated. You do not need to POST/GET to this PHP script, just simply navigating to it with a browser (or other means) will make it work. – zamnuts Nov 26 '13 at 03:16
  • This is what happens when I access the .php file through my browser. **Not Found The requested URL /~tp2283/Assignment3.html was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache Server at web-students.armstrong.edu Port 80 " string(417) "** – user3009883 Nov 26 '13 at 03:24
  • @user3009883 I'm not sure where `Assignment3.html` came from? This should be a PHP file, e.g. "populate.php". *Troublshooting your usage is a bit off topic.* I can help, but perhaps a SO chat session is in order. – zamnuts Nov 26 '13 at 03:27
  • Only 6 reputation, I can't chat yet :( Assignment3.html is the html file that the php file is running off of? I didn't know if I had to switch it to that file. BUT I changed it back to the .php file, its just giving me the error – user3009883 Nov 26 '13 at 03:34
0

Assuming you are asking for 100 fake contacts to test with...

A basic loop would do it

<?php
for($i = 0; $i < 100; $i ++)
{
    mysql_query("INSERT INTO `contacts` (`first_name`, `email`, `etc`) VALUES ('someone ".rand(0,999)."','someone".rand(0,999)."@test.com','etc')");
}
?>

Obviously this relies on an open connection and your actual fields plugged in. No need to bother with escaping anything since this is just script generated test data, right?

Obligatory announcement: mysql_ functions are deprecated. Switch to mysqli or PDO. There are plenty of resources available with just simple google searches like "mysqli_connect" etc.

If this is not what you needed, please update your question.

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
  • It might not be a bad idea to run one query with 100 sets of values instead of 100 queries with one set each. – Shomz Nov 26 '13 at 02:31
  • true indeed but he's running it once to test with I assume. No need for optimizing anything here – Kai Qing Nov 26 '13 at 02:32
  • We upload to our school's server which unfortunately is not updated with mysqli or else we would be using that. So mysql for now... Now how would I go about inputting in 100 sets of values instead of 100 queries is what I am wondering? – user3009883 Nov 26 '13 at 02:35
  • fair enough, but is this what you needed or did you need something else? – Kai Qing Nov 26 '13 at 02:36
  • I need to write an SQL script that when run, generates and populates the appropriate tables for the application with at least 100 contacts. Please provide a brief explanation for each field of the table (or tables) in your Database. – user3009883 Nov 26 '13 at 02:40
  • `for($i = 0; $i < 100; $i ++) { mysql_query("INSERT INTO `contacts` (`fName`, `lName`, `address`, `statedropdown`, `zip`, `phone`, `email`) VALUES ('someone ".rand(0,999)."','someone".rand(0,999)."@test.com','etc')"); }` What exactly do I do with the 'someone".rand(0,999(."@test.com','etc')?? I'm a little lost on that part? – user3009883 Nov 26 '13 at 02:52
  • nothing. it will just add names like someone455, someone321@test.com, etc. all its doing is appending a random number from 0 to 999 after the word someone. There may be duplicates but this is just for testing – Kai Qing Nov 26 '13 at 03:04
  • oh you mean cause the field count doesn't match? You can just do something like VALUES ('someone ".rand(0,999)."','lastname ".rand(0,999)."','some fake address', 'CA', '94101','123-123-1234','someone".rand(0,999)."@test.com') – Kai Qing Nov 26 '13 at 03:08
0

Please use PHP Faker which generates the fake data for you. You can find the this PHP Library @ https://github.com/fzaninotto/Faker. The link guides you how to install and use the more advanced and wide range of features as per your needs.

With the help of this library you can generate as many as data with no time.

The following is the snippet of its usage -

<?php

require_once 'vendor/autoload.php';

$faker = Faker\Factory::create();
$person = new Faker\Provider\en_US\Person($faker);
$address = new Faker\Provider\en_US\Address($faker);
/* You can loop as many times the data you want to generate */
foreach(range(1,10) as $i){
    echo $person->titleMale(),'.',$person->name('male'),'<br/>';
}
Channaveer Hakari
  • 2,769
  • 3
  • 34
  • 45