Solved

how to us ob_start in a function

Posted on 2016-10-30
11
33 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
  • 5
  • 4
  • 2
11 Comments
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 100 total points
Comment Utility
'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 108

Accepted Solution

by:
Ray Paseur earned 400 total points
Comment Utility
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
 

Author Comment

by:Black Sulfur
Comment Utility
Thanks guys, viewing the answers on my mobile EE app. Will try them out when I'm in front of my PC tomorrow...
0
 

Author Comment

by:Black Sulfur
Comment Utility
@ 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 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:Black Sulfur
Comment Utility
@ 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
 

Author Comment

by:Black Sulfur
Comment Utility
@ Ray, sorry. Am reading that link now...
0
 

Author Comment

by:Black Sulfur
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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 82

Expert Comment

by:Dave Baldwin
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
@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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now