PHP- setcookie cannot modify header information [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm new to PHP, and I tried to research this question but maybe I'm not asking right... I can tell from other posts/instructionals that I can not user header() or setcookie() after printing out HTML...
I commented out the header "redirects" - is there an alternative to this that I can put after HTML?
It's the setcookies that are failing at the moment:
what am I not seeing? I keep getting errors but my HTML is after the PHP:
if (!isset($_COOKIE["user"])) {
$sUserIdentity = $_POST["userIdentity"];
//username is not accepted as a get value
$sPassword = $_POST["password"];
$sEmail = $_POST["email"];
$cnn= odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
//check to see if email account or username already used
$sql2 = "select id from i_user where email = '" . $sEmail . "' or username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$id = odbc_result($result,"id");
if ($id == ''){
$cnnCreate = odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
$sqlCreate = "insert into i_user (username,email,salt,active) values ";
$sqlCreate .= "(";
$sqlCreate .= "'" . $sUserIdentity . "',";
$sqlCreate .= "'" . $sEmail . "',";
$rsCreate = odbc_exec($cnnCreate, $sqlCreate);
$sql2 = "select * from i_user where email = '" . $sEmail . "' and username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$expire=time()+60*60*24*30;
setcookie("uid", odbc_result($result,"id"), $expire);
setcookie("user", odbc_result($result,"username"), $expire);
if ($rsCreate){
$sMsg = "congratulations " . $_COOKIE["user"] . " and welcome ";
}
else {
$sMsg = "There was an error with the query";
}
}else{
$sMsg = "User " . $id . " already in DB";
//header('Location: ../fec/createuser.php?error=id');
}
}
//echo $sqlCreate;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Form</title>
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.2.custom.min.js"></script>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<style>
</style>
</head>
<body>
</body>
</html>

Make sure <?php is at the very beginning of the file, with no blank lines before it. And you can't print or echo anything before calling setcookie().

Why don't you use output buffering?
<?php
ob_start();
?>
<html>
<body>
...
</body>
</html>
<?php
ob_end_flush();
?>
This will put any output into a buffer and you can modify header information as long as the buffer isn't flushed.
This will also avoid problems in case a PHP warning or error message was sent to output before you write to the header.

Related

Show Output/Echo of PHP File executing at load on webpage

im trying to create my first website and Im clueless in this case.
So I have a MySQL-Database with a table. And I have a php-File called database.php which reads from the database and echos all the lines of a query:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now on my index.php I want to execute this php-code on calling/loading the webpage and print all the lines (data entries).
But i have no idea how to get the echo (=data entries) of the php file printed in the body of my webpage. I read about AJAX and using a js-script but I still wasnt able to figure it out.
Thanks for your help.
Option 1: Place your PHP code inside the HTML body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
Option 2: Create a separate PHP file containing your code above and include/require it into your body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
Option 3: Call your PHP file using an AJAX call (e.g. by using jQuery load()).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
If your index file is index.php then the PHP code will be run when you load the webpage. That is assuming, of course, that your web server (local or remote) has PHP installed.

MYSQL php database insert including image upload

Im trying insert user input into my databases. I want to add title and description into the advert table and an image to to the pictures table.
this is what i have come up with so far but it doesnt work at all. this is a posthandler.php page which will be called when the user presses submit. Variable at the top are assigned input names from the html page. I have both path name and blob in my pictures database at the moment to see which option will work best.
please help
<?php
session_start();
echo "You are signed in as ". $_SESSION['username'];
include 'mysql.php';
$title='title';
$des='des';
$image='image';
if(isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['title'])) {
$title= $_POST['title'];
} else {
$error = "Please enter a title for your Ad. <br />";
}
if (!empty($_POST['des'])) {
$des = $_POST['des'];
} else {
$error = "Please describe your item <br />";
}
if (!empty($_POST['image'])) {
$image=addslashes($_FILES['image']['tmp_name']);
$name=addslashes($_FILES['image']['name']);
$image=file_get_contents($image);
$image=base64_encode($image);
$filepath = "images/".$filename;
move_uploaded_file($filetmp,$filepath);
$image = $_POST['image'];
} else {
}
if (empty($error)) {
$conn= mysql_connect("localhost","km","data");
if (!$conn){
die ("Failed to connect to MySQL: " . mysql_error());
mysql_select_db("mdb_km283",$conn);
$sql = "INSERT INTO Advert (title, description) VALUES ('$_POST[title]','$_POST[des]')";
$sql2 = "INSERT INTO Pictures(image, Path) VALUES ('$_POST[image]' $filepath)";
mysql_query( $sql,$sql2, $conn );
//mysql_query( $sql2,$conn );
mysql_close($conn);
echo 'Upload successfull';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd"
>
<head>
<link rel="stylesheet" type=text/css" href="stylesheet.css">
Logout
<h1>ERROR - Please go back and fix the below:</h1>
</head>
<body>
<?php
if (!empty($error)) {
echo'<p class="error"><strong>Upload failed. Please go back and fix the below <br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} else {
echo '<meta http-equiv="refresh" content="0; URL=user.php">';
}
?>
</body>
</html>
$filename = $_FILES['image']['name'];
$filepath = 'image/' . $filename;
$filetmp = $_FILES['image']['temp_name'];
$result = move_uploaded_file($filetmp,$filepath);
if(!$result)
echo "Photo field was blank";
else
echo "uploaded";
then write ur mysql code here ....

adding comments using php and html

I was wondering if there were any kind people out there who would be able to help me with my php conundrum! Im very very new to php and I can't quite understand how to add a comment section that is functional. I have made a database table (named 'comments') to store all of the comments that users will submit. I am not sure of these things:
1. how to connect the comment section (on php page - home.php) to my database table (comments)
2. how to make the comments that people post be posted onto the the same page - home.php
I have done something wrong as now when I type in the URL this error comes up
Parse error: syntax error, unexpected '{', expecting '(' in .../home.php on line 34
Anyway I hope someone can help me!
Thanks
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
session_destroy();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
require_once("db_connect.php");
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
}else{ $ db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
require_once('recaptcha/recaptchalib.php');
$privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = "";
if (!$resp->is_valid) {
$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again (reCAPTCHA said: " . $resp->error . ")";
} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission
// e.g. Validate the data
$unsafe_name = $_POST['fullname'];
}
$message .= "Thanks for your input $unsafe_name !";
echo $message;
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
$query2 = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query2) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment";
}
$query3 = "SELECT * FROM comments";
$result3 = mysqli_query($db_server, $query3);
while($array = mysqli_fetch_array($result3)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<?php echo $recaptcha_form; ?>
<input type="submit" id="submit" name="submit" value="Submit form" />
</form>
</body>
</html>
Your below statement is syntactically incorrect,
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
Should be,
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {

PHP error - mysqli_query() expects parameter 1 to be mysqli, null given

I can't seem to correct my php error having looked at their answers and corrections. This is the error I get when the page is refreshed on the internet:
mysqli_query() expects parameter 1 to be mysqli, null given…
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
$db_hostname = 'xxxx';
$db_database = 'xxx'; //'Your database name'
$db_username = 'xxx'; //'your username';
$db_password = 'xxx'; //'Your password';
$db_status = 'not initialised';
$str_result = ' ';
$str_options = ' ';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$db_select = mysqli_select_db($db_server, $db_database);
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server)); }else{ $db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
//require_once('recaptcha/recaptchalib.php');
//$privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
//$resp = recaptcha_check_answer ($privatekey,
//$_SERVER["REMOTE_ADDR"],
//$_POST["recaptcha_challenge_field"],
//$_POST["recaptcha_response_field"]);
//$message = "";
//if (!$resp->is_valid) {
//$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
//} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission // e.g. Validate the data
//$unsafe_name = $_POST['fullname'];
//}
//$message .= "Thanks for your input $unsafe_name !";
//echo $message;
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['bedrooms'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
$query1 = "INSERT INTO comments (comment) VALUES ('$comment')";
$result = mysqli_query($db_server, $query1); if(!result){ die("Insert failed: " . mysqli_error($db_server));
}
$message = "Thanks for your comment";
}
function getPosts(mysqli $db_select){
$query1 = "SELECT * FROM comments";
$result1 = mysqli_query($db_server, $query1);
while($array = mysqli_fetch_array($result1)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Seems like you are overwriting your $db_server on the line that reads:
$db_server = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
So you should change that to be another variable like $result1:
$result1 = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
That said, are you actually connecting via $db_server anywhere else in your code? Look out for errors similar to what I just pointed out.
your $db_server is null which should a valid mysqli instance. this indicates either database connection failed or you didn't initialize $db_server or you overwritten it and looks like last option is true.
$db_server = mysqli_query($db_server, $query1)
this overwrites $db_server.
Insted of $db_server use $db_select. This may work as your $db_server variable does not have a connection to database. Its just a connection to server.

mysql_fetch_array(): error message

I'm trying to get a list of values to display upon a selection from a dropdown menu, but I think my SQL is not quite correct. This is a modification of a W3Schools tutorial http://www.w3schools.com/php/php_ajax_database.asp
I get the error: "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/virtual/hafdal.dk/public_html/test/getuser.php on line 28" when I try to do a selection.
I can't seem to find out what the error is, this function should be able to return multiple rows as I want it to. It might be because it's almost 2 am or just cause I'm dense ;-)
See an example here: hafdal.dk/public_html/test/getuser.php
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php header('Content-Type:text/html; charset=UTF-8');
$q=$_GET["q"];
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server) or die("Unable to select database: " . mysql_error());
$sql="SELECT * FROM view_bæjartal WHERE hrepparid = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Bær/Hús/Þurrabúð</th>
<th>Sýsla</th>
<th>Lat</th>
<th>Long</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo utf8_encode("<td>" . $row['bæir'] . "</td>");
echo utf8_encode("<td>" . $row['slysla'] . "</td>");
echo utf8_encode("<td>" . $row['hreppur'] . "</td>");
echo utf8_encode("<td>" . $row['lat'] . "</td>");
echo utf8_encode("<td>" . $row['long'] . "</td>");
echo "</tr>";
}
echo "</table>";
mysql_close($db_server);
?>
<body>
</body>
</html>
I hope someone can help :-)
The reason might that that w3schools tutorial, as usual, forgot the proper escaping function. This might lead to a syntax error, and due to the absence of any error checking code a failure with the loop.
Right after your mysql_query() add a mysql_error() call:
$result = mysql_query($sql) or print(mysql_error());
It could also just be your Unicode table name. (Then add backticks.)
You can display errors by calling echo mysql_error($db_server); right after your queried the database (with mysql_query($sql)).
Maybe there is a problem with your table/view name, but to know this for sure you need to have a look at the actual error message returned by mysql.

Categories