setcookie() function not working [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I am currently working on a little website on which I have to make an account creation system. In order to know whether the user is already connected or not I would like use cookies cuz this was looking like the easiest way. However, after checking the official documentation on php.net, and some other forums, I'm still not able to create my cookie. Here is my code :
function connexionOK() {
$cookieName = "CookieCo";
$cookieValue = "true";
$isSent = setcookie($cookieName, $cookieValue, time() + 3600, "/");
if($isSent) {
echo '<script type="text/javascript">';
echo "alert('Cookie envoyé');";
echo "</script>";
}
else {
echo '<script type="text/javascript">';
echo "alert('Cookie failed');";
echo "</script>";
}}
So the page is indeed alerting me 'Cookie failed'.
Thanks for everyone who've been trying to help me ! :)

You may be calling this function after headers were already sent:
try this and see if you get an exception:
function connexionOK() {
$cookieName = "CookieCo";
$cookieValue = "true";
if(headers_sent()){
throw new Exception('Cannot set cookie, headers already sent');
}else{
$isSent = setcookie($cookieName, $cookieValue, time() + 3600, "/");
if($isSent){
echo '<script type="text/javascript">';
echo "alert('Cookie set');";
echo "</script>";
}else{
echo '<script type="text/javascript">';
echo "alert('Cookie not set');";
echo "</script>";
}
}
}
connexionOK();
If so, you will need to refactor and make sure you setcookie before headers are sent.
EDIT: The above code was included to more clearly illustrate the problem - it is poorly written and includes a lot of redundancy as calling set setCookie while headers are sent will already throw an exception and probably terminate execution. If this is NOT the case, you will need to add checks and handle them accordingly.

Try
if(isset($_COOKIE['CookieCo'])){
echo '<script type="text/javascript">';
echo "alert('Cookie envoyé');";
echo "</script>";
}
else {
echo '<script type="text/javascript">';
echo "alert('Cookie failed');";
echo "</script>";
}

Related

PHP error- Header sleep function not working

I have a PHP code that has header and sleep Functions to display an alert as it redirects the page a bit slower. But the sleep does not seem to be working.
This is the PHP code, Please check:
<?php
if ($query) {
echo '<script language="javascript">';
echo 'alert("Registration SUCCESFUL")';
echo '</script>';
header('sleep(10);');
header('Location: http://localhost/amberTAG%20requester/Login%20Page/Login.html');
} else {
echo '<script language="javascript">';
echo 'alert("Registration UNSUCCESFUL, Sorry!")';
echo '</script>';
header('sleep(10);');
}
?>
Thanks,
Just use sleep without header
sleep(10);
header('Location: http://localhost/amberTAG%20requester/Login%20Page/Login.html');
Or use:
header('refresh:10; URL=http://localhost/amberTAG%20requester/Login%20Page/Login.html');
If you want to use sleep before alert, you should use setTimeout for JavaScript.
Try this:
setTimeout(function(){
alert("Registration UNSUCCESFUL, Sorry!");
}, 10000);
And, if you want to use sleep before URL redirection, try this:
header( "refresh:10;url=yoururl.html" );

run a if step by step PHP

i have a problem in PHP, i want first show a message like this:
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
and when i clicked on ok, then redirect to another page, my code is like this:
$fgmembersite->RedirectToURL("home2.php");
complete code:
if(isset($_POST['submitted']))
{
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
$fgmembersite->RedirectToURL("home2.php");
}
but this code do not show me the message just redirect to home2.php, if there is another way except of 'if' please explain. the simplest way
thanks
If you just want to redirect to another page.. you can do this:
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
echo '<script>window.location.href = "the-target-page.php";</script>';
you should use javascript o redirect only. You are trying to mix, both php and javascript
echo "<script>javascript:alert('message successfully sent'); window.location = 'home2.php'</script>";

: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\rail\index.php:446) in [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
PHP Header issue with ob_start() and ob_end_flush()
(5 answers)
Closed 7 years ago.
this is warning. even it is NOT allowing me to open the page admin.php and error is ":
Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\rail\index.php:446) in
<?php
ob_start();
error_reporting(E_ALL);
here is warning in this line . where i have started the session
session_start();
include("db.php");
if(isset($_POST['log']))
{
$user= $_POST['username'];
$pass= md5($_POST['password']);
$sql=mysql_query( "select * from reg where username= '$user' AND password='$pass' ") or die( mysql_error());
$data=mysql_num_rows($sql);
if ($data == 1) {
while($row = mysql_fetch_array($sql)){
$_SESSION['username']=$s1;
echo '<script>window.location="admin.php"</script>';
}
}
else {
echo '<script type="text/javascript">';
echo 'alert("Password Invalid!")';
echo '</script>';
}
}
ob_end_flush();
?>
enter image description here
In a nut shell. There are many things which could cause this error/warning. Most of which are narrowed down to a piece of output being sent to the browser before starting a session. So with that in mind, check for output in your script.. this can be anything from a simple white space or text before initialising the session.
another common scenario for this warning to be presented is triggered by your files encoding. There can be something called UTF8-BOM which is a hidden character (s) which some editors might not pick up, providing you have set the wrong encoding for yor file. So in that case, the solution would be to double check the files encoding.
The error message is clear, it states index.PHP and around line 446 is roughly the cause for this warning. So check for things I've mentioned above on or before that line
Try to use this may help you ,
<?php
session_start();
ob_start();
error_reporting(E_ALL);
include("db.php");
include("redirect.php"); // the file which is stored redirect()
if(isset($_POST['log']))
{
$user= $_POST['username'];
$pass= md5($_POST['password']);
$sql=mysql_query( "select * from reg where username= '$user' AND password='$pass' ") or die( mysql_error());
$data=mysql_num_rows($sql);
if ($data == 1) {
while($row = mysql_fetch_array($sql)){
$_SESSION['username']=$s1;
redirect('admin.php'); // HERE YOU NEED TO REPLACE THE FUNCTION
}
}
else {
echo '<script type="text/javascript">';
echo 'alert("Password Invalid!")';
echo '</script>';
}
}
ob_end_flush();
?>
Avoid the ?> if there is not any html tags in your code
EDIT :
If the above did not helped you then try use the below function instead of header()
function redirect($url) {
if (!headers_sent()) {
header('Location: '.$url);
exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
}
}
Thanks to Rajat Singhal for the redirect()

