Header not sent though previously it was working - php

Using PHP Header method to redirect to another page after sending submit button had a problem though previously it was working fine. The problem started after putting additional form field.
Tried looking for any whitespaces, remove the code to the previous working state proved futile.
<?php
session_start();
$hostname_mysql = "localhost";
$database_mysql = "smartsaf_angkasa";
$username = "root";
$password = "";
$mysql = mysql_connect($hostname_mysql, $username, $password);
$errors = array();
//mysql_select_db( $database_mysql, $mysql);
if(!$mysql)
echo "".mysql_error();
else{
//echo "<h2>Connected to database successfully ".mysql_error()."</h2>";
mysql_select_db($database_mysql);
}
if ($_SERVER['REQUEST_METHOD'] != 'POST')
{
?>
<div>
<form class="main-container" action="admin-pakej.php" method="post" enctype="multipart/form-data" >
<div class="input-form"><label for="desc" name="lbldesc">Description</label></div><div class="input-form-right"><input type="text" name="description" size="60" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Market Price" name="lblmarketprice">Market Price</label></div><div class="input-form-right"><input type="text" name="marketprice" id="marketprice" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Membership No" name="lblmemberno">Membership Number</label></div><div class="input-form-right"><input type="text" name="membershipno" id="membershipno" size="20" onblur="change()" ><div id="disabled-text-box"><input type="text" name="membersname" size="35" disabled></div></div>
<div class="clr"></div>
<div class="input-form"><label for="Member Price" name="lblmemberprice">Members Price</label></div><div class="input-form-right"><input type="text" name="membersprice" id="membersprice" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Point PV" name="lblpointpv">PV Points</label></div><div class="input-form-right"><input type="text" name="pointpv" id="pointpv" size="20" required ></div>
<div class="clr"></div>
<div class="input-form"><label for="Package Type" name="lblpackagetype">Package Type</label></div><div class="input-form-right"><select name="package" id="package"><option value="gold">Gold</option><option value="silver">Silver</option><option value="bronze">Bronze</option></select></div>
<div class="clr"></div>
<div class="input-form"><label for="Product Page" name="lblproductpage">Product Page HTML File Name</label></div><div class="input-form-right"><input type="text" id="productpage" name="productpage" size="30"></div>
<div class="clr"></div>
<div class="input-form"><label for="Product Pics" name="lblproductpics">Product Pics</label></div><div class="clr"></div>
<div class="input-form-right"></div><div class="input-form-right"><input type="file" id="upload" name="upload" onchange="readURL(this)"></input><img id="blah" class="container" src="#" alt="preview image" /></div>
<div class="clr"></div>
<div class="input-form"></div><div class="button"><button type="submit" id="submit" name="submit">Submit</button></div>
</form>
</div>
<div class="clr"></div>
<div><p>
<!--<ul>-->
<?php
}
else
{
$desc_product = $_POST['description'];
$membershipno = $_POST['membershipno'];
$product_pics = $_FILES['upload']['name'];
$market_price = $_POST['marketprice'];
$membersprice = $_POST['membersprice'];
$package_type = $_POST['package'];
$pv_points = $_POST['pointpv'];
$productpage = $_POST['productpage'];
if (empty($desc_product) || empty($product_pics) || empty($membershipno) || empty($membersprice) || empty($pv_points) || empty($productpage))
{
array_push($errors, "Fields are empty");
}
else
{
$query = "INSERT INTO product_final (desc, ext_member_id, productpics, marketprice, memberprice, packagetype, pv_points, productpage, category) VALUES
('$desc_product', '$membershipno', '$product_pics', '$market_price', '$membersprice', '$package_type', '$pv_points', '$productpage', '')'";
$result = mysql_query($query, $mysql);
if ($result)
{
if (!headers_sent())
{
header("location:record_page.php");
exit;
}
else
{
echo "Headers already sent";
exit;
}
}
//else
//echo "".mysql_error($mysql);
}
}
?>
<!--</ul>--></p>
</div>
</body>
<script type="text/javascript">
function readURL(input)
{
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function(e)
{
$("#blah")
.attr("src", e.target.result)
.width(300)
.height(250);
};
reader.readAsDataURL(input.files[0]);
}
}
function getpicPath()
{
document.getElementById("imgs").innerHTML;
}
</script>
</html>
Expect to get at least an error message to find out what is actually holding the process from sending committed form submission to another page as acknowledgement that the form has already been processed.

I think you should try
if(mysql_affeted_rows($result)==1)
{
if (!headers_sent())
{
header("location:record_page.php");
}
else
{
echo "Headers already sent";
exit;
}
}
instead of that condition and once you have redirected through header I don't think you need to use exit().
thank you.

