php session is not working in server - php

I want after register the page should continue with session. for that i have create following code.
if($_POST['action']=='finder_quick_reg')
{
extract($_POST);
print_r($_POST);
$result=$dbg->exec("INSERT INTO `login_register`(`email`, `password`, `reg_date`, `complite_register`, `type`) VALUES ('$client_mail','$client_password', now(),'0','c_finder')") or die("Insert Failed ".mysql_error());
$lastId = $dbg->lastInsertId();
$results=$dbg->exec("INSERT INTO `care_finder`(`postal_code`,`user_pic`, `login_id`,`f_name`, `l_name`, `gender` ) VALUES ('$postal_code', 'default.jpg','$lastId', '$f_name', '$l_name', '$gender')")or die("Insert Failed ".mysql_error());
}
else{echo 'error';}
if($results){
include_once 'connection.php';
$con=new connection();
$dbg=$con->db;
$sql="SELECT * FROM `login_register` WHERE `login_id`='$lastId'";
$stmt=$dbg->query($sql);
$rows=$stmt->fetch(PDO::FETCH_ASSOC);
session_start();
//echo $lastId;
$_SESSION['Uname']=$rows['email'];
$_SESSION['pword']=$rows['password'];
$_SESSION['Utype']=$rows['type'];
$_SESSION['Uid']=$rows['login_id'];
}
after this db.php page it will go to user_index.php
following code is using in user_index.php
<?php
session_start();
if (!isset($_SESSION['Uname'])) {
//header("location:index.php");
echo 'no sesseion';
}
else {
......
......
}
can some one help me

You're outputting before starting the session
if($_POST['action']=='finder_quick_reg')
{
// ...
print_r($_POST);
// ...
}
else { echo 'error'; }
And from the title I'd assume that error_reporting is turned off on the production server, otherwise you'd have seen an error message along the lines of
Warning: Cannot modify header information - headers already sent...
You should start the session exactly like in you're doing in your other file - at the very beginning of it, before all other statements.
On a side note, have a look at the point notes in the documentation for export() function, there it's written why/that it's a bad idea to use it on untrusted data.

session_start();
should come from login page on.

Related

Clarification on session_start() when using AJAX

I recently got the following error in my logs:
session_start(): Cannot send session cache limiter - headers already sent
I am new to using sessions so I am not surprised. I use the following code in my header.php file:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
?>
I mostly use AJAX to interact with some files that handle database-related functions. Do I need to add the session_start() on my backend php files too? I am currently doing this:
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
include_once 'database.php';
session_start();
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
$uid = $_SESSION['usr_id'];
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `contributions`(`uid`, `contributionname`, `contributiontype`, `contributionamount`, `employee`)
values ('".$uid."', '".$inputvalues['contributionname']."', '".$inputvalues['contributiontype']."', '".$inputvalues['contributionamount']."', '".$inputvalues['employee']."');
");
// select your query
$addresult = "Success";
$returnResult = $addresult;
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
Is this what is causing my error?

Posts Aren't Showing in PHP

