redirect to different website - php

I searched on the various solutions with respect to my question about redirecting to a different webpage - both on this site and google.com, but I can figure out why i keep getting the error in my specific scenario -
the error being: : "Warning: Cannot modify header information - headers already sent by (output started at test_ecis_lib_pdo.php:3) in login_submit3.php on line 10".
The code of login_submit3.php:
<?php
//! include config file; includes session_start() and ecp php library
include 'config.php';
if(DBLoginSubmitA($mysql_hostname, $mysql_username, $mysql_password,$mysql_dbname))
{
//redirect to webpage depending on SESSION paramter ['customertype'
switch($_SESSION['customertype'])
{
case 'member':
header("location:members3.php",true,'301');
die();
break;
case 'admincrm':
header("location:admincrm3.php");
die();
break;
default:
break;
}
};
?>
<!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>PHPRO Login</title>
</head>
<body>
</body>
</html>
The code of config.php:
/*** begin our session ***/
session_start();
//! include lib after session_start()
include 'test_ecis_lib_pdo.php';
/*** mysql hostname ***/
$mysql_hostname = 'localhost';
/*** mysql username ***/
$mysql_username = 'root';
/*** mysql password ***/
$mysql_password = 'xxxx';
/*** database name ***/
$mysql_dbname = 'xxx';
?>
The code of test_ecis_lib_pdo.php (a library with functions - and where the error refers to) starts with:
<?php
//GLOBAL VARIABLES
$error = "no error";
$timezone = date_default_timezone_set("Europe/Amsterdam");
$CUSTOMER_TYPE=array(
"interested"=>"1",
"member"=>"2",
"chair"=>"3",
"admincrm"=>"4",
"adminfinance"=>"4",
"adminenergymanagement"=>"5"
);
I checked that the test_ecis_lib_pdo.php file does not send send any tags or echo text before calling header() but i still get the error - where do i go wrong??? Please your help.

First,use
header("location: admincrm3.php");
instead of header("location:admincrm3.php");
second, what is your encoding ? if is utf-8 be sure is utf-8 without BOM
and be sure there is no space or another text before <?php
if you want to put text before send header, use ob_start() and ob_flush()

I'm not sure what is going on in your includes, but you may need to look at Output Buffering -- if you try and send headers after data has already been sent to the buffer your going to get that error.

Related

PHP and MySQL database search - removing database credentials from php code [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I found some code for a simple database search using PHP and MySQL and I was able to make it work. However, I decided it might not be such a great idea to leave my database username and password in the PHP code within the root folder. So, I found another code sample that demonstrated how to create a config.ini file outside the root, and use a dbconnect.php file to access the database credentials. I tried to implement this, but I'm not having any luck and was wondering if someone could show me what I'm missing (I only have a rudimentary grasp of coding and am trying to learn little by little). I have included the code for all of the component files (and I changed any username/passwords/servernames to generic placeholders). Below the code I have pasted the errors that are currently being shown when I submit the search form. Thanks!
index.php:
<!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>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
</body>
</html>
search.php:
<!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>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php require_once('./includes/dbconnect.php'); ?>
</head>
<body>
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length) { // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM details WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields
// details is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
if(mysql_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)) {
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
} else { // if there is no matching rows do following
echo "No results";
}
} else { // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
</html>
dbconnect.php:
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/home/cpanelusername/private/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],
$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
// Connect to the database
$connection = db_connect();
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
config.ini:
[database]
servername = localhost
username = username
password = password
dbname = username_database
Warning: mysql_real_escape_string(): Access denied for user
'root'#'localhost' (using password: NO) in
/home4/cpanelusername/public_html/...../search.php on line 29
Warning: mysql_real_escape_string(): A link to the server could not be
established in /home4/cpanelusername/public_html/......./search.php on
line 29
Warning: mysql_query(): Access denied for user 'root'#'localhost'
(using password: NO) in
/home4/cpanelusername/public_html/......../search.php on line 33
Warning: mysql_query(): A link to the server could not be established
in /home4/cpanelusername/public_html/......./search.php on line 33
Access denied for user 'root'#'localhost' (using password: NO)
This is because mysql_real_escape_string takes into account the current character set of the connection. As such, it needs a connection. :-)
Please try to connect database using below code and please let me know if you have any problem.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Scrubbing the strings that come from userland isn't sufficient to prevent SQL injection attacks. The standard way is to use a prepared query. E.g.:
$stmt = mysqli_stmt_init($this);
$result = array();
$okay = mysqli_stmt_prepare($stmt, "SELECT * FROM details WHERE (title LIKE ?) OR (text LIKE ?)");
if ($okay)
$okay = mysqli_stmt_bind_param($stmt, "ss", "%$query%", "%$text%")
else
[handle error]
if ($okay)
$okay = mysqli_stmt_execute($stmt);
else
[handle error]
if ($okay)
$okay = mysqli_bind_result($stmt, $row);
else
[handle error]
if ($okay)
while (mysqli_stmt_fetch($stmt))
array_push($result, $row);
else
[handle error]
mysqli_stmt_close($stmt);

