Solved

Screen prompt while PHP code runs

Posted on 2012-03-30
19
363 Views
Last Modified: 2012-04-05
I'm developing a meeting registration system with 3 basic pages.  Page 1 the registrant inputs information.  Page 2 the registrant can view and confirm the information.  Then the user clicks an input button that calls a PHP page (page 3).  This PHP page stores the information into the database.  The problem is that when the user clicks the button, Page 2 stays on the screen until page 3 is finished running the PHP code.  This could be a few seconds and some users might click the button again thinking they didn't click it the first time.

How can I have a prompt come up to show that the user clicked the button while the PHP code runs?

I'm using a 'controller' file to include the pages.  This code runs in the controller page when the button clicked is...

if (isset($_GET['btn_register']))
{
      include 'formStoreCode.php';
      exit();
}

Is there a way insert a line of code before the include statement that would clear the screen and put up a text prompt?

Thanks,

Steve
0
Comment
Question by:stkoontz
  • 9
  • 6
  • 4
19 Comments
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37789874
You would have to go at it with a different approach.
You'd have to use ajax to send the form, so that the page doesn't reload.
Something like what is shown here:
http://jquery.malsup.com/form/

Then, your page number 2 will become the last page. Your page 3 will be just the script that cares care of business and echoes a message back to the javascript in page number 2.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37790790
Thanks for the quick reply.

I tried the ajax code from your link.  The screen didn't clear when I clicked the button.  The php code (page 3) ran fine, and the ajax prompt came up after the code ran.  Any way to clear the screen when the button is clicked?

Thanks,

steve
0
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37790999
By "clear the screen" you mean, jump to a different page?
If so, then, add the following line after the "alert" command in your javascript:

window.location="http://example.com";

the "alert" command halts execution until the user clicks the alert button, so as soon as the user closes the alert, the window is redirected.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37791078
Yes.  Jump to a different page is probably a better way to put it.  But I don't want the user to have to click the alert button for the code to run.

I'll try to explain again.
When the user clicks the button on page 2, the PHP code on page 3 runs. I'd like to be able to put text on page 3 telling the user that there will be a brief delay.  When I put text on page 3, either regular HTML or using the echo command, the text doesn't show up because the code is running.

Is that more clear?

Thanks for sticking with me on this.

Steve
0
 
LVL 7

Accepted Solution

by:
designatedinitializer earned 500 total points
ID: 37791181
First, in "page2.php" you've got an HTML form that posts to "page3.php"
However, you don't want the form to be posted -- because that would load a new page.
So, you will have to take whatever data processing you are doing on "page3.php" and put it in another page, let's call it "page2-process.php". And in "page3.php" you simply show a success message to the user.

ok, let's start with that simple example.
You can then change it to accomodate your needs.
Here's your "page2.php":
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm({
                 beforeSubmit: function(){ $('#loadingMessage').show(); },
                 success: function(){ window.location = "http://example.com/page3.php"; }
            })
        });
    </script> 
</head> 
<body>
<div id="loadingMessage" style="display:none;" >
    Your data is being sent to the server...<br/>
    DON'T reload the page... stay calm... don't move... wait...
</div>

<form id="myForm" action="page2-process.php" method="post"> 
    Name: <input type="text" name="name" /> 
    Comment: <textarea name="comment"></textarea> 
    <input type="submit" value="Submit Comment" /> 
</form>
</body>

Open in new window


And here's your "page2-process.php". Remember to delete the "sleep(5)" in your version:
<?php
sleep(5); // I put this in just to give you time to read the message
// Do whatever you want to do...
echo "We're done"; // output something
?>

Open in new window


Then, "page3.php" will have the final result.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37791286
Thanks for the sample code.  I got your example to work, but couldn't get it to work in my code.  I'm going live on Monday and don't want to risk digging into my code further for fear of breaking something else.

If there isn't another solution presented by Monday, then I'll give you the points since, if I had more time, we could get yours to work.

If it becomes a problem with people clicking twice, then I'll re-visit your solution.

Thanks,

Steve
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37793231
It sounds to me like the real issue here is that page3 (the data base update) runs much too slowly.  My expectation would be that any information a human being can type into an HTML form would be written into a data base in a fraction of a second.  Do you know where the delay is coming from in the page3 script?  Are you uploading large images into the data base or something like that?  

