Jump to content

Having a bear of a time with functions...


JPark

Recommended Posts

:facewall:

 

I am new to functions and would appreciate some guidance...

 

I have a page that is getting some values from a form ($_POST['states'], $_POST['sectors'] and $_POST['email'] --  the first two values are arrays.  I want to create a function to run the values through a loop, perform some checks and then fwrite the values to a text file on another server.

 

However, I only want to run this function after the user has correctly answered a CAPTCHA.

 

For the life of me, I cannot figure this out.  I can do some very simple functions but this one has me running in circles.

 

Can anyone help shed some light?

 

Please and thank you!!

 

Joe

Link to comment
Share on other sites

For example...

 

function write_the_results($states,$sectors,$email,$today) {
$states = ( isset( $_POST['states'] ) && !empty( $_POST['states'] ) )
        ? $_POST['states']
        : null;
$sectors= ( isset( $_POST['sectors'] ) && !empty( $_POST['sectors'] ) )
        ? $_POST['sectors']
        : null;
$email=( isset( $_POST['email'] ) && !empty( $_POST['email'] ) )
        ? $_POST['email']
        : null;
$today = date('m.d.Y');


	echo "<b>For testing only: </b><br />";
	$line1= $today." ^ ".$states." ^ ".$sectors." ^ ".$email;
	echo $line1."<br>";
}

 

And later...

	} elseif( $captcha_match && empty($usr_errors) )
{
echo "<br /><b>".$_POST['email']."</b>";
echo "<span class='forthem'>";
echo COMPLETE_RESPONSE_TXT;
echo "</span>";
write_the_results($today, $states, $sectors, $email);


}

 

And I get...

Notice: Undefined variable: today in /vs/webdev/docs/econ/notifyme/state_entry2.php on line 432

For testing only:

08.03.2009 ^ ^ ^ j@j.org

 

So, I get an error on $today even though it shows up like I wanted, I don't get anything for $states or $sectors and I get the email correctly (matching $_POST['email']).

 

What am I doing wrong?  What do I do to fix it?

 

Thanks.

Link to comment
Share on other sites

line 432: echo COMPLETE_RESPONSE_TXT;

 

which comes from an include:

define('COMPLETE_RESPONSE_TXT',<<<HTML

 

<span class="forthem">

<p> </p>

<p>Thank you for using the NotifyMe System.</p>

<p>You should receive a confirmation notice by e-mail within 2 business days.</p>

<p>You may also print this page for your records by using the button below.</p><br />

              <form><input type="button" value=" Print this page "

                onclick="window.print();return false;" /></form>

    </span>

 

HTML

);

 

 

 

Link to comment
Share on other sites

It is not an error. It is a notice. That is an important difference. You can rid of it by assigning a value to the variable before it gets used for the first time. An example when you would get such a notice is when using the concatenator on a non-defined string like this: $myVar .= 'someVal';

 

Are you sure it is not from this line:

write_the_results($today, $states, $sectors, $email);

 

I noticed that the order of the variables are not matching up in function def and your call to it:

write_the_results($states,$sectors,$email,$today){...

write_the_results($today, $states, $sectors, $email);

 

hth

 

Bjom

Link to comment
Share on other sites

That helps but it's STILL not being sent (fwrite).  I currently call the function after the CAPTCHA is answered correctly.  The COMPLETE_RESPONSE_TXT; is echoed correctly after a successful CAPTCHA but the text file is not appended or created.

 

If I call the function earlier (say, 30 lines up), it works fine.

 

Why???  :facewall:

Link to comment
Share on other sites

I hope this helps...

<?php
/* Description of stateentry.php
*
*
*
*
* Last modified: 1:13 PM 4/2/2009
**/
include('includes/naics_constants.php');
include('includes/naics.php');
include('includes/cb_text_captcha.php');

$states = ( isset( $_POST['states'] ) && !empty( $_POST['states'] ) )
        ? $_POST['states']
        : null;
$sectors= ( isset( $_POST['sectors'] ) && !empty( $_POST['sectors'] ) )
        ? $_POST['sectors']
        : null;
$email=( isset( $_POST['email'] ) && !empty( $_POST['email'] ) )
        ? $_POST['email']
        : null;


$sys_errors = array(); // errors we may not want to show the user
$usr_errors = array(); // errors we should
$captcha_match = false; // did the capcha answer pass? Assume no at start

function write_the_results($states,$sectors,$email) {

$today = date('m.d.Y');


if (!is_null($states) && !is_null($_POST['sectors']) )
{
	foreach ($_POST['states'] as $temp)
		{
		$abbreviations=explode("-",$temp);
		$line1= $today."^".$_POST['email']."^".$abbreviations[0]."^";
			foreach ($_POST['sectors'] as $temp)
				{
					$sectorCodes=explode("-",$temp);
					$line= $line1.$sectorCodes[0];
					$file_test='/vs/www/http_db/notify/TEST'. date('Ymd') . 'bystate.txt';
					$file_handle = fopen($file_test,'a');
					$file_write = fwrite($file_handle, "\r\n$line");
				}
		}
} else {
}
}	

function write_for_them() {
echo "<b>".date('l jS \of F Y, h:i:s A')."<br />";
$states = 	$_POST['states'];
$sectors = 	$_POST['sectors'];
$email =	$_POST['email'];

	foreach($_POST['states'] as $v)
		{
		$stateName=explode("-",$v);
		echo $stateName[1]."<br>";
		}
	foreach($_POST['sectors'] as $w)
		{
		$sectorName=explode("-",$w);
		echo $sectorName[1]."<br>";
		}
echo "</b>";
}

if( isset($_POST) && !empty( $_POST ) )
{
// This section pattern matches the POSTED email.
// if it complies, use $email_label to show the email address
if(!preg_match(EMAIL_REGEX, $_POST['email']))
{
	$usr_errors[] = USR_ERR_EMAIL;
	$email_label = '<label for="email" style="' . LABEL_STYLE . '">Email Address:</label> ';
	$email_input = '<input type="text" id="email" name="email" value="' . $_POST['email'] . '" />';
}
else
{
	$email_label = '<span style="' . LABEL_STYLE . '">Email Address:</span> ';
	$email_input = htmlentities( $_POST['email'] ) . '<input type="hidden" name="email" value="' . $_POST['email'] . '" />';
}


$captcha_match = ( isset($_POST['captcha']) )? php_check_captcha($_POST['captcha']) : false;

if( isset( $_SESSION[sESS_TXT_CAPTCHA_ANSWER] ) && !$captcha_match )
	$usr_errors[] = USR_ERR_CAPCHA;

if( $captcha_match && empty($usr_errors) )
{
	// In our example we're opening $filename in append mode.
	// The file pointer is at the bottom of the file hence
	// that's where $somecontent will go when we fwrite() it.
	//

	// 'a+' - Open for reading and writing; place the file pointer
	// at the end of the file. If the file does not exist, attempt
	// to create it. 
	if ( ($file_handle = @fopen(NOTIFY_ME_STORAGE_FILE, 'a+'))!==false )
	{
      //$file_locked = true;
	  //*
		// waiting until file will be locked for writing (FILE_LOCK_TIMEOUT milliseconds as timeout)
		$startTime = microtime();
		//echo "<pre>$startTime\n";
		do
		{
			$file_locked = flock($file_handle, LOCK_EX);
			// If lock not obtained sleep for 10 - 100 milliseconds, to avoid collision and CPU load
			//var_dump($file_locked);
			if(!$file_locked)
				usleep(round(rand(10, 100)*1000));
		}
		while (!$file_locked && (microtime()-$startTime) < FILE_LOCK_TIMEOUT); 
      /**/
		// Let's make sure the file exists and is writable first.
		// lets also make sure that the user information we checked
		// so far is valid.
		if( $file_locked && is_writable( NOTIFY_ME_STORAGE_FILE ) )
		{
			foreach($process_order as $key=>$section)
			{
				if( isset( $_POST["$key"] ) && !empty( $_POST["$key"] ) )
					save_posted_naicscodes($_POST["$key"], $section[0], $section[1], $_POST['email'], $file_handle);
			}

			fclose($file_handle);
		}
		else
			$usr_errors[] = 'System is busy.';
	} else
		$sys_errors[] = "The file (" . NOTIFY_ME_STORAGE_FILE . ") is not writable";

}
}

?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<!-- Change date each time you modify the page -->
<meta name="DC.date.created" scheme="ISO8601" content="2008-22-04" />
<meta name="DC.date.reviewed" scheme="ISO8601" content="2008-22-04" />
<meta name="DC.language" scheme="DCTERMS.RFC1766" content="EN-US" />
<style type="text/css">
<!--
.forthem {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: medium;
color: #333366;
}
.note {
font-style: italic;
font-weight: bolder;
color: #333366;
}
.notice {
color:red;
font-size:120%;
	}

-->
</style>
<title> NotifyMe :: Thank you!  ****</title>
<!-- Site wide JS -->
<script type="text/javascript" src="/main/javascript/ruthsarian_utilities.js"></script>
<script type="text/javascript">
	<!--
		if ( ( typeof( set_min_width ) ).toLowerCase() != 'undefined' ) { set_min_width( 'page-container' , 783 ); }
		if ( ( typeof( sfHover ) ).toLowerCase() != 'undefined' ) { event_attach( 'onload' , function () { 
			//sfHover( 'leftmenu' );
			sfHover( 'middlemenu' );
		} ); }
	//-->
	</script>
<script type="text/javascript" src="/main/javascript/unlink.js"></script>
<script type="text/javascript" src="/main/javascript/jquery.js"></script>
<!--End JavaScript Links-->
</head>
<body>
<div id="page-container"> 
  <!-- 44px height -->
  <!-- newline whitespace removed -->
  <!-- wordwrap at col 78 -->
<noscript>
  This Javascript highlights what section of the main navigation you are on and 
  unlinks its URL. 
  </noscript>
  <a name="SKIP2"></a> 
  <div id="outer-column-container"> 
    <div id="inner-column-container"> 
      <div id="source-order-container"> 
        <div id="middle-column"> 
          <div class="inside" style="margin: 1em 2em;"> 

	    <h2>NotifyMe :: Confirmation</h2>
<?
// for each $cat
if(!$captcha_match )
{
?> 
		<!-- START NOTIFYME FORM -->
		<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">

<?php
//write_the_results($states,$sectors,$email,$today);   This will write the results -- but before the CAPTCHA check etc.  NOT GOOD!

echo "<br>";

$states_count= count($_POST['states']);
$sectors_count= count($_POST['sectors']);
$combined_count= ($states_count + $sectors_count);

if ( ($states_count == 0) || ($sectors_count == 0) )
{
	echo "<span class='notice'>Please correct the following:";
		echo "<ul>";
			if ($states_count == 0 ) {
				echo "<li>You have not selected any states.</li>";
				}
			if ($sectors_count == 0 ) {
				echo "<li>You have not selected any sectors.</li>";
				}
		echo "</ul></span>";
}



if (is_array($states) && isset($states) )
{
	if ($states_count > 0) {
		echo "<b>You have selected the following state(s):</b><br><blockquote>";
			foreach($_POST['states'] as $v)
				{
					if ( in_array($v, $states, TRUE) )
					$stateName=explode("-",$v);
					echo $stateName[1]."<br>";
				}
		echo "</blockquote>";
	} 
		else 
			{
			}
	}

if (is_array($sectors) && isset($sectors) )
{
	if ($sectors_count > 0) {
		echo "<b>You have selected the following sector(s):</b><br><blockquote>";
			foreach($_POST['sectors'] as $w)
			{
				if( in_array($w, $sectors, TRUE) )
					{
					$sectorName=explode("-",$w);
					echo $sectorName[1]."<br>";
					}
			}
		echo "</blockquote>";
	} 
		else 
			{
			}
		}



if($combined_count)
{
	if( !isset($_SESSION['seen_captcha_message_once']) )
	{
?>
			<h3>You are almost done...</h3>

              <p>Please show us that you are a real person and not a web robot 
                by answering the following mathematical question.</p>

              <p class="note">Please note that your answer must be spelled out 
                (example, 'two' or 'Two') and not numeric (example, '2').</p>
			<p>Entering the correct answer and clicking Submit Form will complete your registration.</p>
			<p> </p>
<?php
		$_SESSION['seen_captcha_message_once'] = null; // it's existance, not it's value is being tested.
	} // end if( !isset($_SESSION['seen_captcha_message_once']) )
?>
			<table style="<?=TABLE_STYLE;?>">
				<tr>
					<td style="<?=TABLE_TDROW1_STYLE;?>"><?=$email_label;?></td>
					<td style="<?=TABLE_TDROW1_STYLE;?>"><?=$email_input;?></td>
				</tr>
				<tr>
					<td style="<?=TABLE_TDROW2_STYLE;?>"><label for="captcha" style="<?=LABEL_STYLE;?>"><?=php_generate_captcha();?></label><br/>
					<small><?=TXT_CAPTCHA_EXAMPLE;?></small></td>
					<td style="<?=TABLE_TDROW2_STYLE;?>"><input type="text" id="captcha" name="captcha" /></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="<?=ENTRY_SUBMIT_TEXT;?>" /></td>
				</tr>
			</table>
		</form>
		<!-- END NOTIFYME FORM -->
<?php
} // end if($naics_code_count)
else
	echo '<input type="button" value="Go Back" onclick="history.go(-1); return true;" />';
	write_the_results($states,$sectors,$email);  ## SENDS FROM HERE -- BUT BEFORE THE CAPTCHA IS CORRECT (TOO EARLY!)
} // else if(!$captcha_match || !empty($usr_errors) || !empty($sys_errors) )
else
{
echo "<span class='forthem'>";
echo "<p> </p>";
echo COMPLETE_RESPONSE_TXT;
echo "</span>";
//	write_the_results($states,$sectors,$email);   *** DOES NOT SEND IT FROM HERE & IT SHOULD ***

} // end if(!$captcha_match || !empty($usr_errors) || !empty($sys_errors) )
?>
</body>
</html>

Link to comment
Share on other sites

Hmm. looks like you need to clean up that code a bit. Example:

 

function write_the_results($states,$sectors,$email) {

$today = date('m.d.Y');		
if (!is_null($states) && !is_null($_POST['sectors']) )

...

 

you pass a $sectors variable as an argument, then you check for the $_POST['sectors']?

check all the relevant variables with var_dump($variable); like so:

 

var_dump($states);
...
write_the_results($states,$sectors,$email);   //(DOES NOT SEND IT FROM HERE & IT SHOULD

other than that: all that going in and out of php mode within if blocks and all makes my eyes bleed. .... :-[

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.