I've been stuck on this for two days now. I have set up my own blog and the posts are stored in a database. This page is for grabbing an old post based on it's ID. When I try to retrieve them, everything shows but the actual body.
This is the index in /posts/
<?php
include_once('grabPost.php');
$TEMPLATE_TITLE = "$POST_TITLE";
include_once("../inc/template.html");
?>
Then, this is the grabPost.php.
<?php
error_reporting(-1);
$ID = $_GET['id'];
include_once('connectionMod.php');
$DBConnection = new MySQLi($DB_HOST, $DB_USER, $DB_PASS, $DB_DTBS);
function ReturnError($error){
global $POST_TITLE;
global $POST_BODY;
global $TEMPLATE_CONTENT;
$POST_TITLE="Oops!";
$POST_BODY="<p>It looks like we had an error grabbing your post. The post may have been moved, deleted, or you may have an invalid link. If you <strong>know</strong> this shouldn't be happening, please contact a developer.<br><em>$error</em></p>";
$TEMPLATE_CONTENT = "<h1>$POST_TITLE</h1>\n<hr size='2'>\n$POST_BODY";
}
if($ID == null){
ReturnError("No post ID was provided.");
}
if($stmt = $DBConnection->prepare("SELECT `Title`, `Poster`, `Date`, `Body` FROM `posts` WHERE `ID`=?")){
if(!($stmt->bind_param('i', $ID))){
ReturnError($stmt->error);
}
else if(!($stmt->execute())){
ReturnError($stmt->error);
}
else if(!($stmt->bind_result($POST_TITLE, $POST_NAME, $POST_DATE, $POST_BODY))){
ReturnError($stmt->error);
}
else if(!($stmt->fetch())){
ReturnError($stmt->error);
}
else{
$TEMPLATE_CONTENT = "<h1>$POST_TITLE</h1>\n<small>Posted on $POST_DATE by $POST_NAME</small>\n<hr size='2'>\n$POST_BODY";
}
}
else{
ReturnError($DBConnection->error);
}
?>
Oddly though, you can see the most recent post without issue on the homepage. Any suggestions with what's wrong?
Also, ReturnError() never shows the error. What can I do about it?
Function
function return_error($error){
$post_error = "<h1>Oops!</h1>\n<hr size='2'><br />"
."<p>It looks like we had an error grabbing your post."
."The post may have been moved, deleted, or you may have an invalid link."
."If you <strong>know</strong> this shouldn't be happening, "
."please contact a developer.<br><em>".$error."</em></p>";
return $post_error;
}
Usage:
/* check connection */
if ($DBConnection->connect_errno) {
$error = return_error("Connect failed: %s\n", $DBConnection->connect_error);
echo $error;
die();
}
/* check prepare() */
$stmt = $DBConnection->prepare("SELECT ....FROM `posts` WHERE `ID`=?");
if(!$stmt){
$error = return_error("prepare failed()".$stmt->error);
echo $error;
die();
}
and so forth ... By the way if connection fail or any other fatal error occurs, then die() or exit() is the right thing to do..
Well, I found the fix. I needed to run $stmt->store_result() before $stmt->bind_result() since since the body was a LONGTEXT, I guess this is some issue with MySQL and PHP.

PHP form generates "Object not found" but still submits form data

I've got a simple php form for client info that when submitted, generates an object not found 404 error. The information I submitted is still being sent to the db successfully so I'm not sure why I'm seeing this error. Thanks in advance for the help.
<?php
$link=mysql_connect("localhost","root","");
$database='clientinformation';
if (!$link)
die('Failed to connect to Server'.mysql_error());
$db=mysql_select_db($database, $link);
session_start();
if(!$db)
die('Failed to select Data Base '.mysql_error());
if(isset($_GET['process']))
{
$query = "Insert INTO `client_reg` (ClientName, Address, CNICNumber, MobileNumber, TelephoneNumber, CompanyName, ClientStatus, RegisterDate) values('$_POST[ClientName]', '$_POST[Address]','$_POST[CNICno]','$_POST[Mobileno]', '$_POST[Telephoneno]', '$_POST[Companyname]', '$_POST[Clientstatus]', '$_POST[RegisteredDate]')";
//echo $query; exit;
$result = mysql_query($query) or die(mysql_error());
if(!$result)
{
$msg = "not Inserted";
}
else
{
$msg = "Inserted";
header("location:ClientList.php?m=".$msg);
}
}
?>
Does Clientlist.php exist on your server? Remember that UNIX servers are case sensitive. If it's clientlist.php on the drive, you'll get a 404
404 error - "404 Not Found" web page when a user attempts to follow a broken or dead link;
`ClientList.php` the file not found or mismatching in filename
You should follow this convention :
$_POST["name"])
Store value after submit form:
$clientName=$_POST['ClientName'];
$Address=$_POST['Address'];
$Mobileno=$_POST['Mobileno'];
$Telephoneno=$_POST['Telephoneno'];
$Companyname=$_POST['Companyname'];
$Clientstatus=$_POST['Clientstatus'];
$RegisteredDate=$_POST['RegisteredDate'];
Now use this value in your query,hope it will work.

Header, logic and database