If you want to isolate the performance issues in page3, you might add some timing instrumentation to the script.  This little class might be able to help you find where the page3 script is spending its time.  Some examples of use are shown below line 145.
<?php // RAY_class_Stopwatch.php
error_reporting(E_ALL);


// DEMONSTRATE A SCRIPT TIMER FOR ALL OR PART OF A SCRIPT PHP 5+
// MAN PAGE http://php.net/manual/en/function.microtime.php


class StopWatch
{
    protected $a; // START TIME
    protected $s; // STATUS - IF RUNNING
    protected $z; // STOP TIME

    public function __construct()
    {
        $this->a = array();
        $this->s = array();
        $this->z = array();
    }

    // A METHOD TO REMOVE A TIMER
    public function reset($name='TIMER')
    {
        // RESET ALL TIMERS
        if ($name == 'TIMER')
        {
            $this->__construct();
        }
        else
        {
            unset($this->a[$name]);
            unset($this->s[$name]);
            unset($this->z[$name]);
        }
    }

    // A METHOD TO CAPTURE THE START TIME
    public function start($name='TIMER')
    {
        $this->a[$name] = microtime(TRUE);
        $this->z[$name] = $this->a[$name];
        $this->s[$name] = 'RUNNING';
    }

    // A METHOD TO CAPTURE THE END TIME
    public function stop($name='TIMER')
    {
        $ret = NULL;

        // STOP ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                // IF THIS TIMER IS STILL RUNNING, STOP IT
                if ($this->s[$name])
                {
                    $this->s[$name] = FALSE;
                    $this->z[$name] = microtime(TRUE);
                }
            }
        }

        // STOP ONLY ONE OF THE TIMERS
        else
        {
            if ($this->s[$name])
            {
                $this->s[$name] = FALSE;
                $this->z[$name] = microtime(TRUE);
            }
            else
            {
                $ret .= "ERROR: CALL TO STOP() METHOD FOR '$name' IS NOT RUNNING";
            }
        }

        // RETURN AN ERROR MESSAGE, IF ANY
        return $ret;
    }

    // A METHOD TO READ OUT THE TIMER(S)
    public function readout($name='TIMER', $dec=3, $m=1000, $eol=PHP_EOL)
    {
        $str = NULL;

        // GET READOUTS FOR ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                $str .= $name;

                // IF THIS TIMER IS STILL RUNNING UPDATE THE END TIME
                if ($this->s[$name])
                {
                    $this->z[$name] = microtime(TRUE);
                    $str .= " RUNNING ";
                }
                else
                {
                    $str .= " STOPPED ";
                }

                // RETURN A DISPLAY STRING
                $lapse_time = $this->z[$name] - $start_time;
                $lapse_msec = $lapse_time * $m;
                $lapse_echo = number_format($lapse_msec, $dec);
                $str .= " $lapse_echo";
                $str .= $eol;
            }
            return $str;
        }

        // GET A READOUT FOR ONLY ONE TIMER
        else
        {
            $str .= $name;

            // IF THIS TIME IS STILL RUNNING, UPDATE THE END TIME
            if ($this->s[$name])
            {
                $this->z[$name] = microtime(TRUE);
                $str .= " RUNNING ";
            }
            else
            {
                $str .= " STOPPED ";
            }


            // RETURN A DISPLAY STRING
            $lapse_time = $this->z[$name] - $this->a[$name];
            $lapse_msec = $lapse_time * $m;
            $lapse_echo = number_format($lapse_msec, $dec);
            $str .= " $lapse_echo";
            $str .= $eol;
            return $str;
        }
    }
}



// DEMONSTRATE THE USE -- INSTANTIATE THE STOPWATCH OBJECT
$sw  = new Stopwatch;

// SET A STOPWATCH NAME THAT REFLECTS THE PARTS OF THE SCRIPT WE WANT TO TIME
$g_timer = 'GOOGLE TIMER';

// START A TIMER TO GET ELAPSED TIME FOR A CALL TO GOOGLE
$sw->start($g_timer);

// PERFORM SOME ACTIVITY THAT YOU WANT TO TIME (READS GOOGLE WEB PAGE)
$page = 'http://google.com';
$html = file_get_contents($page);

// GET A READOUT OF THE TIMER WHILE IT IS STILL RUNNING
echo nl2br($sw->readout($g_timer));
echo "<br/>" . PHP_EOL;

