What is proper way to calling session_start() - php

I have two shared host.
my problem is realated with calling session_start().
In my localhost and one of my shared host. session start works well with user notice that : cannot call header. then i used to write the below code:
<?php
if(! isset($_SESSION)){
session_start()
}
?>
But in another host, it still echo message that "Notice: cannot start session()..."
also my problem that session doesn't starts in first visit. When I refresh my browser window again then starts session. what is relation between client and server side. again what is wrong with my session_start() ? please help me.
May anyone tell me that what is the proper way to calling a session_start() which will never fail. and where should I call. very top of the page or anywhere in the configuration file. a little example will help me surely.

Two simple things:
1. Always call session_start unconditionally.
2. Always call session_start before you output anything on the page.
So you should do it like this:
<?php
session_start();
// and now anything else
In particular, be aware that you can violate directive #2 in many different ways, e.g. by:
Explicitly printing anything yourself with echo etc.
Having any characters at all in your PHP script before the <?php tag
Inlcuding other scripts that do the above
There are lots and lots of questions here on SO that describe point #2 and how to solve it.

Related

session cache error only on two pages - All other pages are working fine

I developed a website from a developer. My website was working fine. All of a sudden I discovered that whenever I click on Contact Us link, I get an error
"Warning: session_start() Cannot send session cache limiter - heards
already sent (output started at /home/xxx/public_html/contact.php:1)
in /home/xxx/public_html/connection/config.php on line 2"
This was not happenning before. The developer is not giving me support and is ignoring my emails. So I searched and researched for it a lot on the Internet and found that there is something wrong in the way session_start() is defined.
Here is the code of contact.php
<?php
include("connection/config.php");
session_start();
?>
<?php
if(isset($_POST['enquiry2']))
{
.
.
.
}
?>
<!DOCTYPE html PUBLIC
.
.
.
<?php include "footer.php"; ?>
</html>
Code of config.php
<?php
session_start();
error_reporting(0);
if ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '192.168.1.111')
{
$con=
.
.
}
else
{
$con=
.
.
}
error_reporting(E_NOTICE ^ E_WARNING ^ E_ALL);
require_once("logic/class.config.php");
.
.
<?php date_default_timezone_set("Asia/Kolkata");?>
In lot of articles I read that session_start() should be right at the top of the page so I reversed the second and third line of contact.php but it gave me same error pointing to contact.php file.
"Warning: session_start() Cannot send session cache limiter - heards
already sent (output started at /home/xxx/public_html/contact.php:1)
in /home/xxx/public_html/connection/contact.php on line 2"
Earlier it was pointing to config.php fle
Same thing is happening in registration page. I have three files register.php, register1.php and register2.php. The same error occurs only on register3.php when it loads the page and once again when submit button is clicked.
I request if someone can help me identify the problem.
Thanks.
EDIT
As suggested by Premalatha:
Removed session_start(); from contact.php -> but same warning.
Placed session_start(); on top of include("connection/config.php"); -> but same warning.
As suggested by Alok:
I dont know how to check if I am sending content or calling header somewhere before session_start(). The session_start() line is either on top or in the second line with first line being include("connection/config.php"); that I tried interchanging upside down with no help.
One thing I fail to understand that other .php files also have the same coding then why this warning comes only on contact.php? Similarly, register1.php, register2.php also have same coding but why the warning comes only while loading and unloading register3.php. All was working before, this started all of a sudden and I dont remember doing any changes in any of these files so the issue may be something else. I also wanted to try suggestion from wangpeng but I could not find the php.ini file anywhere in cpanel. Moreover, I did not figure out how to check if the file's code if it is UTF8-BOM. Also where exactly should i put OB_START() because i am unable to identify where is the header.
EDIT2
By the way, this warning does not affect the functioning of the site. The error just appears and then disappears. However, it disturbs the css, all fonts and images become bigger and the look of the page goes for a toss. Can someone tell me how to ignore this error so that the system doesn't show it at all?
session_start();
is already included in config.php file.
You can remove in contact.php file and it would start working without any issues.
If you still face any issues then you can place session_start(); line of code in contact.php above the include statement.
1.php.ini session.auto_start = 0 to session.auto_start = 1 .
2.check the file's code is UTF8-BOM? yes,UTF8-BOM to UTF8.
3.OB_START();before header
Headers already sent means PHP script sent the headers to the server already, and it cannot be modified now.
Which means before session_start() your script must be sending content or calling header to the server and and after sending it script is calling session_start() function which tries to modify the headers.
Solution in your case is to check you're not sending content or calling header some where before session_start() in both the scripts.
Update:
Try this,
Locate all the *.php files pointed in contact.php and find session_start(); in it.
Replace it with the following,
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Above code will make sure that you don't start the session again if it is already being started.
I never thought the solution would be this !
However, when I read same thing from four different people, I had to try this and it worked ! I had few leading, trailing and blank spaces in my include files. I got rid of them and my problem was solved.
Here is the article that helped me a lot
Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"
if you have blank space after php tag (or html or any output) in your include files then this error will come. -by Imdad
The reason for getting this issue is 99% likely to be trailing spaces at the end of your include files (yes - I know it sounds unlikely but just try it). Remove the trailing spaces, newlines etc... and all will be well. -by Chris B
a white-space before <?php also send for output and arise error. Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line -by Biswadeep Sarkar
For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending. -by Ross

