Php redirect to page if statement - php

I'm trying to make you redirect to the successful page after succesfully registering but whenever I click the register button I get redirected instantly even if all the input's are empty
if(isset($_POST["registration"])){
if(!empty($_POST["gender"])
and !empty($_POST["username"])
and !strlen($_POST["username"]) < 3
and !empty($_POST["email"])
and !email($_POST["email"])
and !empty($_POST["emailver"])
and !verification($_POST["email"],$_POST["emailver"])
and !empty($_POST["password"])
and !strlen($_POST["password"]) < 8
and strlen($_POST["password"]) < 25
and checkUppercase($_POST["password"])
and checkLowercase($_POST["password"])
and checkNumber($_POST["password"])
and !empty($_POST["passwordver"])
and !verification($_POST["password"],$_POST["passwordver"])){
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_POST["password"]) === TRUE){
$url = 'succesfull.html';
header($url);
}
}
}
The function for addgamers
function addgamer($db,$gender,$username,$email,$password){
$sql = "INSERT INTO gamers (`gender`, `username`, `email`, `password`) VALUES('$gender','$username','$email','$password')";
$db -> exec($sql);
if ($db->query($sql) === TRUE) {
$GamerId = $db -> lastInsertId();
$_SESSION['GamerId'] = $GamerId;
return true;
} else {
return false;
}
}
I found some answers here but all of them do the same and I have no solution for this.
GOTO($url);
Or
header('location: $url');
Or
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_SESSION["password"]) === FALSE ){
die();
}else{
$url = 'successful.php';
header($url);
}
Also tried with jQuery
echo "<script>window.location = '$url'</script>";
On every single click on the registration submit button you get redirected to the successful page but that should not happen until everything is filled in correctly as shown from the above code.
As you can also see I'd like to fix this problem trying with php only first.

Validate before submitting the form would be better at first.
As #Nicolas D mentioned you should also know that the form action is the page you direct to no matter what.
You can however set this to the current page by using action="" or action="<?php echo $_SERVER['PHP_SELF']; ?>"
This last could come with exploits, you can use "htmlentities($_SERVER['PHP_SELF'])" instead. Read about this here.

You have a missunderstanding PHP problem.
If your form use a submit form, it will post automatically to the php page targeted.
If you don't want to post to a new page and still verify your data, then you must use ajax in jquery : http://api.jquery.com/jquery.post/ . With that you ll catch your data without unexpected redirection.
Once all your form is validated by your php code during ajax call, you can redirect in jquery on the callback function.
Hope this will help, I ve been through this step and I remember it was painful

Related

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well

How to display empty field error message

I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!
You can send the error to the main page by using php GET request, and then display it.

how to unsave if page refreshed

I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Reset the form data on unload

I'm using this code:
if(isset($_POST['btitle'])) {
if(count($errors) > 0) {
foreach($errors as $error)
$errContent .= "<li>".$error;
echo notification(
$errContent,
FALSE,
"The following errors were encountered:"
) . "<div style='margin-bottom: 10px;'></div>";
}
else {
echo notification(
"<li>New form added!",
TRUE,
"Success:"
) . "<div style='margin-bottom: 10px;'></div>";
}
}
When I type something in the input named 'btitle' and hit the submit button, everything is fine, until I refresh the page - it should loose the data and start again after refreshing, but it keep saying "Success:" even if the 'btitle' input is empty.
What am I doing wrong?
you need to redirect the user to the same page and loose the post data.
header("Location: file.php?success=true");//or ?errors[]=blabla
exit();
now, in the same page (file.php) you need to:
if(isset($_GET['success']) && $_GET['success'] == true){
//handle true
}else if(/* here you can ask about errors or what ever */){
}
BTW, if you don't do it, the entire submitting form will be act again like you resubmit it.
for instance, if you insert data to the database, it will be insert over and over again when you refresh the page, so if you redirect as suggested, you loose the posted data and now you can show the errors or success.
When you hit refresh, your browser resends POST data to the page. This question has been asked many times, for instance here and here. Take a look at the answers to some of those questions to get an idea of what you can do.

Categories