// PERFORM SOME OTHER ACTIVITY (READS GOOGLE WEB PAGE AGAIN)
$page = 'http://google.com';
$html = file_get_contents($page);

// STOP THE TIMER AND GET A READOUT WITH SHORT DECIMALS
$x = $sw->stop($g_timer);
echo nl2br($sw->readout($g_timer, 1));
echo "<br/>" . PHP_EOL;




// START A SECOND TIMER
$y_timer = 'YAHOO TIMER';
$sw->start($y_timer);

// PERFORM SOME OTHER ACTIVITY THAT YOU WANT TO TIME
$page = 'http://yahoo.com/';
$html = file_get_contents($page);

// REPORT THE STOPWATCHES CONTENT (ONE IS STOPPED AND ONE IS STILL RUNNING)
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";

// STOP ALL OF THE STOPWATCHES
$sw->stop();

// REPORT THE STOPWATCHES CONTENT AGAIN
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// TRY TO STOP A TIMER THAT IS NOT RUNNING
$x = $sw->stop($g_timer);
var_dump($x);
echo "<br/>" . PHP_EOL;
echo "<br/>" . PHP_EOL;



// START THIS TIMER OVER AGAIN
$sw->start($y_timer);

// PERFORM SOME OTHER ACTIVITY THAT YOU WANT TO TIME
$page = 'http://weather.yahoo.com/';
$html = file_get_contents($page);

// REPORT THE STOPWATCHES CONTENT
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// REMOVE ONE OF THE STOPWATCHES
$sw->reset($g_timer);

// REPORT THE STOPWATCHES CONTENT
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// REMOVE ALL OF THE STOPWATCHES
$sw->reset();
echo "ALL STOPWATCHES HAVE BEEN REMOVED";

// REPORT THE STOPWATCHES CONTENT (SHOWS NOTHING)
echo nl2br($sw->readout());

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";

Open in new window

HTH, ~Ray
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37796530
I'm not uploading any images - just inserting about 50 variables into the database.  The system is also sending out up to 3 emails.

A sample of the code I'm using to get the variables is below.

$varid_class = mysqli_real_escape_string($link, $_POST['id_class']);

Is there quicker code that could be used?  Some prompts are from dropdowns and radio buttons.  Would I need to "escape" that input and would it speed it up much if I didn't?

Thanks,

Steve
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37796588
Hi, Steve.  That looks right to me.  How many queries are used to insert the 50 variables?  How many tables are involved?

As far as escaping goes, you need to escape EVERY external input.  External input is an attack vector.  You cannot trust the client side to send you valid information since 100% of the input you receive can be toxic at any time without warning.  Hacker-generated data fields do not go through you client-side processing.

If you want to post the entire action script for page3 I will be glad to take a look and see if there is anything obvious.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Author Comment

by:stkoontz
ID: 37796918
Thanks for taking a look at the code.  Here's the page that inserts the data.  All the data is brought over from page 2 using form variables.  (Does that mean there aren't any 'queries' used to insert the variables?) There's only 1 table involved on this page.

I really appreciate your help.

<?php
session_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
	 
	$securimage = new Securimage();

if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  // you should handle the error so that the form processor doesn't continue

  // or you can use the following code if there is no validation or you do not know how
  echo "The security code entered was incorrect.<br /><br />";
  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
  exit;
}
?>

<?php

//Insert information into database

$varid_class = mysqli_real_escape_string($link, $_POST['id_class']);

$varreg_fee = mysqli_real_escape_string($link, $_POST['reg_fee']);

$varsig_auth=mysqli_real_escape_string($link, $_POST['sig_auth']);
$varsig_ref=mysqli_real_escape_string($link, $_POST['sig_ref']);

$varid_registrant = mysqli_real_escape_string($link, $_POST['id_registrant']);

$varid_church = mysqli_real_escape_string($link, $_POST['id_church']);
$varlc_first_name = mysqli_real_escape_string($link, $_POST['lc_first_name']);
$varlc_last_name = mysqli_real_escape_string($link, $_POST['lc_last_name']);
$varlc_email = mysqli_real_escape_string($link, $_POST['lc_email']);
$varlc_password = mysqli_real_escape_string($link, $_POST['lc_password']);