You are getting this problem basically because some HTML code is included (which is sending the header before only) right before you are trying to send header.
Your form code is sending header initially only, thereby making it impossible to send a http header later.
Use output buffering, i.e. at the very start of your script, put ob_start(), and at the end, put ob_flush(). This enables PHP to first wait for all the output to be gathered, determine in what order to render it, and outputs it.
guide for using output buffer

Related

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

Can't pass a variable from one php file to another

I have a simple login page, and the idea is that if user input incorrect passowrd/login, then he or she will see error message on the same page. I have code in 3 different files - one is simple html, another has the functions, and last one runs all the logic:
<div id="content">
<div class="logo-container"><img src="images/logo2.png" alt=""></div>
<div class="container-fluid">
<!-- All login logic is in login.php file -->
<form action='/login-logic.php' method="post" class="form-1">
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" class="form-control" id="username"
name="username" placeholder="What's your username?" required />
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" class="form-control" id="password"
name="password" placeholder="What's your password?" required/>
<?php
if($isValid === false) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}
?>
</p>
<p class="submit">
<button id="submit-button" type="submit" name="submit" value="submit"><i class="fa fa-arrow-right"></i></button>
</p>
</form>
</div>
// Check match of the credentials in database
function loginValidation($query) {
global $isValid;
$isValid = true;
$count = mysqli_num_rows($query);
if($count == 1) {
header('Location: pages/signup.php'); /* Redirect browser */
} else {
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
}
Thank you!
You declare a variable just before to force browser to reload the page. So the variable is no more defined in the next request.
Here is a possible way.
Instead of :
{
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
Do :
{
/* Redirect browser */
header('Location: index.php?error');
exit();
}
Then, in HTML :
if (isset($_GET['error'])) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}

php long polling with submission form

This is the extended question of the thread implementing php long polling
I got the solutions for that. But in my server.php i am displaying a form which will be having few input fields. This should display in #response area. Now i am able to display the same on instant basis. As it loads on seconds basis, i am not able to enter anything on any input boxes. Here is my display page
<?php
ob_start();
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
$grp_id = $_GET['id'];
?>
<!DOCTYPE html>
<head>
<!-- head section -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp, 'id' : <?php echo $grp_id; ?>};
$.ajax(
{
type: 'GET',
url: 'http://localhost/folder/server.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = JSON.parse(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
// initialize jQuery
$(function() {
getContent();
});
</script>
</head>
<body<?php if ($body_classes) { echo ' class="' . $body_classes . '"'; } ?>>
<div id="page-content" class="block">
<div class="row gutter30">
<div class="col-xs-12">
<div id="response"></div>
<!--Contents in server.php will display according to the condition changes in database-->
</div>
</div>
</div>
server.php
<?php
set_time_limit(0);
$data_source_file = 'data.txt';
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
// main loop
while (true) {
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
// PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
// clearstatcache();
// get timestamp of when file has been changed the last time
// $last_change_in_data_file = filemtime($data_source_file);
// Create database
$sql = "SELECT max(gid) FROM base_grp WHERE gid=".$_GET['id']."";
$result = mysqli_query($conn, $sql);
$last_change_in_data_file = mysqli_fetch_array($result, MYSQLI_NUM)[0];
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
$sql = "SELECT is_set FROM base_grp WHERE gid =".$_GET['id']."";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row['is_set'] == 0)
{
$data .= '<form name="frm" method="post" action="show_data.php">
<div class="row gutter30" style="margin-top:20px;">
<div class="form-group">
<img src="img/img1.png" class="image" />
<input type="text" name="img1" class="form-control" />
<input type="hidden" name="img1_id" value="3" />
</div>
<div class="form-group">
<img src="img/img2.png" class="image" />
<input type="text" name="img2" class="form-control" />
<input type="hidden" name="img2_id" value="4" />
</div>
<div class="form-group">
<img src="img/img3.png" class="image" />
<input type="text" name="img3" class="form-control" />
<input type="hidden" name="img3_id" value="2" />
</div>
<div class="form-group">
<img src="img/img4.png" class="image" />
<input type="text" name="img4" class="form-control" />
<input type="hidden" name="img4_1" value="1" />
</div>
<button type="submit" name="lock" class="btn btn-sm btn-success">SUBMIT</button>
</div>
</form> ';
$last_change_in_data_file = $row["gid"];
}
else if($row['is_set'] = 1)
{
$data .= "<div class='row gutter30' style='margin-top:20px;'>
<div class='col-xs-3'>
<img src='img/img1.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img2.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img3.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img4.png' class='image' /> </div>
</div>
";
$last_change_in_data_file = $row["gid"];
}
$last_change_in_data_file = $row["gid"];
}
}
// mysqli_close($conn);
// put data.txt's content and timestamp of last data.txt change into array
$result = array(
'data_from_file' => $data,
'timestamp' => $last_change_in_data_file
);
mysqli_close($conn);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep( 1 );
continue;
}
}
Not getting how to make the entry ...
Can somebody suggest me where i am going wrong?. Thanks!