Problems with my log in and register scripts

I am getting pretty annoyed with an issue with my log in and register scripts that are not working. The funniest thing is that for two weeks ago I used the exact same scripts in another website in another server and it works awesome!
ISSUE
When I try to register or log in I am not redirected to the page I was supposed to be. On register.php the user gets registered (I can see it on the database) but I am not redirected to the login.php, instead the script get's crashed on the message "redirecting you to xxxx.php". Here you can read my scripts.
I took contact with my server (ipage) and asked if something was going wrong with their system. I got 3 different and crossed answers:
1st) I was able to replicate your issue. I did some preliminary troubleshooting and was not able to get to the root cause of the issue.
2nd) They answered me later that they were able to register new users and log in with no problem
3rd) Final answer was that the issue was on my scripts
I am not sure of what is happening here because the scripts are not working (on the opposite to what they say). I wonder if they are lying because they simply are no good or can't find out the cause of the problem. Anyway, the error log says the following:
*"20131014T033118: url.org/folder/login.php
PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /hermes/bosweb26a/b366/ipg.domainname/folder/folder/common.php:1) in /hermes/bosweb26a/b366/ipg.domainname/folder/folder/common.php on line 77 "*
Line 77 is: header('Content-Type: text/html; charset=utf-8');. If I take it out, the error just passes on to another line...
Presuming that I already debugged the scripts and found no error, could this be due to the server's quality? (PHP version f.i.?)
You can put session_start() on the first line ok common.php
You need to make sure session_start() is called before calling header(), or echoing any content. So in login.php, you need to make sure session_start() is either at the top of the page, or you need to move it so it is called much earlier in your script, at least before any header() calls.
Just switch round session_start and header('Content-Type: text/html; charset=utf-8'):
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
Have you got a space before <?php as the top of common.php? If you do you need to remove it.
Personally i use ob_start(); after the session_start(); and ob_flush() at the end of the file;

Trouble with calling session_start() at the start of all PDO pages

Most of my pages use Sessions, but I'm switching to PDO and calling session_start() at the start of every page is causing problems with passing headers. I've done several hours of research and am still unclear what to do about it.
Edit - What I've been doing: The 1rst line of the sign up/sign in documents as well as auth.php is session_start();, and the 1rst line of all pages the user visits subsequent to sign up/sign is require_once('auth.php');
I'm currently passing the user id to every page with $_SESSION['SESS_USER_ID']
When they sign up/sign in I connect it like this:
$member = $stmt_user->fetch();
$_SESSION['SESS_USER_ID'] = $member['user_id'];
And on every subsequent page I call it like this:
$user_id = $_SESSION['SESS_USER_ID'];
As per the manual
As of PHP 4.3.3, calling session_start() after the session was
previously started will result in an error of level E_NOTICE. Also,
the second session start will simply be ignored.
Does this mean that I no longer need to call it on every page and can just call it once when the user commences a session?
If not, what is the simplest way to do deal with this issue?
If you are using a framework, you likely just need to call it once in that framework. If each of your requests go to different php pages, then you need to make sure it gets called at least once per request (preferably as soon as possible).
You need to make yourself a bootstrap file.
A file with all common operations performed on the every page - session start, connect to database, set global variables, etc.
And then include this file into every script called.
So, you'll be sure that you have everything you need, yet called everything once.
Though I don't understand what does this question to do with PDO (as well as a previous one).
PDO is just a database driver and have not a slightest relation to headers, sessions and the like.
You can use ob_start and ob_end_flush to buffer your outputs, so you can actually do this:
<?php
ob_start();
echo '42';
session_start(); // still works because output is buffered
ob_end_flush();
?>

Very strange php include behavior..