$varfname = mysqli_real_escape_string($link, $_POST['fname']);
$varlname = mysqli_real_escape_string($link, $_POST['lname']);

$vargender = mysqli_real_escape_string($link, $_POST['gender']);
$varemail_address = mysqli_real_escape_string($link, $_POST['email_address']);

$varbreakfast = mysqli_real_escape_string($link, $_POST['breakfast']);
$vararrival = mysqli_real_escape_string($link, $_POST['arrival']);

$varprimary_phone = mysqli_real_escape_string($link, $_POST['primary_phone']);
$varsecondary_phone = mysqli_real_escape_string($link, $_POST['secondary_phone']);

$varparent_phone = mysqli_real_escape_string($link, $_POST['parent_phone']);
$varparent_first = mysqli_real_escape_string($link, $_POST['parent_first']);
$varparent_last = mysqli_real_escape_string($link, $_POST['parent_last']);
$varparent_email_address = mysqli_real_escape_string($link, $_POST['parent_email_address']);
$varparent_phone = mysqli_real_escape_string($link, $_POST['parent_phone']);

$varcenews_signup = mysqli_real_escape_string($link, $_POST['cenews_signup']);

$varaddress1 = mysqli_real_escape_string($link, $_POST['address1']);
$varaddress2 = mysqli_real_escape_string($link, $_POST['address2']);
$varcity = mysqli_real_escape_string($link, $_POST['city']);
$varstate = mysqli_real_escape_string($link, $_POST['state']);
$varzip = mysqli_real_escape_string($link, $_POST['zip']);
$varcountry = mysqli_real_escape_string($link, $_POST['country']);

$vargrade_in_school = mysqli_real_escape_string($link, $_POST['grade_in_school']);
$vartshirt_size = mysqli_real_escape_string($link, $_POST['tshirt_size']);

$varhousing_with = mysqli_real_escape_string($link, $_POST['housing_with']);

$varoccupation = mysqli_real_escape_string($link, $_POST['occupation']);
$varhow_traveling = mysqli_real_escape_string($link, $_POST['how_traveling']);
$varvolunteer_read_faqs = mysqli_real_escape_string($link, $_POST['volunteer_read_faqs']);
$varfamily_serving = mysqli_real_escape_string($link, $_POST['family_serving']);
$varnanny_read = mysqli_real_escape_string($link, $_POST['nanny_read']);

$vartotal_owe = mysqli_real_escape_string($link, $_POST['total_owe']);
$varpaymethod = mysqli_real_escape_string($link, $_POST['paymethod']);

$varskill_games = mysqli_real_escape_string($link, $_POST['skill_games']);
$varskill_basketball = mysqli_real_escape_string($link, $_POST['skill_basketball']);
$varskill_volleyball = mysqli_real_escape_string($link, $_POST['skill_volleyball']);
$varskill_soccer = mysqli_real_escape_string($link, $_POST['skill_soccer']);
$varskill_dodgeball	 = mysqli_real_escape_string($link, $_POST['skill_dodgeball']);
$varskill_other = mysqli_real_escape_string($link, $_POST['skill_other']);
$varskill_writing = mysqli_real_escape_string($link, $_POST['skill_writing']);
$varskill_photographer = mysqli_real_escape_string($link, $_POST['skill_photographer']);
$varskill_av = mysqli_real_escape_string($link, $_POST['skill_av']);
$varskill_nac_vocal	 = mysqli_real_escape_string($link, $_POST['skill_nac_vocal']);
$varskill_nac_keyboard = mysqli_real_escape_string($link, $_POST['skill_nac_keyboard']);
$varskill_nac_instrumental = mysqli_real_escape_string($link, $_POST['skill_nac_instrumental']);
$varskill_nac_art = mysqli_real_escape_string($link, $_POST['skill_nac_art']);
$varskill_nac_writing = mysqli_real_escape_string($link, $_POST['skill_nac_writing']);
$varskill_nac_oratory = mysqli_real_escape_string($link, $_POST['skill_nac_oratory']);

$varip_address=$_SERVER["REMOTE_ADDR"]; 

	$varreg_date = date('y/m/d');
	$varreg_year="2012";

