Php header('Location") error [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I'm having some difficulty with my php coding.
I have 3 files, add.php, lib.php, and view.php
I created a simple form, and when the user clicks submit, it should direct them to the view.php where it will display the database. Now I'm having a couple issues I can't seem to resolve.
when the user clicks submit and the fields are blank or there is an error no entry should be made into the view page (or database)...however when I click submit a blank entry is made into the database. ALSO if i click "enter product" from the top menu bar anytime I click it, it causes a blank entry into the database. I can't figure out why that's happening.
My next issue is with the header('Location')
and my browser says:
"Warning: Cannot modify header information - headers already sent by (output started at lib.php:13) in add.php on line 16"
However if I click submit on my form it goes away.
Here is the code for the pages:
I truly apologize if the code is really messy.
Any help / advice / solution is greatly appreciated thank you.
And yes this was an assignment---it was due last week but since I couldn't finish it, it's not worth any marks anymore.

Your if statement if (empty($_POST)){ will always fail and the else will run, thus the empty db entries.
$_POST will always have something in it, even for empty text inputs. Each key will be set to an empty string.
To test for whether you should save data or not you'll need to validate all required form fields. Your code will probably look something like this. This is by no means complete or secure, but it'll point you in the right direction.
<?php
// store validation rules for required fields
$requiredFields = array(...);
// Store all validation errors here.
$errors = array();
foreach($requiredFields as $key=>$rule) {
if(empty($_POST[$key])) {
$errors[$key] = true;
}
else {
// you can perform more validation work on the value here.
}
}
if(count($errors) > 0) {
// form submit failure.
}
else {
// form submit success, save to db
}

You are sending output before setting the header, thus the specified headers are not sent.

Related

Geting error while using $_POST to insert data to database

I am trying to make a webapp using php. In that app i need to create Batch, Batch Subject etc. I have complited major part of this app. Althou it is working but i am geting an error notice like:
Notice: Undefined index: currentBatchId in C:\wamp64\www\sp\addBatchSubject.php on line 4
I have passed a batch Id from "batchview.php" page to add a batch subject using this code:
Add Subject
By using the below code:
$currentBatchId=$_GET['currentBatchId'];
I can receive that value and can show in this page with out any problem. But while i want to add some data to the database using this code:
if(isset($_POST['add']))
While i press [add} button it generate the error Notice, but data inserted to the database successfully. Now i want to remove the error.
What is the wrong? while data insert code is posting the data to the database, Is the $_GET try to get another value ?
NB: $_GET & $_POST are in the same page.
If I'm following you right I think you need to switch the order of your code around..
<?php
if(isset($_POST['add'])) {
// handle adding new
// make sure to header("Location: xxx.php"); to remove post data
exit(); // because we don't need to continue
}
if(isset($_GET['currentBatchId'])) {
$currentBatchId=$_GET['currentBatchId'];
}
// then maybe you also need to handle the no post / get request
if(!isset($_POST['add']) && !isset($_GET['currentBatchId'])) {
// handle this case
// maybe header("Location: blah.php");
// maybe exit(); here too because we don't have enough information to render the page
}
Hope that makes sense

How to get back from a PHP page called by an HTML <form> tag? [duplicate]

This question already has answers here:
Using HTML5 file uploads with AJAX and jQuery
(2 answers)
Closed 9 years ago.
I'm building an application that have to add a row in a MyPHP database with some data, included for each row an always different, small JPEG image. At the moment it is structured like this:
JavaScript
function fn_addrow() {
document.write('<form action="ADVBKMNGR-EventClass_MANAGE.php?Mode=ADD" method="POST" enctype="multipart/form-data">')
document.write('<table width="500"><th width="150"></th><th width="350"></th>')
document.write('<TR>')
// Form building
document.write('<input type="submit" value="Ok proceed">')
document.write('</form>')
}
PHP
elseif($WorkMode == 'ADD'):
$ID_ev = $_POST[ID_evcls];
$ID_ds = $_POST[Desc];
// Write all the data in a new row
$query='INSERT INTO '.$db_tabscelta.' (`Cod_App`, `ID_eventclass`, `Descrizione`, `Active`, `Logo_Eve`) VALUES ("'.$Station_ID.'","'.strtoupper($ID_ev).'","'.$ID_ds.'","1","'.mysql_real_escape_string($datimmagine).'")';
$result = mysql_db_query("AdVisual_02_", $query ,$connessione);
unlink($ID_logo);
imagedestroy($ID_logo);
The call at the PHP side works, the record is added, but my problem is that at the end I remain on the PHP page, while I would like to return to the calling page and redisplay the whole table. And, the address of the PHP is displayed in the user screen, and I would NOT like this at all.
Does anybody have suggestions?
Very important: I've tried the way with the XMLHttpRequest() command. It's fine, but I'm not able to upload the image at all.
Store the value of
$_SERVER['HTTP_REFERER']
Once you land on page. This will give you the URL
After finishing the job redirect to this URL
I think this for what you searching for form that submits through ajax even file upload is present
http://www.malsup.com/jquery/form/

I need help getting recaptcha to work

I recenlty had a site designed for me, but my dev used a really crappy generic captcha that fails half the time. I'm trying to replace it using a recaptcha, but I'm having trouble. I cannot figure out which *.php is used for 'processing' and which is used for the 'form'.
I didn't want to post the whole code, so here it is:
This is the 'form' page, as it has the form fields and etc embedded:
http://dl.dropbox.com/u/45666699/formcode.txt
Can someone please take a look at this code and tell me where I should put the private code for recaptcha? Also, how do I disable the "random_number" captcha that is already installed? Thanks!
the code for your existing captcha is on line 295, 296 and 297
require_once('recaptchalib.php');
$publickey = "6LfIUdISAAAAAKguxgdPCjZ6-OkVeu5tmcBaa7ug"; // you got this from the signup page
echo recaptcha_get_html($publickey);
Well you'll need the private key when you're trying to validate that the correct captch was entered (i.e. at the point where you're handling the form submission)
Which by looking at your code should start immediately after line 4
Using a project i did a while back, you would have something like so...
$recaptcha_error = NULL;
//set it to NULL initially
if(isset($_POST["btnsend"])){
include_once(INCLUDES_FOLDER."recaptcha-php-1.11/recaptchalib.php");
$resp = recaptcha_check_answer(RECAPTCHA_PRIVATE_KEY,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);
if($resp->is_valid){
//captch was gotten correctly
//continue with your normal code processing here
} else {
//wrong input -- captch was invalid -- give the person the error response
//mine is as below -- my usual way :)
$response = array(array("Something seems to be wrong with the captcha!","Please check that you entered it correctly or check the returned error message"),false,"w");
$recaptcha_error = $resp->error;
//make sure to do the above so u can use it when generating the captcha display
}
}
//You got the recaptch error (or left it as NULL above so you could do this)
//when generating your captch display as done on your lines 295, 296, 297
include_once(INCLUDES_FOLDER."recaptcha-php-1.11/recaptchalib.php");
echo recaptcha_get_html(RECAPTCHA_PUBLIC_KEY,$recaptcha_error);
Hope this helps (even if a little) :)
Cheers

HttpWebRequest POST and retrieve data from php script after login

Hello guys i am newbie to this stuff so i'll try to explain my problem.I am building application that retrieve data after login to php script that looks like this:
https://zamger.etf.unsa.ba/getrssid.php
(see the page source for php scirpt definition)
and definition(source) here:
Korisničko ime (UID):
Šifra:
After i login it shows me data that i must collect like this:
RSSID: 1321B312 (this is only data that it shows and nothing else)
I must do this with httpwebrequest but don't know how i tried to do it with POST(data) but it always give me the defnition of php script as response.But i need response to be like "RSSID: 1321B312" not as script definition mentioned above...please heeelp ASAP....
Define a form action to begin. So if the same page, getrssid.php, will be processing the form, use:
<form action="getrssid.php" method="POST">
After that, you must code getrssid.php to accept the incoming data via POST. POST data is stored in the PHP variables $_POST['inputname']. So if you have the input name as "login", the value entered will be stored in $_POST['login']. Same thing applies for the password.
So, here's a sample of what a basic POST data handling script should look like. Note that this script does not verify the login credentials, sanitize the inputs, or anything of the sort. It is just to show you how to handle POST DATA.
<?php
if (isset($_POST['login']) && isset($_POST['pass'])){
// Form is submitted.
echo 'RSSID: 1321B312';
} else {
// Form is not submitted.
// Display Form.
echo 'Form HTML here';
}
?>
If you are really server conscious, you should put the if ... else statement in the opposite order so the most likely outcome (form not submitted) is evaluated first.
Merry Christmas!

When form validation fails, how to pass error information for new try?

I'm developing a form validation class in PHP. When form validation fails, I can easily redirect again to the form's html page but without error information. I would like to redirect to the form's page with the specific errors about which fields failed and why.
How should I do this? Should I send information back via GET or POST? and in which format? Would really to see some code to see how people tackled this problem.
Thanks!
You could use the header() function. So just check the fields that are posted:
if(!$form->valid()){
$msg = "Form is not valid";
} else {
//Don't know if you want this
$msg = "Form is valid";
}
header("Location: [page where you came from]?msg=" . urlencode($msg));
Then in the page where you're redirecting to use
if(isset($_GET['msg]))
echo urldecode($_GET['msg']);
to echo the message. If you are using other get variables in the location of the header function, of course, use &msg=" . urlencode($msg). (You may also want to return the values that the user submitted, so the user doesn't have to fill out the entire form again if he makes 1 mistake.
I agree with user187291's suggestion of using $_SESSION because:
It doesn't hijack the URI like using $_GET (you would never want a static link to a status message). Users could press "back" to the page with your form and still see a status message because the URI says so.
Print and unset it in the same run, you won't be able to use it more than once (which is what you want?!)
If you're going with AJAX, $_GET is more widely used for retreiving values, which you are doing from the validation controller.
there are number of approaches
pass errors in GET when redirecting back like you said
use sessions to store error info, on the form page check Session for errors
do not redirect after failure, just output form again along with error messages
ajax submits
which one to use depends on the application. For most apps sessions method is most appropriate.
Something like this:
// Pseudo Code
function isValid($parm) {
$return = false;
if(preg_match(/^[a-zA-Z]+$/, $parm) {
$return = true;
}
return $return;
}
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$validFirstName = isValid($firstname);
$validLastName = isValid($lastname);
if($validFirstName == true && $validLastName == true) {
echo "It's all good";
// Do what you need to like, Submit
} else {
echo "Please retry";
// Display error message
}
I use a class to interface with $_POST, similar to the following:
// create the object
$post = new PostData();
// register your requirements... write whatever methods you need
// for each call,read $_POST, check criteria, and mark the field
// as good or bad...
$post->required ('LastName');
$post->required ('FirstName');
$post->numeric ('Age');
$post->optional ('MiddleInitial');
$post->regExp ('/\d{3}/','AreaCode');
$post->email ('Email');
// check the status
if (!$post->isValid ())
{
$_SESSION['FailedPostData'] = $post;
header ('Location: page.php');
}
// normal form processing
Then, on page.php, you can see if FailedPostData is in the session, read it to find the info entered last time, as well as which fields that failed. I use a template engine with macros that let me easily re-populate the form inputs and mark the failures. Otherwise you might end up with lots of code for a simple form...
You'll also need a mechanism to be sure that stale FailedPostData doesn't hang around in the session and confuse things.
I am doing it this way. Beginner in php so not sure if this is the best way to do:
HTML Form Page:
<form id="abc" method="post" action="validate.php">
PHP Page
..validation conditions..call a function if things do not match
function display_error($error) {
echo "<html><body><link href='style.css' rel='stylesheet' type='text/css'><br><center><h2>";
echo "$error";
echo "</h2></center><br><br>";
echo "<center><input type='button' value='Go Back' onClick='history.go(-1)' style='width:100px; height:28px; font-size:16px'></center>";
echo "</body></html>";
}
Clicking on the back button takes you back to the html page with the data intact.

Categories