PHP Header Exceptions

I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);

Why is this jQuery function not communicating properly with my php file?

Let me show you what I have:
(1) Form:
<form name="login-form" class="login-form" method="post" onSubmit="login()">
<div class="header">
<h1>Sign In</h1>
</div>
<div class="content">
<input type="hidden" name="siteToken" value="$token" />
<input id="username" name="username" type="text" class="input username" placeholder="Username" required="required" />
<div class="user-icon"></div>
<input id="password" name="password" type="password" class="input password" placeholder="Password" required="required" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" />
</div>
</form>
(2) jQuery Function:
$(document).ready(function login() {
$('.login-form').submit(function() {
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
function loginMessage(data) {
$('.header').append(data);
};
});
});
(3) PHP Function:
<?php
require_once('VRC_Header.php');
require_once('../Classes/VRC_MasterOO.php');
require_once('../Classes/VRC_Secure_Login.php');
//*******************************//
//Declerations
$signIn = "";
$username = "";
$password = "";
$success = "";
$error = "";
//******************************//
//****************************************************************************************//
//Script Header
$signIn = new UserService($dbuser, $dbpass, $dbhost, $dbname); //Create new class instance
$signIn->sec_session_start(); //Begin session
//***************************************************************************************//
//***************************************************************************************//
//Begin Login Functions
if(isset($_POST['username'], $_POST['password'])) {
//Assign POST submissions to passable php variables
$username = $_POST['username'];
$password = $_POST['password'];
$passedToken = $_POST['siteToken'];
/*//Check Token Values (prevent CSRF attacks)
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}*/
//Test if both fields are not null
if($username == "" || $password == "")
{
$error = "Not all fields were entered<br />";
echo $error;
exit();
}
//Start login process
else
{
$success = $signIn->login($username, $password);
if ($success === true)
{ //Login Successful
echo "Success!"; //Direct to main page.
exit();
}
//Specific login failure determination
else
{
switch ($success){
case 1:
$error = "Your account has been locked.";
echo $error;
break;
case 2:
$error = "Invalid Username/Password (2)";
echo $error;
break;
case 3:
$error = "Invalid Username/Password";
echo $error;
break;
case 4:
$error = "Invalid Username/Password (3)";
echo $error;
break;
}
}
}
}
?>
Fist off, I doubt the problem is in the PHP function. I've tested it before implementing jQuery calls (I used it directly in the html action attribute). My suspicion is that the problem is occurring in the jQuery function (I just started using jQuery and am not really familiar with it).
Note that I have removed the token input for the time being in the php file. I simply want to get it working before I deal with that (there is another problem with that part).
I don't believe that the post variables are being sent to the php file correctly. Also, I don't believe my jQuery function as it is is properly receiving the echo response from my php function either, in the sense that it will display it as html - provided that it worked to begin with.
Any input is appreciated.
$(document).ready(function login() {
That line is the problem.
Probably the login function is not available to rest of the page. It's just a name given to anonymous function which is parameter to $(document).ready function.
You have a scope problem.
Move the login function out separately:
function loginMessage(data) {
$('.header').append(data);
};
function login() {
$('.login-form').submit(function () {
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
});
}
$(document).ready(function () {
login();
});
EDIT:
in your login function, you are registering a handler to your login form's submit event. And it has to be registered only once.
So, remove `onsubmit=login()` from your form's attributes, and you are good.
Slightly Changed your HTML to this
<form name="login-form" class="login-form" method="post">
<div class="header">
<h1>Sign In</h1>
</div>
<div class="content">
<input type="hidden" name="siteToken" value="$token" />
<input id="username" name="username" type="text" class="input username" placeholder="Username" required="required" />
<div class="user-icon"></div>
<input id="password" name="password" type="password" class="input password" placeholder="Password" required="required" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" />
</div>
</form>
and Javascript
$(document).ready(function () {
$('.login-form').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$("input").prop("disabled", true);
$.post('VRC_LoginProcess.php', formData, loginMessage);
function loginMessage(data) {
$('.header').append(data);
}
});
});

Categories