//Generate random password
	$length = strlen($varlname);
	$characters = 3;
	$start = $length - $characters;
	$varfirst = substr($varlname , $start ,$characters);

	$varmiddle=rand(1, 10000);

	$length = strlen($varfname);
	$characters = 3;
	$start = $length - $characters;
	$varlast = substr($varfname , $start ,$characters);

	$varpassword=$varfirst . $varmiddle . $varlast;

//Insert information into database
	$sql = 'INSERT INTO registrants SET 
			id_registrant="' . $varid_registrant . '",
			id_church="' . $varid_church . '",
			sig_auth="' . $varsig_auth . '",
			sig_ref="' . $varsig_ref . '",
			housing_with="' . $varhousing_with . '",
			id_class="' . $varid_class . '",				
			reg_date="' . $varreg_date . '",
			reg_year="' . $varreg_year . '",
			password="' . $varpassword . '",			
			fname="' . $varfname . '",
			lname="' . $varlname . '",
			gender="' . $vargender . '",
			address1="' . $varaddress1 . '",
			address2="' . $varaddress2 . '",
			city="' . $varcity . '",			
			state="' . $varstate . '",
			zip="' . $varzip . '",
			country="' . $varcountry . '",			
			primary_phone="' . $varprimary_phone . '",
			secondary_phone="' . $varsecondary_phone . '",			
			parent_phone="' . $varparent_phone . '",
			parent_first="' . $varparent_first . '",
			parent_last="' . $varparent_last . '",
			parent_email_address="' . $varparent_email_address . '",
			cenews_signup="' . $varcenews_signup . '",			
			email_address="' . $varemail_address . '",
			grade_in_school="' . $vargrade_in_school . '",
			tshirt_size="' . $vartshirt_size . '",
			occupation="' . $varoccupation . '",
			how_traveling="' . $varhow_traveling . '",
			volunteer_read_faqs="' . $varvolunteer_read_faqs . '",
			family_serving="' . $varfamily_serving . '",
			nanny_read="' . $varnanny_read . '",			
			reg_fee="' . $varreg_fee . '",
			breakfast="' . $varbreakfast . '",			
			arrival="' . $vararrival . '",
			total_owe="' . $vartotal_owe . '",
			balance="' . $vartotal_owe . '",			
			skill_games="' . $varskill_games . '",
			skill_basketball="' . $varskill_basketball . '",
			skill_volleyball="' . $varskill_volleyball . '",
			skill_soccer="' . $varskill_soccer . '",
			skill_dodgeball="' . $varskill_dodgeball . '",
			skill_other="' . $varskill_other . '",
			skill_writing="' . $varskill_writing . '",
			skill_photographer="' . $varskill_photographer . '",
			skill_av="' . $varskill_av . '",			
			skill_nac_vocal	="' . $varskill_nac_vocal . '",
			skill_nac_keyboard="' . $varskill_nac_keyboard . '",
			skill_nac_instrumental="' . $varskill_nac_instrumental . '",			
			skill_nac_art="' . $varskill_nac_art . '",
			skill_nac_writing="' . $varskill_nac_writing . '",
			skill_nac_oratory="' . $varskill_nac_oratory . '",
			ip_address="' . $varip_address . '",
			paymethod="' . $varpaymethod . '"';


	if (!mysqli_query($link, $sql))
	{
		$output = 'Error adding record: ' . mysqli_error($link);
		include 'output.php';
		exit();
	}
	
?>

<?php
//store variables to send email and show on confirmation page
$_SESSION['ses_fname']=$varfname;
$_SESSION['ses_lname']=$varlname;
$_SESSION['ses_id_registrant']=$varid_registrant;
$_SESSION['ses_id_class']=$varid_class;
$_SESSION['ses_total_owe']=$vartotal_owe;
$_SESSION['ses_email_address']=$varemail_address;
$_SESSION['ses_parent_email_address']=$varparent_email_address;
$_SESSION['ses_cenews_signup']=$varcenews_signup;
$_SESSION['ses_password']=$varpassword;
$_SESSION['ses_lc_first_name'] = $varlc_first_name;
$_SESSION['ses_last_name'] = $varlc_last_name;
$_SESSION['ses_lc_email'] = $varlc_email;
$_SESSION['ses_lc_password'] = $varlc_password;
$_SESSION['ses_id_church'] = $varid_church;

