Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Take data from text field and append to a text file 1

Status
Not open for further replies.

dreamaz

Technical User
Dec 18, 2002
184
CA
hello,

Im pretty new at this, what i'm trying to do is add a form on my website with one textfield. I'd like users to enter in their email address then submit, this information should get added to a text file resident on the web server. This is an email registration page

I can then mass mail those email addresses when i have an update available for them. can this be done?

Any help is appreciated.

Thanks,
 
Hmm.
Yes it can be done, quite easily.
But before we go further, have you considered the security ramification of a text file containing all these email addresses sitting on your server?

Additionally, are you fully aware of the CanSpam guidelines and the requirements put upon you if you collect email addresses?


Assuming you have thought about and understand all that (and the implications of it) you need to look up the fopen() and fwrite() PHP functions.


--
Tek-Tips Forums is Member Supported. Click Here to donate

<honk>*:O)</honk>

Tyres: Mine's a pint of the black stuff.
Mike: You can't drink a pint of Bovril.
 
you could try look at a book called 'PHP 5 IN EASY STEPS', i think the guestbook example may be of help..then again i dunno. but the first part is simple, youre just posting data out of a form which contains a text field.

also dreamaz, you need to take care of emails ALREADY in that text file, so that no duplicate are entered and stored.
This obviously means a writing a small function which will take the email address entered as an argument, and then from here, inside the function you write code which opens the text file for reading the file, checking the posted email addy with each line (email) of the text file.

by the way, when you click 'submit' do you want the program to output something like 'email addition successful' message ? or do you want that and then be redirected back to the form to enter a second email and third and so forth ??


 
this should get you off and running. try this first.


go visit this link and enter a fictitious email if u can.

then blah blah, just , i dunno play around heh. is that what you wanna do ?



its on my server i was playing around trying to achieve what you wanted...only problem is it fails to catch out emails entered that already EXIST in the file haha. :D

i know i can sort that out, but why dont YOU sort it out for a change ? :)
heres the code I used dude
==========================================================

// call this page 'add_fields'
// and save it as a htm page.


<html>
<head>

<title>add emails</title></title>
</head>

<body>
<form name='myform' method="post" action="checkemails.php">
<br>
Enter email address <input type="text" name='new_email' value="">

click to add email <input type="submit" name="submit" value="Add Email">

</form>
</body>
</html>


============================================================
// and call this script checkemails.php
// just copy n past ethe code into a notepad document
// go to save as, next to where it saves filename, add
// .php
// now next to where it says save as type pick 'all files'
// and save.
<?

$new_email = $_POST['new_email'];
// posted email stored in variable called new_email
// it came from your form

$filename = "emails.txt";

$fileptr = fopen($filename,"r"); // open for read

$myarray = file($filename);

// for ($i = 0; $i<count($myarray); $i++)
// {
$oneEmail = $myarray[$i];
// get one email address, one line from the text file
// at a time

if (strcasecmp($new_email,$oneEmail) == 0)
{
print "This email already exists!" ."<br>";
print "Please enter a different email" . "<br>";
fclose($fileptr);
// maybe add some code here to 'redirect to form'
}

else
{
$fileptr = fopen($filename,"a");
// write new email into text file after inserting
// a new line


fwrite($fileptr, "\n$new_email");
// use \r and \n in double quotes to add a cariage return and new line
print "you have added $new_email to the emails list" ."<br>";
fclose($fileptr);
// and you use the file pointer variable and the variable holding your new email with fwrite, to write
// to ya text file
$fileptr = fopen($filename,"r");
// now lets do a read , of the file and read our email list
$fileptr = fopen($filename,"r");
$myarray = file($filename);

foreach ($myarray as $newline)
{
print $newline . "<br>";
}
// but lets look at it as an array

fclose($fileptr);
}
// fclose($fileptr);

print " click the button below to view your text file";
print"<br>";


?>
<html>
<head>
<body>
<form name="myform2" method="post" action="emails.txt">
<input type="submit" name="submit" value="View emails.txt file!">
</form>
</body>
</head>
</html>
============================================================

and create a made up text file, i made one up and it appears on browser when you use the program i wrote.


if you want any more help let me know.

kindest regards

lazy c0der

 
fairly similar to cd0deMonK424 here is something that does what you need as an object.

from a security perspective you must make sure that the text file is stored in a folder either completely outside the webroot or, if not possible, then in its own directory with an appropriate .htaccess file. instructions are in the docblocks.

Code:
<?php
/**
 *	class for adding and retrieving email addresses from a text based database
 *
 *	inline example for adding an address
 *	<code>
 *		if (isset($_POST['email'])){
 *			$address = new emailAddressBook();
 *			$address->addAddress($_POST['email']);
 *			if ($address->isError()){
 *				$address->bail();
 *			}			
 *		}
 *	</code>
 *
 * 	inline example of addressbook use
 *	<code>
 *		$addressbook = new emailAddressBook();
 *		$addresses = $addressbook->getAddresses()
 *		foreach ($addresses as $address){
 *			//do something with the address
 *		}
 *	</code>		
 */

