Display alert box upon form submission - php

So I have these two pages: pageOne.php and pageTwo.php.The form is in pageOne.php:
<form method="post" action="pageTwo.php"> .... </form>
and doing all the data collection-validation-insertion and sending out mails in pageTwo.php (the reason i'm doing everything in two separate pages is to avoid the data re-submission upon page refresh...this was the easiest way for me to handle the issue). So far everything is working perfectly.
Now, I want to display a success/failure message using alert box after the form submission and tried few things w/o any luck. E.g. when I tried THIS solution on pageTwo.php, no pop up box shows up and I think that's because I have this header on top of that page
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
if( $_POST ) {
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
echo "<script type='text/javascript'>alert('It worked!')</script>";
}else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
And when tried this second solution in pageOne.php, I get the alert box popping up every time i refresh the page and get the failure message even though the data had been inserted into database and mails were sent out. pageOne.php:
<html>
<body>
<?php
if( $GLOBALS["posted"]) //if($posted)
echo "<script type='text/javascript'>alert('It worked!')</script>";
else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<form method="post" action="pageTwo.php"> .... </form>
</body>
and in pageTwo.php:
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
$posted = false;
if( $_POST ) {
$posted = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
} ?>
Why isn't this simple thing working :( ? is there any easy way to fix it? Thank you!!
UPDATE
So I have made some changes according to drrcknlsn's sugession and this is what I have so far....pageOne.php:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
echo "<script type='text/javascript'>alert('It worked!')</script>";
} else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<html> <body>
<form method="post" action="pageTwo.php"> .... </form>
</body> </html>
and pageTwo.php:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
header('Location: http://TestPages.com/pageOne.php');
exit;
} ?>
With these changes now the page's redirection and success message is working, but i get the failure msg every time i open/refresh the page (i know that's because the session key is not set yet)...how can i avoid that? Thanks again!!

First, a couple points:
Variables (even globals) are not shared across requests like you're trying to do in your bottom example. In order for $posted to be accessible in both pages, you must persist it in some way. Usually this involves setting a session variable (e.g. $_SESSION['posted'] = true;), but it could also be persisted in a cookie, in a database, on the filesystem, in a cache, etc.
Use something like if ($_SERVER['REQUEST_METHOD'] === 'POST') instead of if ($_POST). While the latter is probably safe in most cases, it's better to get in the habit of using the former because there exists an edge case where $_POST can be empty with a valid POST request, and it may be a hard bug to track down.
One potential pattern to solve your problem using the above advice:
pageOne.php:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
}
?>
...
<form>...</form>
pageTwo.php:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
// do form processing stuff here
header('Location: pageOne.php');
exit;
}
// show an error page here (users shouldn't ever see it, unless they're snooping around)

It looks like it's a scope problem.
use:
global $posted = true;
http://php.net/manual/en/language.variables.scope.php

Related

How to display error messages on redirect?

It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting

Google reCAPTCHA g-recpatcha-response has no value in PHP

p.s: I gave up on this as I found no solution and implemented my own php captcha that worked a treat :) - http://www.the-art-of-web.com/php/captcha/
I have spent many hours & days trying to solve this problem but I cannot seem to figure it out. I have read a lot of different tutorials & questions online.
Just to keep in mind, my PHP level is fairly basic.
I cannot seem to get the 'g-recaptcha-response' $_POST value in my php file.
I have summarised the important code needed below...
File 1: contact.php
Before Head Tags
<?php
session_start(); // start php session
// Setup session variables to save the form data
if( isset($_SESSION['contact_form_values']) ){
extract( $_SESSION['contact_form_values'] );
}
include('contactengine.php');
?>
In Head Tags
<script src='https://www.google.com/recaptcha/api.js'></script><!-- reCAPTCHA form -->
Between the Form tags
Action="" so that it posts to itself which has the contactengine.php file included so that it runs through only when the user clicks the submit button?
<form class="contactform" method="POST" action="">
<div class="g-recaptcha" data-sitekey="6Lc92gkTAAAAAFKjZEOlY0cg9G8ubmlVoC13Xf3T"></div>
File 2: contactengine.php
Between this
if($_SERVER["REQUEST_METHOD"] == "POST")
I have
if( isset( $_POST['g-recaptcha-response'] ) ){
$captchaResponse = $_POST['g-recaptcha-response'];
}
Now this is the point where the variable $captchaResponse isn't being populated as I output the value of it like this:
if( !$captchaResponse ){ // check the POST recaptcha response value
$resultMsg = 'Please check the captcha form. - '.$captchaResponse;
}
Therefore I get no visible output of the response code in the $resultMsg string.
The only thing I could think is effecting it, is including the contactengine.php file at the beginning in contact.php. And having the action as ="". But this is what the tutorial guided me to do. So maybe not...
I used http://www.9lessons.info/2014/12/google-new-recaptcha-using-php-are-you.html as the guide.
Thanks a lot in advanced!
You're nearly there! You just need to query Google's API.
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
}
if (!$captcha) {
// Captcha wasn't checked, do something...
exit;
}
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRETKEYGOESHERE&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if ($response.success == false) {
// Captcha failed! Do something!
} else {
// Captcha is valid! Do something else!
}
Replace SECRETKEYGOESHERE with your actual secret key, and you're set!

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

PHP - Check if page refresh or post data on the same page

Is there any way to know if the page was refreshed or data was posted data on the same page?
To be little more specific:
I have to post data on the same page.
This affects the where condition of the query.
If the page was refreshed, then the where condition must be 1.
Otherwise, where condition contains some id to get specific data from
the table.
Your best bet is to use PHP sessions, along with your submitted data in $_POST. Let's presume for this example you have the following form:
<form action="this_page.php" method="post">
<input type="text" name="important-info" />
<input type="submit" value="Submit" />
</form>
Then elsewhere in the same page is the PHP code:
<?php
// example code
session_start();
if (!isset($_SESSION['previousVisitor']) && isset($_POST['important-info'])) {
// this is a new visitor who has submitted the form
$_SESSION['previousVisitor'] = true;
// where is based on $_POST['important-info']
} else () {
// where is 1
}
// close the session after you do what you need - this stops large pages causing hang
session_destroy();
Please note that they can clear this session variable by deleting their cookies.
on the top of the page just include
if(isset($_POST['name']) && $_POST['name']!=''){
//your code goes here
}
I suggest you to check request
//Here goes the code
session_start();
$counter = 0;
$counter = (isset($_SESSION['param'])) ? $counter++ : 0;
if($counter == 0)
echo "data GET or POST";
else
echo "refreshed";
** If you want only POST param, use $_POST instead of $_REQUEST

How should I handle the case in which a username is already in use?

To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.

Categories