PHP Classes

Session variable problem!

Recommend this page to a friend!

      Top level forums  >  PHP Specialists  >  General  >  Session variable problem!  
Subject:Session variable problem!
Summary:Session variable not remembered after submitting form
Messages:8
Author:David
Date:2025-04-01 04:06:27
Update:2025-04-01 17:58:22
 

 


  1. Session variable problem!   Reply   Report abuse  
Picture of David David - 2025-04-01 17:58:22
Hi,

I am using a script to allow users to upload their profiles and renaming them while keeping the extensions - docx, pdf, jpg, etc.

Each user has a unique user number. The renamed files would look like this: profile_usernum.extension, e.g profile_351.pdf

The user number is retrieved from a database. The script works, except that the user number (UserNum) is not carried after submitting the form. So, I end up with "profile_.pdf" instead of "profile_351.pdf".

Please note that session_start() is stated at the top of each script. The files are mentioned below. I've been trying to solve this for 4 days now with no avail.

Please help.

There are 3 files:

main.php
<?php
session_start();
// code to retrieve UserNum from database
$_SESSION ['UserNum'] = $UserNum;
$UserNum = $_SESSION ['UserNum'];
include "upload.php";
?>

upload.html

<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="submit">
</form>

</body>
</html>


upload.php
<?php
session_start();
$UserNum = $_SESSION ['UserNum'];

// to check that $UserNum is there:
echo $UserNum; // correctly displayed only before submitting the form

include "upload.html";

$submit=$_POST["submit"];
$target_dir = "profiles/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$extension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// changing the name of uploaded file
$myfile = $target_dir . "profile_" . $UserNum . "." . $extension;

if (isset($submit))
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $myfile)) {
echo "The file has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

There are 7 replies in this thread, which are not being displayed.
Browsing this forum thread replies is available only to premium subscribers.


Go to the premium subscriptions page to learn how to become a premium subscriber and have full access to this forum.