PHP session ends when submit button is clicked - php

I want to make profile upload image for users so they can upload their own avatars on their profile...So the issue here is whenever i click the upload button session gets destroyed.
Here is the form:
if(isset($_SESSION['profileimgID'])){
echo "<form action='upload.php' method='POST' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit' name='uploadimgsubmt' class='button1'>upload</button></form>";
}
?>
partial code of upload.php file:
<?php
session_start();
include_once 'includes/dbh.inc.php';
$id = $_SESSION['profileimgID'];
if(isset($_POST['uploadimgsubmt'])){
**code code code**
if($fileError === 0){
if($filesize < 1000000){
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($filetmpname, $fileDestination);
$sql = "UPDATE profileimg SET STATUS=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?upload=success");
}
}
**code code code**
Code if user is successfully logged in, inside loginCheck.php:
session_start();
$_SESSION['userID'] = $row['idusers'];
$_SESSION['username'] = $row['uidusers'];
$cmpor = $row['idusers'];
$sql = "SELECT * FROM profileimg WHERE id";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
if($row['id'] == $cmpor){
$_SESSION['profileimgID'] = $row['id'];
}
}
header("Location: ../index.php?login=success");
exit();
}
And the last code section that is related to the problem is located to index.php:
<?php
session_start();
include_once 'includes/dbh.inc.php';
?>
**code code**
<?php
if(isset($_SESSION['profileimgID'])){
echo 'Show this content';
}else{
echo 'Show this content';
}
?>
**code code**
If i remove the 'profileimgID' to nothing ('') everything works fine but isset method doesnt hide-show the content.
If i keep it as it's isset method works fine but upload button destroys the session and user is logged out.
print_r($_SESSION) results in both index.php and upload.php if user is successfully logged in:
for user #2
Array ( [userID] => 2 [username] => popa [profileimgID] => 2 )
I checked the console for requests , when i click the upload button i get this message:
Form contains a file input,
but is missing method=POST and
enctype=multipart/form-data on the form.
The file will not be sent.
This part (isset($_SESSION['profileimgID'])) is interfering somehow with this process. When i remove it, session is maintained and it works fine upload works too.
UPDATE:
this is what i get when i click the upload-button:
https://i.stack.imgur.com/So7OD.png
this is i guess the right one ?:
https://i.stack.imgur.com/HcBqz.png
Im new to php so... sorry for my mistakes.

Exactly how are you maintaining the session-identifier now? "Sessions" rely upon a "session-id" being somehow sent from the client to the host with each exchange: normally, this is done using a cookie, but it could be done using a GET parameter (e.g. &sessionid=XXXX) It sounds to me like this information isn't being sent: the session hasn't been "destroyed," actually, but you can't find it.
Probably the fastest way to solve this is to use the network debugging features of your browser: look at the complete packet of data that's being sent, including the HTML headers (which is where cookies will be). First, look at "normal" exchanges. Then, look at the one that happens when you click that button. "Cookies" will be sent every time since they live in the header. But, if you're actually using a GET parameter to send the session-info, you'll have to do it.

Found the problem it seems like i didnt close the form on the index isset condition where logout form was located, my bad because i didnt show u guys the code :D so the problem was </form> ... pff sorry
Lesson of the day , guys always close ur </...> :)

Related

i am try to create session but always session empty

I want to try to make a session but always session Empty.Use this code rate this product this link send an email open email and click link Active than code working session empty please help me...
<?php
session_start();
include("myhomeportal/setting/config.php");
$conform = $_GET['conform'];
$query = mysqli_query($conn, "SELECT * FROM item_users where com_code='$conform'");
$row = mysqli_fetch_array($query);
if ($row) {
// now update `com_code`
$sql = "UPDATE item_users SET com_code='active', user_type='user' WHERE com_code='$conform'";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
$inventory_id = $row['inventory_id'];
$active = $row['com_code'];
$_SESSION['sess_active'] = $active;
header("Location: category.php?inventory_id=$inventory_id");
} else {
// confirm code not found, show error
}
?>
Try to debug first.
Echo this $row['com_code']; then $_SESSION['sess_active'].
If they print something then go ahead.
There ir an error in your test page.
"sir other page is not working session just simple test code – Pankaj"
Instead you are only testing, you must start the session always with session_start() in every .php you want to use session.
Solving testing page.
"<h1>welcome <?php session_start(); echo $_SESSION['sess_active'];?> </h1> – Panka"
Note from w3schools:
The session_start() function must be the very first thing in your document. Before any HTML tags.
you are writting some html code before start the session, you should do that way:
<? php session_start(); ?>
<h1>welcome <?= $_SESSION['sess_active']; ?> </h1>
You can read more about this https://www.w3schools.com/php/php_sessions.asp