Why does my code shows headers already sent even if it is in if else condition? [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I have a very simple code which checks whether email address exists in the table or not. If it exists then alert Already Exists and redirect to another page and if it doesn't exist then insert into table. Inserting when the email address is not present in the table is happening properly and is getting redirected to the respected page but when the email is existing in the table then although it alerts that username exists, it shows headers already sent at error
My code is
<?php
require_once('connection.php');
$tbl_name="cust_contacts";
$ccode=$_POST['ccode'];
$name=$_POST['name'];
$des=$_POST['desig'];
$dep=$_POST['dep'];
$phone=$_POST['phone'];
$mobile=$_POST['mob'];
$email=$_POST['email'];
$check="select * from $tbl_name where email='$email'";
$checkqry=mysql_query($check);
if($checkqry['error'])
die(mysql_error());
$countcheck=mysql_num_rows($checkqry);
if($countcheck==0)
{
$qry="insert into $tbl_name(cust_code,name,designation,department,phone,mobile,email) values('$ccode','$name','$des','$dep','$phone','$mobile','$email')";
if (!mysql_query($qry))
{
die('Error: ' . mysql_error());
}
header("location:index.php?customername=$ccode#pop4");
}
else
{
echo '<script type="text/javascript">alert("User already exists. Try editing the user");</script>';
header("location:index.php?customername=$ccode");
}
//$count=mysql_num_row($result);
//if($count==1)
?>
If you want to show an alert message and redirect to another page, you can use JavaScript like this:
Befor (Your Original Code):
echo '<script type="text/javascript">alert("User already exists. Try editing the user");</script>';
header("location:index.php?customername=$ccode");
After:
echo '<script type="text/javascript">';
echo 'alert("User already exists. Try editing the user");';
echo 'location.href = "index.php?customername=' . $ccode. '";';
echo '</script>';
Hope this helps.
I had the same problem, and as far as i can see if the header() is use after some code then it throws an error, so maybe try removing the echo statement.
If that doesn't work, i used a function call. this the function:
function redirect($url) {
if (!headers_sent()) {
header('Location: '.$url);
exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
}
}
And this is an example of the call:
if($mail->send()) {
// redirect to thank you message.
redirect( BASE_URL . "thanks/");
exit;
} else {
$error_message = "There was a problem sending the email: " . $mail->ErrorInfo;
}
Here i used it to redirect if an email was successful sent using PDO class, but it can used anywhere.

PHP header pass parameters in url

I have an index.php for registration, a login.php as the registration handler. when the registration is failed, it sent out the error message to client. I use this code for sending out the message
header('Location: http://localhost/musicshare/index.php?reg=false');
and receive in index.php
if(isset($_POST['reg'])){
echo 'set';//for checking whether reg is set
if($_POST['reg']=='false'){
echo '<script type="text/javascript">';
echo 'alert("Reg faile")';
echo '</script>';
}
}
However, It seems not working at all; Please help, thanks.
Use $_GET instead of $_POST:
if (isset($_GET['reg']) && $_GET['reg'] == 'false'){
// do something
}
When you use a header() it fires a GET request.
So you should use $_GET['reg']
if(isset($_GET['reg'])){
echo 'set';//for checking whether reg is set
if($_GET['reg']=='false'){
echo '<script type="text/javascript">';
echo 'alert("Reg faile")';
echo '</script>';
}
}

Categories