class emailAddressBook{
	private $file;
	public $addresses = array();
	private $newEmail;
	public $isError = false;

	/**		
	 *		constructor function
	 *
	 *		enter the absolute path ot the address book.
	 *		make sure it is in its own subdirectory and the subdirectory has
	 *		an .htaccess file with 
	 *		DENY FROM ALL
	 *		in it.  this stops people accessing directly the address book.	
	 */
	public function emailAddressBook(){
		$this->file = 'addressbook.txt';	//enter the absolute path to the address book.
		if (!is_file($this->file)){
			$fh = fopen($this->file,'w');
			fclose ($fh);
		}
		$this->cacheAddresses();
	}
	
	/**
 	 *		adds a new address to the address book
	 *
	 *		@param string $address	the email address to add (typically a $_POST variable)
	 */
	public function addAddress($address){
		$this->newEmail = trim(strtolower($address));
		$this->validate();
		if ($this->isError){
			$this->bail();
		}else{
			$this->commitChanges();
		}
	}
	
	/**
	 *	returns a numeric array of email addresses
	 */
	public function getAddresses(){
		if ($this->dirtyFile){
			$this->cacheAddresses();
		}
		return $this->addresses;
	}
	
	/**
	 *	gets all the addresses in the address book and caches them
	 *
	 */
	private function cacheAddresses(){
		$contents = file_get_contents($this->file);
		$addresses = explode('\r\n', $contents);
		if (is_array($addresses)){
			foreach($addresses as $key=>$val){
				if (!empty($val)){
					$this->addresses[] = $val;
				}
			}
		} else {
			$this->addresses = array();
		}
		$this->fileTouch = filemtime($this->file);
	}
	
	private function validate(){
		if (!$this->isValidEmail()){
			$this->setError(__LINE__, __FUNCTION__, "Email address {$this->newEmail} is not a valid address");
		}
		if ($this->isInBook()){
			$this->setError(__LINE__, __FUNCTION__, "Email address {$this->newEmail} is already in the address book");
		}
	}
	
	/**
	 *	validates the new email address 
	 */
	private function isValidEmail(){
		$pattern = "/^\\s*\\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+[.])+[A-Z]{2,4}\\b\\s*$/i";
		$result =  preg_match($pattern, $this->newEmail,$matches);
		return $result;
	}
	
	/**
	 *	checks whether the new email address is already recorded
	 */
	private function isInBook(){
		if ($this->isFileDirty()){
			$this->cacheAddresses();
		}
		return in_array($this->newEmail, $this->addresses);
	}
	
	/**
	 *	commits the new email to the address book
	 */
	private function commitChanges(){
		if ($this->isFileDirty()){
			$this->cacheAddresses();
		}
		$this->addresses[] = $this->newEmail;
		$fh = fopen($this->file, "w");
		print_r($this->addresses);
		$contents = implode("\r\n", $this->addresses);
		file_put_contents($this->file, $contents, FILE_TEXT | LOCK_EX);	
	}
	
	/**
	 *	checks whether the file has been changed since the last cacheing
	 */
	 private function isFileDirty(){
	 	clearstatcache();
	 	if (empty($this->fileTouch)){
	 		return true;
		}
	 	return ($this->fileTouch !== filemtime($this->file));
	 }
	 
	 /**
	  *	records salient details in an error message array
	  */
	 private function setError($line, $function, $message){
	 	$this->errorMessages[] = compact('line', 'function', 'message');
		$this->isError = true;
	 } 	
	 
	 /**
	  *	method to exit the process grecefully with some error messages
	  */
	 public function bail(){
	 	$messages = $this->getMessage();
		echo <<<HTML
<h1>Error processing</h1>
<p>The following messages were reported</p>
<ul>$messages</ul>
HTML;
	exit();	
	 }
	 
	 /**
	  *	method to retrieve data from the error messages, formatted for use in bail()
	  *	@return a string of error messages
	  */
	 private function getMessage(){
	 	$output = '';
	 	foreach ($this->errorMessages as $_message){	
			extract ($_message);
			$output .= <<<HTML
	<li>
		<p>Error occurred at line $line in function $function.</p>
		<p>Error message was: $message</p>
	</li>
HTML;
		}
		return $output;
	 }	
}
?>
 
lovely, very nice solution indeed jpadie. I was trying to avoid that route, and tried to find the simplest way to explain it to him as i felt he was a genuine novice; i myself being a learner lol.

but i liked how you approached it, very compact and robust coding. excellent!


regards

CodeMonk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top