?>
<?php
 header( 'Location: sendemails.php');
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37797051
There may be issues with the redirect at the bottom of the script, but I cannot see any reason for this script to run slowly.  It's basically just copying strings from one variable to another.  Where does the data base connection occur?
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37797359
The redirect (sendemails.php) runs code that takes the session variables and sends out up to 3 emails.  I'm using PHPmailer.  

Sendemails.php also connects to mailchimp.com using their API to sign the registrant up for an email list.

The delay is only about 4 seconds, but enough that it could make someone wonder if they clicked the button.

The data base connection occurs once through this controller file.

<?php

include_once $_SERVER['DOCUMENT_ROOT'] .
	'/includes/magicquotes.inc.php';

include_once $_SERVER['DOCUMENT_ROOT'] .
	'/includes/db.inc.php';

include_once $_SERVER['DOCUMENT_ROOT'] .
	'/includes/helpers.inc.php';	

$result = mysqli_query($link, 'SELECT fname, lname FROM registrants');

if (!$result)
{
	$output = 'Error fetching registration: ' . mysqli_error($link);
	include 'output.php';

	exit();
}

if (!isset($_GET['btn_next']) && !isset($_GET['btn_register']))
{
	 include 'page1.php';
	 exit();
}

if (isset($_GET['btn_next']))
{
	include 'page2.php';
	exit();
}

if (isset($_GET['btn_register']))
{
	include 'page3.php';
	exit();
}
?>

Open in new window


Here's the database connection code

