This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I have a simple checklist form with a number of input fields and counters to check them. Form consists of only few text fields and some radio buttons, whose value is set to either conforms or notConforms:
error counter ($errCounter) = counts errors like illegal input format and missing fields
non conformance counter ($notConforms) = checks if/how many input fields are set to notConforms.
I am trying to alert the user and get their confirmation if any inputs are set to notConforms.
Two problems with the outcome of my code below:
it makes two entries (duplicate) into database
after database update, it does not header the user to the indicated page (inspectionbatch.php)
What is wrong with the following?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if($errCounter == 0){ // provided there are no errors found during form validation
// warn user if there is a non-conformance
if($notConforms !== 0){ ?>
<script>
if(confirm("A not-conforms 'N/C' result has been recorded for one or more inspection criteria. If this is accurate, click OK to continue.")) {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
} else {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
}
</script>
<?php } else {
updateDatabase(); header("location: inspectionbatch.php");
}
} else { // if errors are found during form validation, return how many errors were found
echo "Error count: " . $errCounter;
}
}
I also tried putting the header() function inside the updateDatabase() immediately after the syntax to update database. Database was updated fine but header() did not work...
This code doesn't work because PHP, a server-side technology, runs to completion before javascript, a client-side technology, even begins. All the PHP code will execute on your web server, and a response will be sent to the client and then all the javascript will run in the the web browser.
If you want to mix the 2, you'll have to imagine how the completely rendered dynamic result will look to a web browser.
Additionally, a call to the header() function cannot be made if any bytes have already been written to the HTTP body. From the docs:
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.
Related
I have a simple form with four input fields, name, email, phone, and message. I am using JavaScript with Ajax to post my input fields to a PHP file for validations and mailing via phpmailer.
I collect the errors in an array from the validation functions. The I use and if statement to send the errors back to the html page via json_encode(array) function and exit the script. Else, I let the script to continue to and successfully send the email to my inbox.
The problem I have is json_encode(array) exit the script where errors were found or not. Even if I do not forcefully exit the script with die or exit. In that respect, no email is sent as the script is prematurely terminated.
I listed below a few lines from my php file to show how my if statement is set up.
I have searched the web for answers to no avail. I tried to place the json_encode function as different location in the file, and it did not work. I tried combining the error array with the success or failure strings from the mail sent function and did not work.
if ( $errors != null ) {
echo json_encode( $errors );
exit;
} else {
$mail = new PHPMailer( true );
/* Set the mail sender. */
$mail->setFrom( 'jsmith#gmail.com', 'John Smith' );
/* Add a recipient. */
//set who is receving mail
$mail->addAddress( 'heh#hotmail.com' );
/* Set the subject. */
$mail->Subject = 'New message from contact form';
/* Set email to be sent as HTML */
$mail->isHTML( true );
/* Set the mail message body. */
$mail->Body =
I am expecting that once the if statement clears the errors, the entire php file script will continue until the data is emailed. However that is not happening.
I found the answer from another related question I posted on a different post. The errors array was containing all null variables that the conditional statement I had to determine whether the mail should be sent on Boolean false (no errors found) was not considering the array as empty. I had to change the conditional if statement to use array_filters instead.
Thank in advanced,
I was looking at creating a linked dropdown menu and found tutorial/code online
I have used this code twice to create lmsdropdown.php and clubdropdown.php. I am able to store the values from the lmsdropdown form is a session and echo them to clubdropdown (just for verification that values are present).
lmsdropdown is a php include within members.php and clubdropdown is an include in members2.php.
When I select a value on clubdropdown the page refreshes to populate the 2nd dropdown box and this results in my session data being cleared.
I am new to PHP/Javascript so the answer may be very obvious but this has had me stumped for a few days now. Any help would be very much appreciated.
Below is a merge of two snippets members2.php, that has taken the output of lmsdropdown and stored output in sessions.
clubdropdown shows the java code and also the echo session statements
I am able to correctly echo the session data however the javascript seems to remove this when building dropdown 2.
members.php session data
<?php
session_start();
$_SESSION['lms'] = $_POST['lms'];
$_SESSION['week'] = $_POST['week'];
if (!isset($_SESSION['usr_lvl']) or ($_SESSION['usr_lvl'] != 0)) {
header("Location: login.php");
exit();
}
?>
clubdropdown output of session data
<SCRIPT language=JavaScript>
function reload(form) {
var val = form.lge.options[form.lge.options.selectedIndex].value;
self.location = 'members-page2.php?lge=' + val;
}
</script>
</head>
<body>
<?php
$usr = $_SESSION['usr_id'];
#$lge=$_GET['lge']; // Use this line or below line if register_global is off
if(strlen($lge) > 0 and !is_numeric($lge)){ // to check if $lge is numeric data or not.
echo "Data Error";
exit;
}
$usr = $_SESSION['usr_id'];
$lms=$_SESSION['lms'];
$week=$_SESSION['week'];
echo "<br>Value of \$week = $week<br>Value of \$lms = $lms <br>Value of \$usr = $usr";
The image below shows the session variables outputted to clubdropdown that is included in members2.php
clubdropdown with variables shown
This image shows the errors after a selection is made from th 1st dropdown.
Error after list refresh
From some of the answers to similar questions on here I assume the error is because the post data is being overwritten/removed on refresh but I thought that's what the session was for?
Any input is greatly received thank you.
You are getting the values from $_POST, which the second time you run the page is absent. You need to add an If(isset($_POST['lms'])){ $_SESSION['lms'] = $_POST['lms']; } so that it is skipped if the $_POST value isn't present.
Currently, your $_SESSION variables are still there, but are being replaced with empty $_POST values.
I suspect you might be better off using an AJAX call to populate your dropdown list.
I am accepting Permanent Account Number (pan) from the user and before submitting, I am doing a check if the pan number already exists in db. It is working and I also get an error saying that pan no is already registered If I ignore the error and do not change the pan number and proceed to submit, it goes into the database.
I have observed that after the validation check, the entered number stays there. I wish to know how can I empty the input box after getting the error. If it remains empty, the submit button will not work. So how can I delete the entered number from the input box once the error appears and how can i get the cursor focus in the input box?
Thanks
HTML
<input name="panno" type="text" id="panno" style="width:219px;" />
<span id="pan_status1"></span>
FUNCTION
$("#panno").change(function()
{
$("#pan_status1").html('<img src="images/9.gif" align="absmiddle"> Loading Please wait...');
var id=$(this).val();
var dataString = 'panno='+ id;
$.ajax
({
type: "POST",
url: "checkp.php",
data: dataString,
cache: false,
success: function(html)
{
$("#pan_status1").html(html);
}
});
});
CHECKP.PHP
<?php
require("connection/config.php");
if(isset($_POST['panno']))
{
$mpan = $_POST['panno'];
$sql_check = mysql_query("select * from register where pan_no='".$mpan."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red"><STRONG>'.$madhar.'</STRONG> is already registered.</font>';
$response = array();
$response['successStatus'] = 'error';
$response['responseMessage'] = $erroMessage;
header('Content-type: application/json');
echo json_encode($response);
}
else
{
$response = array();
$response['successStatus'] = 'success';
$response['responseMessage'] = $erroMessage;
header('Content-type: application/json');
echo json_encode($response);
}
}
?>
EDIT
I made changes in the php file. Now when I enter the pan number and if the entered pan number does not exist in the database, I get the following output next to the input button
{"successStatus":"success","responseMessage":null}
and if it exists, I get the following
123456789012 is already registered.{"successStatus":"error","responseMessage":null}
Now that the status is captured, how can I make the input field empty if the status is error
I do not want to show the html / json output if the status is success and want to show ONLY the html if the status is error.
Since mysql ( php extension ) is deprecated you should mysqli to execute your SQL code. Next would be to escape your incoming POST request, because you don't want to get hacked via an SQL Injection.
You can respond with a JSON in order to announce the client side (jQuery) that you got an error or not.
Moreover, don't send PHP errors to a client, you can use a try / catch solution.
It is straightfoward-enough to clear the field, although the user might not wish for you to do so, especially if they're a slow typist. (They can say to themselves, "d'oh, I swapped two numbers!" and fix their actual tpyo, then push the button again.)
I suggest that what you need to do here is to have your JavaScript remember that the server told it (by means of the POST result) that the number was not valid. (Or, better yet, to remember that it has not yet told you that a particular number is valid.) If the user pushes the button anyway, you can give him an informative message, and not send the server anything.
And then, no matter what, you must also validate the incoming information on the server side. Even though you provide an AJAX-call to validate a PAN number, the server is ultimately responsible for ensuring that the database is updated correctly. It must check again to see that the number is valid, before posting it to the database. And, you must provide appropriate tests of that result, in your JavaScript: to see if the post succeeded, and if not, why not.
Your JavaScript should not knowingly send a missing or invalid PAN number to the host. However, the host must not assume that the client is "doing the right thing." Ultimate responsibility for the content of the database lies with the host.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys
I've done some hunting around, and I haven't seen my question asked by anyone yet. So, I'll ask here.
I'm new to computers in general and very new to web development specifically. I'm currently building my first website. It has a back-end database, server side scripting, the whole shebang.
Also, I'm on a Linux/Apache/PHP platform using a LAMPP local host server.
Preliminaries discussed, I was coding an AJAX call today (my first!) and came across some strange behavior on the front end. I'll post the code, but I'll briefly explain first.
My code is for a log-in form that verifies your password and username and then either lets you move on into the site or puts up an error message on the screen. I use JS for front end error checking just to stop any unnecessary data exchange from the client to the server.
Of course, you can't trust anything on the front end, so I wrote some PHP to error check on the back end as well. To test the efficacy of my back end error checking, I intentionally changed the parameters of the back end code so that my input would be accepted by JS but rejected by PHP.
Here is the code:
function serverValidation(x, y){
var z;
if (window.XMLHttpRequest){z=new XMLHttpRequest();}
else{z=new ActiveXObject("Microsoft.XMLHTTP");}
z.onreadystatechange=function(){
if (z.readyState==4 && z.status==200 && z.responseText == "false"){
$("#submit_error_3").show();
$( "#submit_error_3" ).text("X INVALID ENTRY");
$( "#username, #password").css("border-color", "red");
}
if (z.readyState==4 && z.status==200 && z.responseText == "true"){
$("#hidden_form_profile").submit();
}
}
z.open("POST","login.php",true);
z.setRequestHeader("Content-type","application/x-www-form-
urlencoded");
z.send("username=" + x + "&" + "password=" + y);
}
As you can see, I'm using POST to send form-like data, and I'm receiving ordinary text. The response is either the string "true" or the string "false". If "true" is received, the JS goes one way. If "false" is received, the JS goes another.
Here's the back end:
<?php
session_start();
if(!isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])){
$x = trim($_POST['username']);
$y = $_POST['password'];
if(validate($x, $y)){$_SESSION["logged_in"] = "true"; echo "true";}
else{
echo "false";
}
}
function validate($x, $y){
if( strlen($x) < 6 || strlen($y) < 6 ){
return false;
}
return true;
}
?>
This all works great, just as expected.
But, the back end isn't done. Once the format of the input is verified, I then plan on going into the database and matching the username and password to see whether the input is valid.
To that end, I included a PHP file with: include "login_info.php"; at the very top of the AJAX back-end script. This file just holds basic variables for the database server address, the database name, the username, and password.
Once I included that file, saved, and refreshed, things got VERY strange.
Basically the AJAX call stopped working. Through troubleshooting with alert boxes and such, I ascertained that the PHP script did its job, but the front end script wouldn't interpret the data properly.
As far as the JS was concerned, the returning data was a string and it took on the values "true" and "false" under the expected circumstances, but if(z.responseText == "false") and (z.responseText == "true")both evaluated to false in all cases.
Further, if(z.responseText) always evaluated as true in all cases. That is, when I included that extra file, somehow the JS considered the returning data to be a string with the expected value but treated it as a boolean that was always true.
Can someone explain to me what happened when I included that file in the back-end script?