Enabling both a PHP parser and an Include statement

I have an existing SHTML page with a few INCLUDE statements for menu's. This has worked well. To this point, my .htaccess file has looked like:
Options +FollowSymLinks
And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->
I have a new need to add some PHP code to the main page. The PHP code queries a Mysql database to return a single row. If the row exists in the database, I want to show it on the SHTML page. If the row does not exist, do nothing. Here's the PHP 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>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Message is: " . $row["notice"]. "<br>";
}
} else {
echo "";
}
mysqli_close($conn);
?>
</body>
</html>
When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text. When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser. For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
SetHandler application/x-httpd-php5
</FilesMatch>
However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work. How can I enable both the PHP and #Include code together in the same SHTML page? Thanks very much for looking at this.
In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');
There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm

PHP - cookies and header location: Cannot modify header information - headers already sent by [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
This is my user log in page. After the user enter log in details, I want to store cookie files and direct the user to home page. However, I keep getting this error I have tried every possible way to solve it and I have read other questions posted on here but nothing did solve my problem... am I missing something here? what could it be?
<?php //<--- line 4
error messages:
Warning: Cannot modify header information - headers already sent by (output started at /www/99k.org/p/h/o/phoneclassmate/htdocs/login.php:4) in /www/99k.org/p/h/o/phoneclassmate/htdocs/login.php on line 6
The issue is that you're trying to send HTTP headers (Location:) after HTML code.
You should refactor your code to avoid that; or as a hack you can work around it using output buffering, that'll allow you to modify HTTP headers after you started outputting your HTML content. Not a great way to handle the problem IMHO but good to know anyway; see
http://ca.php.net/manual/en/function.header.php#refsect1-function.header-notes
You need to enclose your if statement block as shown below:
if($_POST['submit']) {
$hour = time() + 3600;
setcookie('username', $_POST['username'], $hour,'/');
setcookie('password', $_POST['pass'], $hour,'/');
header("Location: tutorhomepage.php");
}
Also, you need to move connection etc. part just after the above segment.
<?php
if($_POST['submit']){
$hour = time() + 3600;
setcookie('username', $_POST['username'], $hour,'/');
setcookie('password', $_POST['pass'], $hour,'/');
header("Location: tutorhomepage.php");
}
//------ server and mysql connection
$connection = mysql_connect('mywebsite', 'username', 'password') or die('Unable to connect');
mysql_select_db('myDB') or die('unbable to select DB');
//------log in cookie check
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
$pass = $_COOKIE['password'];
$check = mysql_query("SELECT * FROM tutors WHERE username = '$username'") or die(mysql_error());
while ($info = mysql_fetch_row($check)) {
if ($pass != $info[1]) {
} else {
header("Location: /tutorhomepage.php");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body><?php
//------- if form is submitted
if (isset($_POST['submit'])) {
// check if the user enetered login details
if (!$_POST['username'] | !$_POST['pass']) {
die('You must enter the required data.');
}
// and so on

php header command isn't working

I'm having a problem getting this code to work on the website that I'd like to launch soon. In particular when I sign in the header won't redirect after a successful login. I have used this code before many times and I've never had a problem with it. The only difference now is that I'm using a different server and a different database. Here's the code that is giving me trouble:
<?php
/*set all the variables*/
$email = $_POST['email'];
$password = sha1($_POST['password']); /* hash the password*/
$conn = mysqli_connect ('servername', 'username', 'password', 'databasename') or die('Error connecting to MySQL server');
/*select the id from the users table that match the conditions*/
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count = mysqli_num_rows($result);
if ($count == 1) {
echo 'Logged in Successfully.';
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
/*If invalid prompt them to adjust the previous entry*/
else {
echo '<h2>Invalid Login</h2><br />';
echo '<h2>Click HERE to go back and adjust your entry.</h2>';
}
mysqli_close($conn);
?>
It's not a matter of it connecting properly because I get the message 'successful Login' but it won't redirect at all.
Thanks for all the answers, I tried removing the echo but all I get now is a blank page, I thought maybe it was the browser I was using so I switched to another and I still just get a blank page, any other suggestions?
You cannot echo anything before your header statement.
echo 'Logged in Successfully.';
This is causing the header call to not work.
if ($count == 1) {
echo 'Logged in Successfully.';
//this statement is creating problem
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
This is because you are echoing something berfore header
You should use ob_start() at start and ob_end_flush() at the end of the document..
or do not echo before header().As we found you haven't turned on the error.So turn it ON.
You can't be posting the header after the echo... if this actually worked you'd never see the text (it would simply redirect). (To fix remove/comment out the echo line)
Also the location header requires an absolute/full URL (although many browsers seem to cope with relative URLs).
If you want to do it this way (show some sort of status before hand), use an HTML or Javascript redirect that triggers after a couple of seconds.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logged in Successfully.</title>
<meta http-equiv="REFRESH"
content="5;url=http://www.example.com/users_table.php"></HEAD>
<BODY>
Logged in Successfully.
</BODY>
</HTML>
Javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Logged in Successfully.</title>
</HEAD>
<BODY onLoad="setTimeout(function() {
window.location='http://www.example.com/users_table.php'},5000)">
Logged in Successfully.
</BODY>
</HTML>
Better yet, allow the users_table.php page to display a successful login message and use the header-location redirect.

Troubleshooting database-backed custom session handler - values are not persisting between page loads

I am trying to get my custom sessions working but my variables do not persist from page to page. If I remove the require line and replace it with session_start(); it works fine. All of these files are in the same directory and I have session.save_handler set to user in my php.ini file.
first HTML page
<?php
require("sessionSetup.php");
$_SESSION['test'] = "session test";
session_regenerate_id();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>sessions test</title>
<script type="text/javascript">
<!--
alert("Test: <?php echo $_SESSION['test'];?>");
//-->
</script>
</head>
<body>
Click here to go to session2.
</body>
</html>
second HTML page
<?php
require("sessionSetup.php");
//session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>sessions test</title>
<script type="text/javascript">
<!--
alert("Test: <?php echo $_SESSION['test'];?>");
//-->
</script>
</head>
<body>
Click here to go to session.
</body>
</html>
sessionSetup.PHP
<?php
session_set_save_handler('_open','_close','_read','_write','_destroy','_clean');
session_start();
function _open(){
global $_sess_db;
if($_sess_db = mysql_connect(host,user,password)){
return mysql_select_db(db, $_sess_db)or die("cannot select DB");
}
return false;
}
function _close(){
global $_sess_db;
return mysql_close($_sess_db);
}
function _read($id){
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "SELECT data FROM session WHERE id = '$id'";
if ($result = mysql_query($sql, $_sess_db)) {
if (mysql_num_rows($result)) {
$record = mysql_fetch_assoc($result);
return $record['data'];
}
}
return '';
}
function _write($id, $data){
global $_sess_db;
$access = time();
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);
$sql = "REPLACE INTO session VALUES ('$id', '$access', '$data')";
return mysql_query($sql, $_sess_db);
}
function _destroy($id){
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "DELETE FROM session WHERE id = '$id'";
return mysql_query($sql, $_sess_db);
}
function _clean($max){
global $_sess_db;
$old = time() - $max;
$old = mysql_real_escape_string($old);
$sql = "DELETE FROM session WHERE access < '$old'";
return mysql_query($sql, $_sess_db);
}
?>
I have replace the database login stuff with dummy information here. Also when I check with phpadmin there is no info in my sessions db. All I get on the second HTML page is a null value. I have been working on this for a while now and have made no progress. Any help I could get wiould be greatly appreciated.
The code looks ok.
Make sure your database table used for storing session data is correctly set up, because session handler functions don't seem to have any error checking.
The most probable cause of your sessions not working is either id or data column of session table not big enough to hold full info. Access should be int, try different sizes of varchar for id and data.
As emphasized in the php manual page on session_start() it MUST go before anything is outputted to the browser. Most likely your required file (sessionSetup.php) has a couple empty bits at the beginning or end which are not being interpreted as php and therefore being outputted to the bowser. To fix this simply put session_start before require("sessionSetup.php"); (also don't forget to remove session_start from your session setup file once you do that). OR you could create an output buffer.

Categories