My php header tag will not redirect

I've tried doing my research and it doesn't look like I'm coming up successful. I made sure there is no content being printed out to the screen before my header tags.
This page is taking information given from the form in the previous login page and using that information to determine which page the user should be redirected to. Unfortunately, it doesn't look like any of my header tags are redirecting to anything, it just stays on this php page.
To debug, I have echo'd each scenario (logged in, out, wrong pw) and each scenario works, but obviously when I echo'd the redirect wouldn't work. I just wanted to test that the information was being transmitted correctly.
Can anyone else help and give me an outsider's perspective?
<?php
session_start();
include('dbconnect.php');
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$query = "SELECT password FROM artists WHERE email='$email'";
$passwordMatch = mysqli_query($db, $query);
$row = mysqli_fetch_array($passwordMatch);
if($row[0] == $password){
$query = "SELECT active FROM artists WHERE email = '$email'";
$active = mysqli_query($db, $query);
$active = mysqli_fetch_array($active);
$active = $active[0];
if ( $active == 0 ){
header('Location: validate.php');
}
else{
header('Location: artistHome.php'); //redirect to user home page and update session
$_SESSION['user']= $email;
unset($_SESSION['error']);
}
}
else{
header("Location: login.php");
$_SESSION['error']= 'Invalid Password';
}
?>
There were about thousands of posts like this one over here.Get rid of php closing tag ?> and whitespaces, html, blank lines before php opening tag <?php. Also check if there is no output before :
header("Location:");
Like print,var_dump, echo and so on.
Also check your if condition, maybe you are just skipping it.
If you include,include_once,require_once or require check all the things above in the included files too.
To narrow a circle of the things to correct look into your php error_log and provide us with error description.
header("Location: login.php"); will always fail if anything is returned to the browser before it. That includes whitespace, or even errors PHP are returning. Make sure nothing is being returned before the header function is used.

converting an script from PHP mysql_insert_id header, location method to PHP session method

I have successfully implemented data transfer attempt from one page to another using PHP mysql_insert_id header, location method. What I did was:
I have validated it (transferring (i.e. form action) the form to the same page), I have saved it in database, and now I m trying to display the data on another page.
page1 (where original form is located)
$id = mysql_insert_id();
header('Location: page2.php?id='.$id);
and in page2
$id = $_GET['id'];
$query = "SELECT * FROM form1 WHERE id=$id";
{
// there after display of data
}
The problem I faced:
I m getting this link in the title bar
http://localhost/aaa/page2.php?id=76
now if I try to change id= 56 or 45 or any other it is changing displayed data to that id.. so any user can change it in address bar and hence will be able to see my db values..
I thought of encoding it in first place, then at second place I thought of changing it to sessions instead.
so I searched a lot on google to set it as session and I tried this
<?php
// Starting the session
session_start();
if(isset($_SESSION['id'])) //and is this use of id correct?
{ // then what?
}
thanks guys for your help
You have to explain what you are exactly trying to do ? so that we can give suggestion . Though below code will work fine. But i think no use of it.Use session_start before using the session.
Page 1:
$id = mysql_insert_id();
$_SESSION['last_id'] = $id;
header('Location: page2.php');
Page 2:
$id = $_SESSION['last_id'];
$query = "SELECT * FROM form1 WHERE id=$id";
{
// there after display of data
}
page1.php:
<form action="post" action="page2.php">
<input name="name" type="hidden" value="<?=mysql_insert_id();?>"></input>
</form>
page2.php:
<?php
$id = $_POST['name'];
$query = "SELECT * FROM form1 WHERE id=$id";
?>