I am having an issue with my header location. I am new to php and I am unable to redirect to my index page after this separate php file is run. In addition my function is unable to tell whether the contents of a text box is blank or equal to the default value of "<>".
Thank you
<?php
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
{
// the form was submitted
//remove hacker HTML
$email2=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email2'";
$result=mysql_query($sql2);
//Direct back to homepage
echo "heloooo";
header('location:/index.php');
}
else
{
header('location:/index.php');
}
}
else
{
header('Location:http://www.google.com');
`enter code here`}
?>
EDIT
After making the changes suggested my error log is as follows
Notice: Use of undefined constant db_selected - assumed 'db_selected' in /home/clubbtpk/public_html/connectionFile.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /home/clubbtpk/public_html/connectionFile.php:15) in /home/clubbtpk/public_html/addEmail.php on line 28
The code in the connection file is:
<?php
$host="localhost";
$username="username";
$password ="password";
// Create connection to mysql server
$con=mysql_connect("$host","$username","$password");
// Check connection
if (!$con)
{
die ("Failed to connect to MySQL: " . mysql_error());
}
// Select database
$db_selected = mysql_select_db("DB", $con);
if(!db_selected)
{
die ("Cannot connect : " . mysql_error());
}
?>
EDIT 2
Resolved first error by changing
if(!db_selected)
to
if(!$db_selected)
RESOLVED
Added the following line of code to my index.php file:
<?php
if(isset($_REQUEST["emailAdd"])){
include("addEmail.php");
}
?>
Then changed the action of the form to "" so that it reloads the current page:
<form name="emailAddr" method="post" action="">
You must not output anything before your redirect.
So this is not allowed:
echo "heloooo";
header('location:/index.php');
EDIT: You should definitely enable error_reporting on your script. I found another error in your query:
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
should be
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
Furthermore you should not use the mysql_* functions anymore but upgrade to mysqli_* functions. And always check the inputted data before inserting them into sql-queries.
EDIT2: Add this at the beginning of your script:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
EDIT3:
You have to change this line too:
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
Should be:
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>")
If you would turn error_reporting on you would see it yourself.

Form to insert data in database works, but does not show success-page

I've a simple order-form on my website. If I click the submit-button the the form will send the data to my database. This works. But it does not show the success.php - it only shows the start.php again. So there must be a mistake. On my previous hoster it worked. But now I have a new one.
Here's my php-script (start.php):
<?php
$con = mysql_connect("localhost", "user", "pw") or die ("No connection to db possible");
mysql_select_db("db", $con) or die ("No connection to db possible");
mysql_query("SET NAMES 'utf8'");
if (isset($_POST['button']))
{
foreach ($_POST AS $key => $postvar)
$_POST[$key] = stripslashes($postvar);
$_POST['name'] = mysql_real_escape_string($_POST['name']);
$_POST['strasse'] = mysql_real_escape_string($_POST['strasse']);
$_POST['plz'] = mysql_real_escape_string($_POST['plz']);
$_POST['ort'] = mysql_real_escape_string($_POST['ort']);
$_POST['mail'] = mysql_real_escape_string($_POST['mail']);
$_POST['anzahl'] = mysql_real_escape_string($_POST['anzahl']);
$sql = "INSERT INTO `bestellungen` (`name`,`strasse`,`plz`,`ort`,`mail`,`anzahl`,`datetime`)
VALUES ('".$_POST['name']."', '".$_POST['strasse']."', '".$_POST['plz']."', '".$_POST['ort']."', '".$_POST['mail']."', '".$_POST['anzahl']."', '".date("Y-m-d H:i:s")."');";
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
?>
<?php Header("Location: success.php");
exit();
?>
<?php
} else { ?>
That won't work because header('Location: success.php') needs to happen before you output anything to the browser. You seem to have gaps before that is called.
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
// Now its time for the header!
header("Location: success.php");
exit();
You cannot have any output before the header() redirection.
Check your script for possible errors, warnings or notices, any of these will output text and the redirection will no happen.
So far, whenever I found this kind of problem; there must be two reasons I often do. Either I print any html code before the header function or I don't realize that my success.php also redirect to start.php.
Maybe you can check either of these two exist in your code.
Format it this way.
$result = mysql_query($sql,$con);
if (!$result) {
echo mysql_error();
} else {
Header("Location: success.php");
}
mysql_close($con);
?>

Categories