<?php
$link = mysqli_connect('host', username', 'password');
if (!$link)
{
	$error = 'Unable to connect to the database server.';
	include 'http://registration.cenational.org/output.php';
	exit();
}

if (!mysqli_set_charset($link, 'utf8'))
{
	$output = 'Unable to set database connection encoding.';
	include 'http://registration.cenational.org/output.php';
	exit();
}

if (!mysqli_select_db($link, 'table'))
{
	$error = 'Unable to locate the database.';
	include 'http://registration.cenational.org/output.php';
	exit();
}
?>

Open in new window


Do you see anything that could be coded better?

Thanks,

Steve
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37797455
I don't really see anything in what's been posted here so far, but I am wondering about the idea of calling an external API in an inline script.  It may be that the delay is coming from the MailChimp API.  I think I would want to time that API (and any others that you might be using) and if it is slow, you might want to consider decoupling the API call.

Let's go back to the earlier code snippet.  Here are lines 180 through the end at line 202
?>

<?php
//store variables to send email and show on confirmation page
$_SESSION['ses_fname']=$varfname;
$_SESSION['ses_lname']=$varlname;
$_SESSION['ses_id_registrant']=$varid_registrant;
$_SESSION['ses_id_class']=$varid_class;
$_SESSION['ses_total_owe']=$vartotal_owe;
$_SESSION['ses_email_address']=$varemail_address;
$_SESSION['ses_parent_email_address']=$varparent_email_address;
$_SESSION['ses_cenews_signup']=$varcenews_signup;
$_SESSION['ses_password']=$varpassword;
$_SESSION['ses_lc_first_name'] = $varlc_first_name;
$_SESSION['ses_last_name'] = $varlc_last_name;
$_SESSION['ses_lc_email'] = $varlc_email;
$_SESSION['ses_lc_password'] = $varlc_password;
$_SESSION['ses_id_church'] = $varid_church;

?>
<?php
 header( 'Location: sendemails.php');
?>

Open in new window

This gets my attention because if you really have the script organized like that, the sendemails.php script will not get executed.  The reason for this is the nature of the header() function.  It is a law of HTTP that all headers must come first and must be complete before any browser output, including invisible white space.  Perhaps your script starts the output buffers somewhere in a segment that we have not seen yet?  If not, the header() is almost certainly failing because there is an invisible end-of-line character after line 199 and before line 200.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37797662
By "Decoupling the API Call" do you mean to put it somewhere else in the program?

What are 'output buffers'?  ("Perhaps your script starts the output buffers somewhere in a segment that we have not seen yet?")

The emails are going out and the data is being written to the database, so sendmails.php is running.  Is there better code to use to redirect to the sendmails.php page?

Thanks for going over-and-above to help me work through this.

Steve
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37797756
That's a lot of questions!  But I'll try to help.  You can learn about output buffers here:
http://php.net/manual/en/function.ob-start.php

Decoupling the API call is a little more complicated.  Let me try to explain from my own experience.  I use an external API to get the IP-to-location needed to build this web page.
http://www.landonbaseball.com/site_visitors.php

The external API is not always lightning fast.  I need to feed it the client IP address and record the IP address in my data base.  So instead of waiting while the API runs, I use a code block like this in the page header
// RECORD VISITOR IP ADDRESS
$ipa = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : NULL;
if ($ipa)
{
    $paa = array('ipa' => $ipa);
    ob_start();
    $xyx = curl_post('http://www.landonbaseball.com/call_geoio.php', $paa, 1, TRUE);
    if (!$xyx)
    {
        $xyz = ob_get_clean();
    }
    unset($xyz);
}

Open in new window

The curl_post() function makes a POST-method request to a script that can run asynchronously.  It passes the parameter list and forces a timeout in no more than one second.  If anything comes back from the asynchronous script into the $xyz variable, I discard it.  There is a small chance that the asynch script will complete in less than a second before the timeout.  I do not want its output in this script.  And the asynchronous script will log errors so I can look at those whenever I have spare time.

Here is the curl_post function
function curl_post($url, $post_array, $timeout=1, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = '';
    foreach ($post_array as $key => $val)
    {
        $post_string .= urlencode($key) . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL,            $url         );
    curl_setopt( $curl, CURLOPT_HEADER,         FALSE        );
    curl_setopt( $curl, CURLOPT_POST,           TRUE         );
    curl_setopt( $curl, CURLOPT_POSTFIELDS,     $post_string );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout     );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE         );

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);

    // ON POSSIBLE FAILURE
    if (!$htm)
    {
        // ON CERTAIN FAILURE
        if (!$err)
        {
            // PROCESS ERRORS HERE
            if ($error_report)
            {
                echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
                echo "<pre>\n";
                var_dump($inf);
                echo "</pre>\n";
            }
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS
    curl_close($curl);
    return $htm;
}

Open in new window

Regarding this, Is there better code to use to redirect to the sendmails.php page? I find it hard to believe that I am really looking at a script that works, unless perhaps something in your server configuration is buffering the output.  I think if it were my script I would not have those Stop-PHP-Start-PHP sequences.  They do not add value.

Anyway, going forward here is what I would do.  Insert the script timer into your web pages and use it to time various parts of the pages.  You can use it to time the call to the API, to time the connect and select of the data base, to time the execution of the query, etc.  Once you know what those times are, you will know where to concentrate your attention in your efforts to improve performance.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 37798252
I commented out various parts of the page and found that the lag is in the sending of the emails not the mailchimp call or the storing of the data.

When I commented out the below code only, the script ran nearly when I clicked the button.

if(!$mail->Send())
{
 echo "Message could not be sent. <p>";
   echo "Please contact cenational with this error message: " . $mail->ErrorInfo;
 exit;
}

With the above code sending out the email, it takes about 10 seconds for the script to run.

The curl_post function is far deeper than I can get into for this system.

I removed the Stop-PHP-Start-PHP sequences to clean up the code.

Knowing that the speed problem is in the emailing, I'll have to think about it overnight.  (I'm on a shared webhost, so changing email programs isn't an option.)

Thanks again for all the help.  

Steve
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37798301
Interesting.  Maybe you could write a log record for the mail that needs to be sent, and just run a CRON job to send the mails.  You can run a CRON once a minute.  There will be negligible impact on server performance (probably will not be noticed at all) and it will get your script decoupled from the slow part of things.

Anyway, best of luck with it, ~Ray
0
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37798379
Steve:
Before embarking on a wild goose chase,you should know that 3/4 seconds for all this is normal for a cheap shared server to do all this posting, socket connections and redirect.

Do you want to optimize you code for performance? If so, my advice is for you to open another question. This question is titled "Screen prompt while PHP code runs". When other people come find this question by searching the experts-exchange, they may find all this speculation useful (or not), but it will be most useful to them:
1. If it is properly titled and tagged;
2. If a real solution is provided, which can only be If...
3. ...it attracted the experts in the field (experts who will find your question in case you titled and tagged properly in the first place...)
0
 
LVL 2

Author Closing Comment

by:stkoontz
ID: 37814134
Although Ray had some good advice about optimizing the code, designatedinitializer has the answer to my question.

Thanks to both of you for going above and beyond to try to help me.

Steve
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now