How to login on php

I am trying to create logins for users. I have an sql that inserts the information in a mysql database, but after that i don't know how to actually start the login. As of now, I insert the information on join_action.php which then redirects to /index.php (below). Does session_start() on /index.php actually start the login? Becuase if so, it's not working.
PHP (join_action.php):
$sql=mysql_query("INSERT INTO users VALUES ('','$name','$password','$email','$date','$time','$random','0','1','0')");
$id=mysql_insert_id();
$_SESSION['id'] = $id;
header("Location: http://localhost/index.php");
HTML (index.php top):
<?php session_start(); ?>
login.php (untested, but should give you the right idea)
<?
#session_start();
if(isset($_POST['login'])){
$name = addslashes({$_POST['login']});
$password = addslashes({$_POST['password']});
$res=mysql_query("SELECT * FROM users WHERE name = '{$name}' AND password = '{$password}'");
if(mysql_num_rows($res)>0) {
$_SESSION['loggedin'] = 1;
$_SESSION['user'] = mysql_fetch_assoc($res);
} else {
$_SESSION['loggedin'] = 0;
$_SESSION['user'] = null;
}
}
if($_SESSION['loggedin']==1) {
?>
Logged in!
<pre><? print_r($_SESSION['user]); ?></pre>
<? } else { ?>
Not logged in...<br>
<form method='post' action='login.php'>
<div>Login: <input type='text' name='login'></div>
<div>Password: <input type='password' name='password'></div>
<input type='submit' value='Log In'>
</form>
<? } ?>
Download any number of open source projects and see how they handle logins.
No, session_start() doesn't directly handle the login, it's just starting a new session which MIGHT be used by the login script.
session_start will initialize the PHP session for the page, but you don't appear to have any code to actually manipulate them like setting them or checking their validity or anything else, so it'll basically do nothing. It doesn't magically know what you want to DO with your session. All you've got is one line to set an ID.
You'll need to code a little extra in order to start using session_start(). To begin, session_start() simply begins a PHP session where the server begins tracking that particular user. In your methodology, you'll need to link that session to user data in your code.
When I was learning PHP users, this handy script really helped me understand the methodology: http://www.majordojo.com/php-users/
Although it's in PHP4, it's very similar code. :)

Creating an isset if function using php to avoid and update if the input is empty for a MYSQL update

Hi I am newish to php and I have created an update page for Content Management System. I have a file upload in this case a picture. I have other inputs that contain text and I can get them to populate my form and thats fine and works great because the user can see what has already been entered. But the file name for the photo can not have a value so if the user doesn't pick the picture from the directory again it will update minus the picture. What I think I need is a isset function that says if the file (picture) input is left blank don't update this field and use whatever what already in the database for it, that way if it was left blank when created it will still be, and if the user has changed it this time it will change; or if they want to leave it the same it won't leave their picture blank. Hope that makes sence.
Here is my coding currently for the Form:
<p>
Photo:
</p>
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input type="file" name="photo"/>
Below is my php code for my update if the update button is pressed:
$con = mysql_connect("localhost","******","********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
// run this only, once the user has hit the "Update" button
if (isset($_POST['update'])) {
// assign form inputs
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$pic = $_POST['photo'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];
// add member to database
$result = mysql_query("UPDATE dbProfile SET nameMember='".$name."',bandMember='".$position."',photo='".$pic."',aboutMember='".$about."',otherBands='".$bands."' WHERE id='".$id."'");
mysql_close($con);
Header("Location: listMember.php");
exit;
}
else { // read member data from database
$result = mysql_query ("SELECT * FROM dbProfile WHERE id='".$id."'");
while($row = mysql_fetch_array($result))
{
$name = $row['nameMember'];
$position = $row['bandMember'];
$pic = $row['photo'];
$about = $row['aboutMember'];
$bands = $row['otherBands'];
}
}
mysql_close($con);
?>
If you could help I would be very please and greatful.
You have to use the $_FILES variable for uploaded files. For further information, see Handling file uploads in the PHP manual.
Try:
if(is_uploaded_file($_FILES['photo']['tmp_name']))
From the manual:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

Categories