I am experiencing some very strange behavior when including a php file.
I need to load a script that is not on the same domain as the page that will be calling it.
I have already created a system that works using cURL, but I just recently found out that many of the sites that will need to have access to this script, do not have cURL installed.
I did, however, notice that these sites have allow_url_fopen set to on. With this knowledge I got started creating a new system that would let me just include the script on the remote site.
Just testing this out, I coded the script test.php as follows:
<?php
echo("test");
?>
I include this script on the remote page using:
<?php
include("http://mydomain.com/script.php");
?>
and it works no problem and "test" is printed at the top of the page.
However, if I add a function to the script and try to call the function from the page, it crashes.
To make it worse, this site has php errors turned off and I have no way of turning it on.
To fully make sure that I didn't just mess up the code, I made my test.php look like this:
<?php
function myfunc()
{
return "abc";
}
?>
Then on the page including the file:
<?php
include("http://mydomain.com/script.php");
echo(myfunc());
?>
And it crashes.
Any ideas would be greatly appreciated.
This is not odd behavior, but since you load the file over the internet (note in this case the World Wide Web), the file is interpreted before it is sent to your include function.
Since the script is interpreted no functions will be visible, but only the output of the script.
Either load it over FTP or create an API for the functions.
My guess: The PHP of http://mydomain.com/script.php is interpreted by the web server of mydomain.com. All you're including is the result of that script. For a simple echo("test"), that's "test". Functions do not produce any output and are not made available to the including script. Confirm this by simply visiting http://mydomain.com/script.php in your browser and see what you get. You would need to stop mydomain.com from actually interpreting the PHP file and just returning it as pure text.
But: this sounds like a bad idea to begin with. Cross-domain includes are an anti-patterns. Not only does it open you up to security problems, it also makes every page load unnecessarily slow. If cross-domain inclusions is the answer, your question is wrong.
You are including the client side output from test.php rather than the server-side source code. Rename test.php to test.phpc to prevent executing the script. However this is dangerous out of security point of view.

providing login check, page redirect in all pages in php

I am making a simple Dynamic Website using PHP, where i allow the user to login and then access specific pages. So here's what i have done so far.
The logged in values are taken though $_POST variables in a php script where it fetches values from database for registered users. If the user is found i do the following:
session_register('userid');
$_SESSION['userid'] = $username;//this is taken from $_POST
$_SESSION['accesslevel'] = $access;
at the beginning of the php script i have put session_start();
Now here comes my problem.
At every page now i have to check if the user is allowed to view that page or not, if he ain't then he must be redirected to login.php, if he is then the page load must continue.
Now so far what i have learnt is that only way to maintain values across php pages is to use $_SESSION variables, and which ever page i am using Session Variables i must write session_start() on each page as the first line, else i will be getting Headers Already Sent error..
Strangely i exactly have done that but still get erros with the "headers already sent".
SO i want to what is the best way to design a website, where i have to use Session variables across most of the pages, and keep these common checks at a common place..
Can i use include() feature some how?
Are sessions only way to communicate data across php pages.
What is a better way?
I have the following code :
<?php
session_start();
if(!isset($_SESSION['user']))
{
$_SESSION['loc'] = "adminhome.php";
header("location:ettschoollogin.php");
exit();
}
?>
Which resides on top of every page which wants to check if the user has logged in.
And this is teh script to check for login
<?php
session_start();
include("connection.php");
$userid =$_POST['userid'];
$userpwd =$_POST['userpwd'];
$query="Select UNAME,UPASSWORD,SCHOOL,uaccess from schooluser where uname = '$userid'";
$result=mysql_query($query) or die("couldn't execute the query");
$row=mysql_fetch_array($result);
$useraccess = $row["uaccess"];
$school =$row[2];
if(($row[0]==$userid)&&($row[1]==$userpwd))
{
session_register('userid');
$_SESSION['userid']=$userid;
$_SESSION['school']=$school;
if($useraccess =="admin")
{
header("Location:adminhome.php");
}
if($useraccess !="admin")
{
header("Location:school_main.php");
}
}
else
{
header("Location:ettschoollogin.php?err=1");
}
?>
i was aware of the common error of having extra spaces after "?>", BUT I STILL GET IT.
Thanks guys, i missed out and the "connection.php" file actually had extra spaces after "?>" i had removed it before, but some how the file got rewritten again.Thanks a lot.
Yes, you can use include. Put all your common functions in a separate php file and "include" it at the top of each file.
You can use cookies to store information (typically just an id that you use to look up additional information in the PHP page). Normally, PHP sessions are handled using cookies though. See setcookie in the docs.
You are probably getting the error messages due to stray characters outside of a <?php ?> block. A common error is to have an extra blank line at the end of an include file, after the ?>. That blank line will be output and your headers will have been sent. If that isn't the problem, you will just need to make sure you move the session related code above any code that might generate some output (eg by using print or echo).
•Can i use include() feature some how?
Yes. You can do whatever you want before your session_start() call, only, you must not have outputted anything, not even a single space or character. Probably you have already outputted something, maybe on an automatic inclusion or apache prepend.
•Are sessions only way to communicate data across php pages.
•What is a better way?
Other ways are cookies, post and get parameters. But sessions are the only way to securely pass data among pages without sending them to the client and back (which may pose security risks)
Write ob_start(); at the top of your code and then you dont get the error of "headers already send"

Categories