sending a form to different pages depending on values - php

I was wandering how you would go about sending a form to different pages.
If there is an error in the form, stay on the page, showing an error and if there is no error go onto another page
here is my code
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar" value="Enter Student Number" style="min-width:165px;">
<input type="button" value = 'Continue' onclick="validate()">
<?
$studID = $_POST['txtChar'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
echo $_SESSION['module'];
if(isset($studID)){
if($result == null){
$studerr[] = "No Student with that ";
print_r($studerr);
}
$_SESSION['student'] = $studID;
}
echo' <SCRIPT TYPE="text/javascript" LANGUAGE="javascript">
function validate() {
if('.$result.' == null)
{
return false
}
else
{
return true;
}
}
</script>';
?>
</form>
cheers

Very briefly (without knowing other details):
if (!empty($errorMessage)) {
echo $errorMessage;
} else {
header("Location: http://domain.com/success.php");
}

Have you searched something about that ???
YOu can use normal php validation for error checking and
if(there is no error )
{
header('location: redirect2page.php')
}
else
{
show errors
}

you have to do simple javascript validation in form submit if error occures it will return false so, thats remain on same page
like
function validate()
{
if(document.getElementById('elementid').value=='')
{
return false;
}
else
{
return true;
}
just call this function on submit button click

Related

My cookies are not being set after the login form has been sent

I have a login script and a functions.php script to check if the session username and cookie are set. When the user logs in, if they select the remember me, the cookie is supposed to set. But the problem is that, the script works, but the cookie doesn't set so the user is not being logged in. I've searched through so many topics on here and tried as many solutions as possible, but I still either get the same result or end up giving me more errors.
if (isset($_POST['rem']) && $_POST['rem'] == 'on') > {
setcookie('MCLatestUser', $token, 31622400, > '/');
session_regenerate_id(true);
}
This is the part of the code that should set the cookie if remember is checked.
Log.php (Since I use an ajax login script, the url is set to this):
<?php
include_once 'db.php';
include_once 'functions.php';
error_reporting(-1);
if(isset($_POST['email'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = $mysqli->real_escape_string($_POST['password']);
try {
$check = mysqli_query($mysqli, "SELECT * FROM users WHERE email='$email'");
$res = mysqli_num_rows($check);
if($res > 0) {
while($run = mysqli_fetch_array($check, MYSQLI_ASSOC)) {
$blocked = $run['blocked'];
$deactivated = $run['deactivated'];
$paused = $run['paused'];
$verified = $run['verified'];
$rank = $run['rank'];
$token = $run['token'];
$pass = $run['password'];
$pbackup = $run['pbackup'];
if($verified == 'true') {
if($blocked == 'true') {
echo 'Looks like your account was blocked. If you think this is an error, please contact an admin via support#mclatest.com';
} else if($deactivated == 'true') {
echo 'Looks like your account has been deactivated. If you think this is an error, please contact an admin via support#mclatest.com';
} else if($paused == 'true') {
echo 'Looks like your account is frozen. If you think this is an error, please contact an admin via support#mclatest.com';
} else {
if(password_verify($password, $pass)) {
$timestamp = time();
// Authenticated, set session variables
$_SESSION['username'] = $run['username'];
if (isset($_POST['rem']) && $_POST['rem'] == 'on') {
setcookie('MCLatestUser', $token, 31622400, '/');
session_regenerate_id(true);
}
$sql = mysqli_query($mysqli, "UPDATE users SET Ip = '$ipaddress', login_ip = '$ipaddress', latest_login_date = '$now', login_date = '$date', login_time = '$time', login_day = '$day', login_month = '$month', login_year = '$year', status = '$timestamp' WHERE email = '$email'");
if($sql) {
echo "Success!";
} else {
echo "Error login in";
}
// do stuffs
} else if(password_verify($password, $pbackup)) {
$timestamp = time();
// Authenticated, set session variables
$_SESSION['username'] = $run['username'];
if (isset($_POST['rem']) && $_POST['rem'] == 'on') {
setcookie('MCLatestUser', $token, 31622400, '/');
session_regenerate_id(true);
}
$sql = mysqli_query($mysqli, "UPDATE users SET Ip = '$ipaddress', login_ip = '$ipaddress', latest_login_date = '$now', login_date = '$date', login_time = '$time', login_day = '$day', login_month = '$month', login_year = '$year', status = '$timestamp' WHERE email = '$email'");
if($sql) {
echo "Success!";
} else {
echo "Error login in";
}
// do stuffs
} else {
echo "<h4 style='font-weight:bold;font-family:arial;margin:8px'>Your password is incorrect, please try again. If you still get this error after using your backup password, please <a href='https://mclatest.com/community/reset.php?r=password'>reset</a> your password</h4>";
}
}
} else {
echo "<h4 style='font-weight:bold;font-family:arial;margin:8px'>You need to verify your account. Please click this link to <a href='https://mclatest.com/community/confirm.php?email=".$email."&token=".$token."'>verify your account</a></h4>";
}
}
} else {
echo 'No records of that user have been found!';
}
} catch(PDOException $e){
echo $e->getMessage();
}
} else {
echo "Invalid email";
}
Login.php (the html and ajax form):
<form id="login_form" style="text-align:center" method="post">
<script>
$(document).ready(function() {
$("#login").click(function(e) {
e.preventDefault();
var email = $("#email").val();
if (email = "") {
$("#error_msg").html("<h4>Email cannot be empty</h4>");
} else {
var data = $("#login_form").serialize();
$.ajax({
type: "POST",
url: "../inc/log.php",
data: data,
beforeSend: function() {
$("#error_msg").fadeOut();
$("#login").val('sending ...');
},
success: function(data) {
if (data == "Success!") {
// alert("Works"); //for testing purposes
window.location.href = "index.php";
} else {
$("#error_msg").fadeIn(1000, function() {
$("#error_msg").html('<div style="border:1px solid: red; background:rgba(255,0,0,0.9;)">'+data+'!</div>');
$("#login").val('Login');
});
}
},
error: function(data) {
alert("Process Failed!");
}
});
return false;
}
});
});
</script>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label ">
<label for="input_email" class="mdl-textfield__label">Email</label>
<input type="email" name="email" class="mdl-textfield__input" maxlength="255" id="input_email" />
</div>
<br>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<label for="input_password" class="mdl-textfield__label">Password</label>
<input type="password" name="password" class="mdl-textfield__input" maxlength="255" id="input_password" />
</div>
<br>
<label style="width:auto !important" for="remember_me" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" >
<input name="rem" type="checkbox" id="remember_me" class="mdl-checkbox__input" checked />
<span class="mdl-checkbox__label">Stay logged in?</span>
</label>
<br>
<nav style="width:auto !important;display:-webkit-box;-webkit-box-pack:center" class="mdl-navigation">
<a class="mdl-navigation__link" href="forgot.php?ftype=password">Forgot Password?</a> |
<a class="mdl-navigation__link" href="register.php">Register?</a>
</nav>
<br>
<input type="submit" id="login" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" name="login" value="Login"/>
</form>
functions.php (this is the portion of the script to check the session and cookie variables):
function loggedIn() {
if (isset($_SESSION['username']) && !empty($_SESSION['username']) && isset($_COOKIE['MCLatestUser'])) {
return true;
} else {
return false;
}
}
Script works but cookies aren't being sent. I'm at my wits end here, been working on this for over 4-5 hours now, had over 35 chrome tabs open just to figure this out. I am probably overlooking a minor detail. Login Page Link
It works if i remove the && $_COOKIE['MCLatestUser'] from the function script
setcookie('MCLatestUser', $token, 31622400, '/');
This method has some problems in the third parameter.It should be based on the current time.
PHP: setcookie - Manual
I figured it out. It turns out it was the browser's fault. I tried it on Microsoft Edge and Mozilla Firefox and it worked. So I looked about for that issue and all I had to do was clear my cookies and site data on chrome. Thank you to those who helped and those who wanted to but couldn't/didn't.

Button for updating data

I have a list of buttons that each pass on a different value. The code should store this value as a variable or session, which then is passed on to a function that updates the table row of the value. I tried just storing this value as a variable and then passing it on, but that didn't work so I figured I'd make it into a session. And that didn't work either, no idea where to go from here.
Here's a button example:
<tr>
<td data-title="Name"><img src="banner.jpg" width="400"></td>
<td data-title="Link">
<form name="first" action="pending.php" method="POST"><input type="hidden" name="xz" value="one"><a class="mbutton" onclick="document.forms['first'].submit();">Gedaan</a></form>
</td>
<td data-title="Status"><p class="ptable"><?= $fgmembersite->One(); ?></p></td>
</tr>
Here's where the form leads to:
<?PHP
include("./include/membersite_config.php");
$_SESSION['postdata'] = $_POST;
$bname = $_SESSION['postdata'];
if($fgmembersite->Pending($bname))
{
$fgmembersite->RedirectToURL("index.php");
}
?>
So this should pass on $bname to the function Pending().
And here's pending:
function Pending($bname)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$result = mysql_query("Select * from $this->tablename where confirmcode='y'",$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error");
return false;
}
$row = mysql_fetch_assoc($result);
$ux = $row['username'];
$ustat = $row['one'];
$bname = $_SESSION['postdata']['xz'];
$qry = "Update $this->tablename Set $bname='In behandeling' Where username='$ux'";
if(!mysql_query( $qry ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$qry");
return false;
}
return true;
}
So you are saying that the Pending function is returning TRUE, and redirecting you to membership.php ? or index.php ( or are these the same ) -
if that query fails and returns false - you would just end up on the page that you had posted to .

PHP function return true or false

I am trying to create a function that will check against the data from the database. If the results are empty, continue with the code. If else, abort.
Here is an example of my code.
function check_if_blocked(){
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(empty($results)){
$var = false;
} else {
$var = true;
}
return $var;
}
Function check_if_blocked is going to be used multiple through out the plugin.
Here is an example of how I plan on using check_if_blocked()..
function msg_form(){
if(check_if_blocked(){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send">';
}
}
Regardless on how I switch around the true, false, and even if(!check_if_blocked...
You are trying to return the wrong value, get_results will return true if the query was successful, not if it found matches, so, it might return true even if there are no matching records found, try this instead:
function check_if_blocked()
{
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(!$results) {return false;} // query failed, no way to know if there are matching records.
$numrows = count($results); // query worked, now, check if there are matching records.
if (is_int($numrows) && $numrows) {$var = true;} else {$var = false;}
return $var; // return the result.
}
Now, the function will return true only if there are one or more matching records.
Also, you have a syntax error here:
if(check_if_blocked(){
It should be:
if(check_if_blocked()){
After everyone's advice. I finally got it to work. Here is my code.
function check_if_blocked($blocked){
global $wpdb;
$user = '1';
$user2 = '2';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE blocked = $user AND blocker = $user2");
if(empty($results)){
$blocked = 'not_blocked';
} else {
$blocked = 'is_blocked';
}
}
function msg_form(){
if(check_if_blocked($blocked) == 'not_blocked){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send"></form>';
}
}

Calling functions which are defined in other php file wont work the way I want

I have followin PHP code, it is where I defined my functions:
<?php
function emaili_pikkus($email){
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
$emaili_pikkus=True;
}
}
function parooli_pikkus($parool)
{
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
$parooli_pikkus=True;
}
}
function varasem_olemasolu($email)
{
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad WHERE e_mail = '$email'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
$varasem_olemasolu=True;
}
else
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
}
}
function paroolide_kattuvus($parool, $parool_uuesti)
{
if($parool==$parool_uuesti)
{
$paroolide_kattuvus=True;
}
else{
echo "Paroolid ei kattu.";
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Praks/templates/registreeritud.php'>";
}
}
?>
Then I have other PHP code where I call necessary functions(They are seperated, because I want to use my functions in other applications too):
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1($parool.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi','$perekonnanimi','$hashed_pwd','$salt')";
emaili_pikkus($email);
if ($emaili_pikkus=True){
parooli_pikkus($parool);
}
if ($parooli_pikkus=True){
varasem_olemasolu($email);
}
if ($varasem_olemasolu=True){
paroolide_kattuvus($parool, $parool_uuesti);
}
if ($paroolide_kattuvus=True){
NewUser();
}
?>
And then I have my HTML code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
init.funcs.php looks like that:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
include_once 'functions/survey.funcs.php';
?>
It all together should be a registration form and it worked before I made few changes. Before those changes I had my functions defined to work only for this registration form and they had no parameters needed. Also they were nested in each other. My question is how should I write my second PHP code, so it all would work. Right now it creates new user even if some previous condition are not True. It is a long question and I would be very thankful if someone answers me.
You have a lot of errors in your code:
Your functions aren't returning any value. Variables intitalized inside the function will not be available outside it. The best way is to return a boolean value and check that outside
The function definition:
function some_func($param1, $param2) {
if (some_condition) {
// If everything okay, return TRUE
return TRUE;
} else {
// It's not gonna work with this, so return FALSE
return FALSE;
}
}
Checking the return value:
if (some_func($foo, $bar)) {
// some_func returned TRUE, do further processing
}
With if($var = True), you're not actually checking if a variable is true or not. You're assigning it the boolean value True. You need to write if($var == True instead.
You're using the deprecated mysql_* functions. They're deprecated. Use MySQLi or PDO instead.

Using .Post() to pass a JQuery Variable to PHP

I am trying create an email subscription input box using JQuery, but for some reason, the inputted email addresses are not inserting into the MySql database, can anyone help me?
Here is the code I have in my newsletter.js file:
jQuery(function($){
var validateRegexps = {
email: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
"default": /.{4}/
}
if ($("#newsletter form").length == 0) return
var defaultMessage = $("#newsletter").attr("data-default")
var subscribedMessage = $("#newsletter").attr("data-subscribed")
var newsletterForm = $("#newsletter form")
/* newsletter code */
function newsletter(send) {
var subscribe = true
newsletterForm.find('input[type="submit"]').val(subscribe ? "Sign Up" : "Unsubscribe")
var email = newsletterForm.find('input[name="email"]')
var check = true
if (email.val() == defaultMessage || email.val() == subscribedMessage) {
email.val("")
if (!send) check = false
}
if (check) {
if(validateRegexps["email"].test(email.val())) {
// valid mail
email.removeClass("error")
if (send) {
$.post("php/newsletter.php",{add: email.val()}, function(data) {
email.val(subscribedMessage)
});
email.val("sending")
}
} else {
// invalid mail
email.addClass("error")
}
}
return false
}
function restore(e) {
var jqEl = $(e.currentTarget)
if (jqEl.val() == "") {
jqEl.val(defaultMessage)
}
return true
}
function signUp() {
return newsletter(false)
}
function signUpAndSend() {
return newsletter(true)
}
newsletterForm.find('input[name="email"]').focus(signUp).focusout(restore)
newsletterForm.change(signUp)
newsletterForm.submit(signUpAndSend)
});
Here is the code in my newsletter.php file:
require("config.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
$subsql = "INSERT INTO subscribe(email) VALUES(".$_POST['add'].");";
mysql_query($subsql);
And here is the code in my other php page to display the input box:
<div id="newsletter" data-default="youremail#yourdomain.com" data-subscribed="Thank you for subscribing.">
<form action="#" method="POST">
<input type="text" name="email" value="youremail#yourdomain.com" />
<input type="submit" value="submit" />
</form>
<h2>Sign Up to Our Newsletter!</h2>
</div>
Any help is greatly appreciated. Thank you very much in advance!!!
Hmm! Looking at your code does not directly point to any errors but the most obvious issue seems to be in the INSERT query that the email address isn't enclosed in single-quotes. Please draft your query like:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
Hopefully the above INSERT should work fine. If the issue still exists though, try finding out if the query might be generating any errors:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
mysql_query($subsql);
if (mysql_error()) {
echo mysql_error();
}
If no errors are found and the issue still exists, it might make sense to look into other basics, like:
Is $_POST['add'] available in "newsletter.php"?
Is MySQL connection correctly established in "newsletter.php"?
Is there any JavaScript issue that the POST request isn't send at all or perhaps send with an empty email address?
Hope this helps!

Categories