Cannot modify header information [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am getting the following error from the following code, and I am not entirely sure why. If you could tell me how to fix it, that would be great. Thanks in advanced.
Warning: Cannot modify header information - headers already sent by (output started at...) on line 45.
<?php
// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$ref = isset($_GET['ref']) ? $_GET['ref'] : "";
// Protect against sql injections
// Insert the score
$retval = mysql_query("INSERT INTO $table(
site
) VALUES (
'$ref'
)",$conn);
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
mysql_close($conn);
?>
<?php
$url = $_GET['url'];
$loc = 'Location: '. $url;
header($loc);
exit;
?>

Take out the echo calls, you can't send information to the browser before the headers.
You can try something like this to still show if an error happens:
if(!$retval) {
echo "Unsuccessfull " . mysql_error();
}

If you change the headers you cannot output any text prior to to the header command otherwise the headers will already be sent.
ie.
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
Is outputting text before you change the headers.

Use Output Buffers: http://php.net/manual/en/function.ob-start.php
ob_start();
at the start and
ob_end_flush();
at the end.

What I generally recommend for situations like this, is save all output to the end, as gmadd mentioned, you can do the ob_start, but I prefer to store the data in a string without having to add the extra code (I know you can also designate this in the .htaccess file, I would go that route over adding the actual ob_start items).
What I would do:
$display = ""; // initiate the display string
// etc doe here
if($retval) {
$display .= "Successfull";
} else {
$display .= "Unsuccessfull " . mysql_error();
}
// end of the script right before ?>
echo $display;
?>
The ob_start method works and if you want to go that route, you can add this in the .htaccess file (given that allowoverride is set in your apache setup):
php_value output_buffering On
Again I still recommend the $display storage method, but that is my personal opinion.

Use:
<meta http-equiv="Refresh" content="0;url=http://www.example.com" />

Related

This PHP code refreshes a simple log, how can I get an "OK" when data has been successfully posted?

this is my first time using PHP, so I'm here because I don't even know how to look for the information I want (function name's, properties, etc). As I said before, my code receives a string with two variables and uploads it to a log with the format:
Raw time data, var1, var2
So, I want to add some lines that allow the code to send an "OK" confirmation when data has been successfully posted. How can I get it?
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "<pre>";
echo "hello! \n";
$file = 'measures.txt';
$time = time();
$row = "$time";
if ( isset( $_GET["T"] ) )
{
$new_measure = $_GET["T"];
echo "Temperature: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
if ( isset( $_GET["H"] ) )
{
$new_measure = $_GET["H"];
echo "Humidity: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
file_put_contents($file, "$row\n", FILE_APPEND | LOCK_EX);
echo "</pre>";
?>
Julio,
in your file_put_contents function you could simply echo a " OK" message if the file is successfully stored in the location you set. Now if you are trying to do email confirmation you would need to setup a mail function within your php application and have the proper smtp configurations so your server can do that.
I am assuming you have verification checks before the file is given to your file_put_contents function.

Redirect function not redirecting [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
I built a website locally with WAMP server, and everything worked fine, then ported over to web server on GoDaddy, and my redirect function suddenly stopped working.
Simple site at (www.minute.tech), you can test out the one form I have, goes to the form_processing.php, but should redirect back to the index page with a message. When you go back to the index page after the failed redirect, it still shows the proper message of "Booyah!...", and inputs the email into my database.
Any ideas why it won't redirect on my web server, but will on my local WAMP server with the same code? Cheers!
Here's my redirect function in sessions.php:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit();
}
Here's process_email.php where I redirect:
<?php require_once("sessions.php"); ?>
<?php require_once("db_connection.php"); ?>
<?php require_once("functions.php"); ?>
<?php
if(isset($_POST['submit']) && !empty($_POST['email'])){
//Process form
$email = $_POST['email'];
$email = mysql_prep($email);
$techcheck = (isset($_POST['techcheck'])) ? 1 : 0;
// 2. Perform database query
$query = "INSERT INTO signups (";
$query .= " email, techcheck";
$query .= ") VALUES (";
$query .= "'{$email}', $techcheck";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["good_message"] = "Booyah! We will keep you posted on progress.";
redirect_to("../index.php");
} else {
//Failure
$_SESSION["bad_message"] = "Failed to accept email.";
redirect_to("../index.php");
}
} else {
//This can be an accidental GET request
$_SESSION["bad_message"] = "That is not a valid email! Please try again.";
redirect_to("../index.php");
}
?>
You have to start object for header function sometimes
Add this code to all pages
<?php ob_start(); ?>
Do with JS.
<?php
function redirect_to($new_location) { ?>
<script>window.location="<?php echo $new_location; ?>";</script>
<?php } ?>
Remove all the empty spaces. Some server set-ups will be okay with output before the header redirect but the vast majority of servers will not redirect properly. Turn on error reporting and it will probably tell you have output before the redirect:
<?php
// ^---- Just do one open tag
require_once("sessions.php"); // Remove close tag, possible empty space after
require_once("db_connection.php"); // Remove close tag, possible empty space after
require_once("functions.php"); // Remove close tag, possible empty space after
// Remove the close and open php tags
if(isset($_POST['submit']) && !empty($_POST['email'])){
//Process form
$email = $_POST['email'];
$email = mysql_prep($email);
$techcheck = (isset($_POST['techcheck'])) ? 1 : 0;
// 2. Perform database query
$query = "INSERT INTO signups (";
$query .= " email, techcheck";
$query .= ") VALUES (";
$query .= "'{$email}', $techcheck";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["good_message"] = "Booyah! We will keep you posted on progress.";
redirect_to("../index.php");
} else {
//Failure
$_SESSION["bad_message"] = "Failed to accept email.";
redirect_to("../index.php");
}
} else {
//This can be an accidental GET request
$_SESSION["bad_message"] = "That is not a valid email! Please try again.";
redirect_to("../index.php");
}
// If you have no more content below this point, just remove the close php tag
// it is not required and is a possible source of empty space down the line...
Also, you should not be using mysql_ anymore, it is deprecated and removed in PHP 7. Also, bind parameters instead of doing this parameter right into the sql:
$query .= "'{$email}', $techcheck";

PHP preg_match() steam link validation error

What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...

500 Server Error in PHP

If you visit my script "page.php" in the URL. A 500 Error appears. If you submit through a form it works.
<?php
## send forgot pass
$a=$_REQUEST['email_address'];
include("template.funcs.php");
$yz = mysql_connect("","","");
mysql_select_db("", $yz);
$b=mysql_real_escape_string($a);
$d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
if (mysql_affected_rows()==0){
header("Location: cart.php?pass=notsent");
}else{
send_registration_email($b,'','','');
header("Location: cart.php?pass=sent");
}
mysql_close($yz);
?>
A 500 error is a server side error, and I've found the best way to fix this is to check the logs on your server.
On the other hand, looking at your code, you may not have defined $_REQUEST['email_address']. Try this:
<?php
if (isset($_REQUEST['email_address'])) {
## send forgot pass
$a=$_REQUEST['email_address'];
include("template.funcs.php");
$yz = mysql_connect("","","");
mysql_select_db("", $yz);
$b=mysql_real_escape_string($a);
$d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
if (mysql_affected_rows()==0){
header("Location: cart.php?pass=notsent");
}else{
send_registration_email($b,'','','');
header("Location: cart.php?pass=sent");
}
mysql_close($yz);
}
?>
I would assume this has something to do with $_REQUEST['email_address'] not being defined on normal page load...
Use useful variable names. Use indenting appropriately. Only escape input before inserting it into your database. Group often used functionality in functions. Don't use $_REQUEST. Fail fast. A few hints which massively increase your code quality.
Now have a look at this:
include("template.funcs.php");
function Redirect($to)
{
header("Location: " . $to);
exit();
}
if ($_SERVER['REQUEST_METHOD' != "POST" || !isset($_POST['email_address']))
{
Redirect("cart.php?pass=notsent");
// or redirect to your "forgot password" form
}
$mailAddress = $_POST['email_address'];
$dbconn = mysql_connect("","","");
mysql_select_db("", $dbconn);
mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".mysql_real_escape_string($mailAddress)."'");
if (mysql_affected_rows() == 0)
{
Redirect("cart.php?pass=notsent");
}
send_registration_email($mailAddress,'','','');
Redirect("cart.php?pass=sent");

Variable is not printing to the screen when I use echo in PHP

I'm trying to print the host/ip to the screen. But, it's printing: "Resource id #2" instead. I'm using SSH2_connection(). I read the doc page and know the the function parameters are host, port, methods ... but when I try fread($host), the host/ip is still not printing can someone give me some direction on this? Thanks!
Code:
<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($ssh = ssh2_connect('10.5.32.12', 22))) {
echo "fail: unable to establish connection\n";
} else {
if(!ssh2_auth_password($ssh, 'root', '********')) {
echo "fail: unable to authenticate\n";
} else {
echo "Okay: Logged in ... ";
$content = fread($ssh); //Line in question (want ip address to show here)
echo "$content <br>"; //Line in quesion
$stream = ssh2_exec($ssh, 'find / -name *.log -o -name *.txt');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
?>
I believe you need the parenthesis around the variabls as well when using double quotes. "{$content} <br>"
Have you tested with your own debug methods whether the $content variable contains information? You can set a value for the variable to test whether your echo statement is correct syntax.
$content = fread($ssh);
fread() reads from a file and puts the info into a resource handler for use later. I don't think you are using this in the right way currently.
I don't see where $ssh is being defined, but I assume it holds the IP you are wanting to output? If that is the case, just replace
$content = fread($ssh);
With:
echo $ssh;

Categories