I have one field (for zip code), if user enters zip code that matches one in my array and click "go" - they are redirected to the next step, if not - display "out of our service area" message. Form and php script are on the same page. How Do I do redirection inside That's what I have so far.
<form>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" value="GO" />
</form>
<?php
$allowedzips = array("10051", "10061", "10071", "10081");
$input = echo $_POST["zipcode"];
$input = str_split($input);
$message = "Out of our service area";
foreach($input as $zip) {
if (in_array($zip, $allowedzips)) {
$message //redirect goes here
break;
}
}
echo $message;
?>
A PHP redirect is quite easy to do:
header('Location: www.example.com');
exit;
Make sure to exit;, as that will stop the script from executing any further.
I think it would be better to use javascript instead of PHP for how you are looking to do this.
What I would do is add this into the head of your html
<script type="test/javascript">
function checkZipCode(zip) {
var myZipCodes=new Array("10051", "10061", "10071", "10081");
for(i=0;i<myZipCodes.length;i++) {
if (zip = myZipCodes[i]) {
form.submit;
}
else
window.location = "redirectpage";
}
}
</script>
And then on submit call and pass the zip code to checkZipCode.
I would do this in PHP to ensure that you're not tricked on the client side
Use the in_array() function to determine if the element you're looking for is within you list of valid zip codes, and redirect accordingly.
Related
Suppose you wished to create a HTML/php script which produced a webpage containing 2 buttons which, when clicked, told you which button had been clicked. The only way of doing this using php that I know of, is to create the index file
<? include('buttons.php'); ?>
<? include('clicked.php'); ?>
Where buttons.php is saved in the same directory and contains
<form method="post">
<input type="submit" name="button1" value="button1">
<input type="submit" name="button2" value="button2">
</form>
And the php script clicked.php contains
<?php
if($_POST['button1']){
echo "You have clicked button1";
}
elseif($_POST['button2']){
echo "You have clicked button2";
}
?>
This method works, but I suspect that it's not the best way of using php to get this result.
Is there a better way of doing this?
This is a server-side solution to executing PHP file however, you can approach this using client-side code and a generic handler for real-time executing and page-loading.
jQuery is free, world-wide used framework for JavaScript extensions and is easy to use.
$("#btn-one").click(function() {
$.get("clicked.php", { button: 1})
.done(function (data) {
body.innerHTML = data;
});
});
Your PHP (clicked.php) would look like this:
if(isset($_GET['button'])):
switch($_GET['button'])
{
case 1:
echo "You pressed button 1";
break;
case 2:
echo "You pressed button 2";
break;
default:
break;
}
endif;
And finally, your HTML would look like this!
<button type="button" id="btn-one">Button 1</button>
You could create your own wrapper
class Input
{
public static function fetch($key, $rules=[])
{
// ctype_alnum is used to check if the $key is alphanumeric
if (ctype_alnum($key) && isset($_POST[$key])) {
return $_POST[$key];
}
return false; // or ''
}
}
// practical use
// If string
$option = (string) Input::fetch('option');
Change the name to button[]
Then use the switch function.
you could use the rules argument to add validation rules and check for expected response types.
I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.
I have a simple input form on my site for people to enter in information for submission. The code looks like this in the case they do not enter anything:
this is form.php
if ($_POST['q']) == NULL ){
echo "Please enter your information"
The code works great, but it sends the user to form.php with the echo, where I want this to be echoed on my main page index.html right below the input box - basically so it doesn't navigate away from the page. Is this doable in php or will I need some javascript. I would have searched for ways to do this but I don't know what this method is called.
Thanks!
dont set a action in the url and it will submit to its self, if that still wont work you will need rewrite rules.
If you don't want to navigate away from the page you will need to use Javascript. Add a onSubmit to the form, and then let the function you call there return false, if the input is not complete and the form should not be submitted.
you can make it postback to itsself and then redirect the page to post.php?q=value if there is a value else echo below the input field.
<?php
$qisempty = false;
if(!empty($_POST['q']))
{
header("Location:http://../post.php?q=".$_POST['q']);
}
else
$qisempty = true;
?>
<input name="q" type="text">
<?php if($qisempty) echo "Please enter your information";?>
You can use AJAX for this thing. AJAX is great for this type of problems when you don't want to reload pages to do task in specific place or Div of HTMLpages.
For your problem, You need to create a HTML file with your form in it, and submit it via AJAX. and get your response via same AJAX.
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
This was the first page. Now Use your script in your PHP file(probably, submit_file.php) as you want and then echo the text you want in your div by validation or something.. a sample would be
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
Hope you got what you wanted...
The simplest way would be assigning the error message to a variable called (e.g $errorMsg)
the printing it on page using a echo or print function.
<?php
if ($_POST['q']) == NULL ){
$errorMsg =' Please enter your information';
}
?>
Place this code where you want the error to appear
<? print $errorMsg; ?>
hi i am using php and mysql.
i have a form to add record for user.
user should prompt when he will not select any file to upload that you want to save data without image.
Can we do that using javascript..
if any one know it would be appreciated..
Thanks in advance
You can verify the file input using javascript.
Here is an example:
function checkFile(yourForm){
var fileVal = yourForm.elements['fileField'].value;
//RegEx for valid file name and extensions.
var pathExpression = "[?:[a-zA-Z0-9-_\.]+(?:.png|.jpeg|.gif)";
if(fileVal != ""){
if(!fileVal.toString().match(pathExpression) && confirm("The file is not a valid image. Do you want to continue?")){
yourForm.submit();
} else {
return;
}
} else {
if(confirm("Do you want to continue without adding image?")) {
yourForm.submit();
} else {
return;
}
}
}
In your html
<form name="yourForm" method="post" enctype="multipart/form-data"">
<input type="file" name="fileField" />
<input type="button" value="submit" onClick="checkFile(this.form)" />
</form>
Note pathExperssion can be customized. Another thing is checking the extension is not too reliable as anyone can inject a file name as extension. Click here for other info.
just check to see if the field is empty and then ask them if that's really what they want...
if( document.forms["uploadForm"].elements["imageField"].value == ""
&& confirm("You have not added an image, are you sure you want to continue?")
)
upload();
else
doNothing();
I have found many sites that describes PRG, but no simple PHP code example.
Here's what I implemented:
The form.php has an action: validate.php.
The validate.php is never seen by the user; if validates all $_GET and, if valid writes it to database and generates the HTML of a confirmation page / if not valid, it generates the HTML of an error page explaining what is wrong.
Whichever HTML is generated get stored in a $_SESSION variable and then validate.php calls header('Location: <as appropriate>);.
The submitted.php of invalid_input.php (in case the user reads the URL) consists only of echo $_SESSION['form_html'];.
That seems to me like protection against both page reload and back button problems.
Did I goof by trying to reinvent the wheel?
Simplest scenario:
<?php
if ($_POST) {
//validate the input
if (/* input is OK */) {
// Execute code (such as database updates) here.
// Redirect to this page.
header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
exit();
}
}
?>
<html>
<!-- here goes your HTML page with a form -->
Use REQUEST_URI. Do not use PHP_SELF as in most CMS systems and frameworks PHP_SELF would refer to /index.php.
A snippet of code:
if (count($_POST)) {
// process the POST data
// your code here- so for example to log a user in, register a new account..
// ...make a payment...etc
// redirect to the same page without the POST data, including any GET info you
// want, you could add a clause to detect whether processing the post data has
// been successful or not, depending on your needs
$get_info = "?status=success";
// if not using rewrite
// header("Location: ".$_SERVER['PHP_SELF'].$get_info);
// if using apache rewrite
header("Location: ".$_SERVER['REQUEST_URI'].$get_info);
exit();
}
Browser
HTML form
method=POST
|
v
PHP app
reads $_POST
sends 303 header
|
v
Browser
receives header
redirected to
new page
|
v
PHP app
reads $_GET
does whatever
A common use is in login authentication. That's the process flow when user submits the login form. PHP app authenticates user via $_POST vars. Sends a 303 header back to browser when the user has successfully authenticated. So user is redirected to a new page.
I would like to introduce you to a method that is often used on a greater scale and in much more detail in frameworks.
What we are going to do
We have a file called index.php.
We are going to submit a form
We are going to check for this submit
We will add the POST data to a session
We will redirect the user to a confirmation page
We will display the data and let the user confirm.
We will submit, and finally process the data.
We will redirect back to index.php and show a notification.
The code
<?php
if (!isset($_SESSION)) session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['submit']) {
case 'add':
// This is where our first POST will end up
// We can perform actions such as checking the data here
// After that we will add the POST data to a session
$_SESSION['postdata'] = $_POST;
// and unset the $_POST afterwards, to prevent refreshes from resubmitting.
unset($_POST);
// Now we will redirect...
header("Location: ".$_SERVER['PHP_SELF']);
break;
case 'confirm':
// We can now insert the data into the database or email it
// Then we will unset the session and redirect back
unset($_SESSION['postdata']);
// This is to display our notification
$_SESSION['success'] = true;
// And there we go again...
header("Location: ".$_SERVER['PHP_SELF']);
break;
}
// We will exit here because we don't want the script to execute any further.
exit;
}
?>
<?php if (isset($_SESSION['success']) && $_SESSION['success'] == true): ?>
<p>Our data has been processed succesfully</p>
<?php unset($_SESSION['success']); ?>
<?php endif; ?>
<?php if (isset($_SESSION['postdata'])): ?>
<p>
You want to add the following data:<br />
<pre><?php print_r($_SESSION['postdata']); ?></pre>
Is this correct?<br />
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<button type="submit" name="submit" value="confirm">Yes</button>
</form>
</p>
<?php else: ?>
<p>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<input type="text" name="..."><br />
<button type="submit" name="submit" value="add">Add something</button>
</form>
</p>
<?php endif; ?>
Here is form.php
<?php
session_start();
// 1) _____________________________________________ POST _____________________________
if ( count($_POST) ) {
$ermsg ='';
…
check data, write some data to database(s), set error message(s) if any
…
$userdata1 = $_POST['htUserdata1'];
$userdata2 = $_POST['htUserdata2'];
…
$_SESSION['PRG'] = array('field1'=>$userdata1,'field2'=>$userdata1,…,'ermsg'=>$ermsg);
session_write_close();
header('Location: ' . $_SERVER['REQUEST_URI'].'?z',true,303);
exit;
// 2) _____________________________________________ REDIRECT ________________________
} else if ( array_key_exists('PRG',$_SESSION) ) {
$userdata1 = $_SESSION['PRG']['field1'];
$userdata2 = $_SESSION['PRG']['field2'];
…
$ermsg = $_SESSION['PRG']['ermsg'];
unset($_SESSION['PRG']);
// 3) _____________________________________________ GET ______________________________
} else {
…
retrieve data from database(s)
…
$userdata1 = dbGet1();
$userdata2 = dbGet2();
…
$ermsg = '';
}
// 4) _____________________________________________ DISPLAY _________________________
?>
<!DOCTYPE html>
<html lang="fr">
…
<form method="post" action="form.php" accept-charset="utf-8">
<input id="htUserdata1" name="htUserdata1" type="text"/>
<input id="htUserdata2" name="htUserdata2" type="text"/>
…
</form>
<script language="javascript">
"use strict";
<?php
$G['htUserdata1'] = $userdata1;
$G['htUserdata2'] = $userdata2;
…
$G['ermsg'] = $ermsg;
$myJSON = json_encode($G);
echo "var G=$myJSON;";
?>
document.getElementById('htUserdata1').value = G.htUserdata1;
document.getElementById('htUserdata2').value = G.htUserdata2;
…
if ( G.ermsg !=='') alert(G.ermsg);
</script></body></html>
Caller.htm
<form method="post" action="Callee.php?Query1">
<input type="text" name="PostData" />
<input type="submit" value="Go" />
</form>
Callee.php (Is called twice.)
if ($_POST) {
header("Location: ". $_SERVER['REQUEST_URI']. 'Query2');
// PART1: Use $_POST and $_GET to execute database updates here...
// Now any display (i.e. echo or print) will come after the header.
// ...
die; // When done, GET 'myself' to execute PART2 below.
}
// PART2: Results page goes here...
echo 'PART 2 display output: '; var_dump($_GET);
Notice there are two query strings involved
Look what var_dump says about $_GET:
PART 2 display output: array(1) { ["Query1Query2"]=> string(0) "" }
Issues with putting header at the end of the POST section like this:
header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); die;
The php manual says: "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."
However if you need to build 'Query2' based on what happens in the POST section, it may need to be at the bottom of the POST section. This is ok, so long as you don't try to insert any echo's above it, not even for testing.