Solved

how to us ob_start in a function

Posted on 2016-10-30
11
53 Views
Last Modified: 2016-11-01
I am trying to use ob_start()  within a function but I just get a blank page instead of redirecting to the desired page. I do have error reporting on.

function login_form($link){


	if(isset($_POST['submit'])) {
		

			$message = "";
			$email = $_POST['email'];
			$sp_email = filter_var($email, FILTER_SANITIZE_EMAIL);
			$stmt = $link->prepare("SELECT `sp_password` FROM `service_providers` WHERE `sp_email` = ?");
			$stmt->bind_param("s", $sp_email);
			$stmt->execute();
			$result = $stmt->get_result();
			if($result){
				$row = $result->fetch_assoc();
				$password = $_POST['password'];
				$db_pass = $row['sp_password'];
				if(password_verify($password, $db_pass)) {
				ob_start();
				header("location:dashboard.php");
				exit;
				ob_end_flush();
				
			} else {

				$message = "<div class='alert alert-danger'>Invalid login credentials</div>";
			}
		}
		return $message;
	}
}

Open in new window

0
Comment
Question by:Black Sulfur
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 2
11 Comments
 
LVL 83

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 100 total points
ID: 41866105
'ob_start' is for buffering the HTML output of a PHP script.  It is not going to do anything the way you are trying to use it.  Putting 'ob_end_flush' after 'exit' means it never gets called because the script Stops at 'exit'.  I think that section is probably formatted wrong.  You still need to use the proper formatting around that code.

http://php.net/manual/en/function.ob-start.php

I never use 'ob_start' myself.  Since the 'header is executed as soon as it is encountered, you don't need 'ob_start'.  I would write it this way.
if(password_verify($password, $db_pass)) {
	header("location:dashboard.php");
	exit;
}

Open in new window

1
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 41866207
This is a really good opportunity to follow the examples in these articles:
https://www.experts-exchange.com/articles/2391/PHP-Client-Registration-Login-Logout-and-Easy-Access-Control.html
https://www.experts-exchange.com/articles/28768/Password-Hashing-in-PHP.html

This article discusses some of the kinds of conditions that make sense with ob_start()
https://www.experts-exchange.com/articles/4423/Warning-Cannot-modify-header-information-headers-already-sent.html

From a design perspective, functions that might or might not return values or return control are kind of scary to me.  Why not let the function simply verify (True or False) whether the client login information is acceptable?  This would tighten up the responsibilities of the function and make it easier to test.

From a performance perspective, any SELECT query that expects zero or one result in the results set should have LIMIT 1.  No need to do a table scan.

From a variable naming perspective, the password hash stored in the database should probably be named in a way that clearly indicates it's not  a password -- it's a hash.  So maybe change the column name to something like password_hash.

This code might be tightened up (there is no advantage to proliferating variables, even inside the scope of a function).

Original
$row = $result->fetch_assoc();
$password = $_POST['password'];
$db_pass = $row['sp_password'];
if(password_verify($password, $db_pass)) { /* ...

Open in new window

Tighter
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['sp_password'])) { /* ...

Open in new window

Just some thoughts...
0
 
LVL 1

Author Comment

by:Black Sulfur
ID: 41867507
Thanks guys, viewing the answers on my mobile EE app. Will try them out when I'm in front of my PC tomorrow...
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:Black Sulfur
ID: 41868204
@ Dave, I had it exactly as you suggested:

if(password_verify($password, $db_pass)) {
	header("location:dashboard.php");
	exit;
}

Open in new window


but I get the error: Cannot modify header information - headers already sent

This is the line causing the problem apparently :

<?php echo login_form($link);?>

Open in new window


I looked it up and it mentions something about whitespace in the php code. I checked the code and there isn't any white space that I can pick up. I also read that output buffering could solve this issue.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41868214
Let me try this one more time...
https://www.experts-exchange.com/articles/4423/Warning-Cannot-modify-header-information-headers-already-sent.html

Here is the man page for ob_start()...
http://php.net/manual/en/function.ob-start.php

TL;DR...
Put ob_start() as the first function call in your "top-level" script.  Do not put it in any other scripts.  Do not call it more than once.  PHP needs to be the first thing executed when your web page loads, before anything else whatsoever.  Ob_start() needs to be the first PHP instruction executed, before anything else whatsoever.  Poof!  Problem gone! ;-)
0
 
LVL 1

Author Comment

by:Black Sulfur
ID: 41868215
@ Ray,

I keep forgetting to put LIMIT 1 at the end of my queries! I need to remember that. Noted, regarding changing column name to password_hash and proliferating variables. It just makes things clearer in my mind to do that which is why I do it.
Would you be able to briefly explain the function true/false logic? I don't really understand it. In my mind, the code is saying that if the email address exists in the database and the password hash in the database matches the input from the user, then the user is to be redirected...

if(password_verify($password, $db_pass)) {
	header("location:dashboard.php");
	exit;
}

Open in new window


But are you saying it should rather just return true?
0
 
LVL 1

Author Comment

by:Black Sulfur
ID: 41868216
@ Ray, sorry. Am reading that link now...
0
 
LVL 1

Author Comment

by:Black Sulfur
ID: 41868224
Okay, I read it and I put it the ob_start code on the actual page calling the function and it works fine now. I noticed you haven't got this:

ob_end_flush();

Open in new window


I read somewhere that if you use ob_start() then you should use ob_end_flush as well. Any truth in that?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41868237
Ob_End_Flush() is always done by the script termination / garbage collection process.  You probably do not need it in your code.  If you read something that said you needed it, check the age of the publication.  That sounds like a PHP4 thing, and PHP4 is obsolete.  I've never found a need for ob_end_flush() in 20 years of PHP development!
1
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 41868685
I have only used ob_start a couple of times in 15 years.  I tend to build my code so that it isn't needed.
1
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41868750
@Dave: Agree - we try to build our code so that ob_start() is not needed.
 
That said, there is a measurable performance advantage to ob_start(), whether or not it's needed because of script logic.  With ob_start() you only need to connect to the server output engine once - when the script ends.  Without it, any time PHP sends a burst of output, it has to connect and disconnect.  Not a huge amount of overhead, but it's nice to avoid the overhead in a deployed application.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Ajax and PHP 4 47
MSSQL - Lock Row from reading by other programs 9 58
MySQL limit and not so limited 13 38
Php logic to add to date card 9 39
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question