0

I have searched through numerous posts on this site to figure out why my session variable is not being recognized, but I haven't been able to figure out a solution.

It is really simply what I am trying to do. I have two PHP files. The first one I have the following code. I HAVE started a session.

PHP file 1

$profile_viewer = $_GET['user'];
$_SESSION['viewer'] = $profile_viewer;

PHP file 2

$_SESSION['viewer'] = $profile_viewer;

I keep getting the error : Notice: Undefined variable: profile_viewer

What am I doing wrong with putting $profile_viewer in the session and then calling for it?

EDIT:

File 1

 $profile_user = $_GET['user'];
    $_SESSION['viewer'] = $profile_user;

File 2

    $user = new User();
    //$profile_user = $_GET['user'];
    $profile_user = $_SESSION['viewer'];
    echo $profile_user;
    $friend_status = $_POST['friend_status'];
    $okay = true;

    if ( $okay ) {
        $add_friend_sql = "
            INSERT INTO friends 
            (friend_one, friend_two, date)
            VALUES(?, ?, NOW())
        ";
        $add_friend_stmt = $con->prepare($add_friend_sql);
        $add_friend_stmt->execute(array($user_id, $profile_user));
    }

Full code for file 1

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once '../core/init_account.php';

if(Session::exists('home')) {
    echo '<p>' . Session::flash('home') . '</p>';
}
if(!$user->isLoggedIn()) {
    Redirect::to('../index');
}
$profile_user = $_GET['user'];
$_SESSION['viewer'] = $profile_user;

// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
    function UploadFile($fileArray = array(), $destinationFolder = 'profile_images/') {
        $filename       =   $fileArray['file']['name'];
        $tmp_name       =   $fileArray['file']['tmp_name'];
        $filesize       =   $fileArray['file']['size'];
        $file_error     =   $fileArray['file']['error'];
        $file           =   $fileArray['file'];
        // Save all the default data.
        // Success and error should be set by default to fail
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        // I added a directory creation function so you don't have to 
        // manually make folders. This will do it for you.
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  =   (move_uploaded_file($tmp_name, $destinationFolder.$filename));  

        return $return; 
    }

// Create a save-to-database function so it's easier and reusable
    function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
        $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
        $img_insert_sql = "
            INSERT INTO profile_img
            (user_id, img)
            VALUES (?, ?)
        ";
        if($img_insert_stmt = $con->prepare($img_insert_sql)) {
            $img_insert_stmt->execute(array($user_id, $filename));
            return true;
        }
        return false;
    }

// Get current profile img
    function getPhoto($con) {
        $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
        $profile_viewer = $_GET['user'];
        if ($profile_viewer == $user_id) {
            /*$img_select_sql = "
                SELECT *
                FROM profile_img
                WHERE user_id = ?
                ORDER BY id DESC
                LIMIT 1
            ";*/
            $img_select_sql = "
                SELECT i.*
                FROM profile_img i
                WHERE user_id IN (?, ?)
                ORDER BY id DESC
                LIMIT 1;
            ";
        }
        else {
            //echo "This is not your image";
            echo $profile_viewer;
            $img_select_sql = "
                SELECT i.*
                FROM profile_img i
                WHERE user_id IN (?, ?)
                ORDER BY id DESC
                LIMIT 1;
            ";
        }
        if ($select_img_stmt = $con->prepare($img_select_sql)) {
            $select_img_stmt->execute(array($user_id, $profile_user));
            $rows = $select_img_stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                //$status = $row['status'];
                return $row;
            }
        }
    }

// Make sure all functions above are include here. Checks for post
    if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
        }   
        else {
            // You could add error handling here based on the results of 
            // each function's success or failure below.

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
            }
    }
    $profPic = getPhoto($con);
?>  
</head>
<body>
<?php
include_once("../analyticstracking.php");

if($user->hasPermission('User')) {
    include 'nav/navUser.php';
}
?>
    <div id="main">
<?php
    $profile_viewer_message = null;
    if($profile_user == $user_id) {
        echo $profile_viewer_message = "This is your profile.";
    } else {
        echo $profile_viewer_message = "You are viewing someone elses profile.";
        echo '<div id="add-friend"><img src="../icons/collection/add.png" alt="Add Friend">' . "Add Friend" . '</div>';
    }
?>  
        <div id="profile-pic-container">
            <img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
            <img src="../icons/photo-camera.png" id="change-picture" alt="Profile Picture">
            <form action="" method="POST" enctype="multipart/form-data">
                <input type="file" id="upload-profile-pic" name="file" class="file-input">
                <div id="profile-pic-change"><a href="" id="upload-link">Change profile pic</a></div>
        </div>
                <!-- <img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
                <input type="submit" class="none" name="create" value="Upload Profile Picture">
            </form> -->
            <div id="new-profile-pic-preview">
                <div id="pic-preview-container"><img class="none pic-preview total-center" id="file" src="#" alt="your image"></div>
                <input type="submit" class="none" name="create" value="Upload Profile Picture">
            </form>
            <a class="popup-close" data-popup-close="popup-1" href="#">Close</a>
            </div>
        <!-- <form action="" method="POST" enctype="multipart/form-data">
            <input type="file" id="upload-profile-pic" name="file" class="file-input">
            <img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
            <input type="submit" class="none" name="create" value="Upload Profile Picture">
        </form> -->
        <form action="profile.php" method="POST">
            <div class="field">
                <label for="streetline1">First Name</label>
                <input type="text"  class="inputbar" name="streetline1" value="<?php echo escape($user->data()->firstname); ?>">
            </div>
            <div class="field">
                <label for="streetline2">Last Name</label>
                <input type="text"  class="inputbar" name="streetline2" value="<?php echo escape($user->data()->lastname); ?>">
            </div>
            <div class="field">
                <label for="city">Email</label>
                <input type="text" class="inputbar" name="city" value="<?php echo escape($user->data()->email); ?>">
            </div>
            <div class="field">
                <label for="state">Phone</label>
                <input type="text"  class="inputbar" name="state" value="<?php echo escape($user->data()->phone); ?>">
            </div>
            <div class="field">
                <label for="zipcode">Phone Network</label>
                <input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->network); ?>">
            </div>
            <div class="field">
                <label for="zipcode">Birthday</label>
                <input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->birthday); ?>">
            </div>
                <label for="submit">
                <input id="signinButton" name="submit" type="submit" value="Submit">
                </label>
        </form>
    </div>
</body>
</html>

Session class

class Session {
    public static function exists($name) {
        return (isset($_SESSION[$name])) ? true : false;
    }
    public static function put($name, $value) {
        return $_SESSION[$name] = $value;
    }
    public static function get($name) {
        return $_SESSION[$name];
    }
    public static function delete($name) {
        if(self::exists($name)) {
            unset($_SESSION[$name]);
        }
    }

    public static function flash($name, $string = '') {
        if(self::exists($name)) {
            $session = self::get($name);
            self::delete($name);
            return $session;
        } else {
            self::put($name, $string);
        }
    }
}
Paul
  • 3,348
  • 5
  • 32
  • 76
  • Not starting the session in the second file? And why override it in the second file? Show full code. – JOUM Nov 17 '16 at 21:13
  • I am starting the session in both files. Any other code than this is not necessary. So, I do not have to call for it in the second file? – Paul Nov 17 '16 at 21:14
  • file 2 - maybe `$profile_viewer = $_SESSION['viewer'];` – AbraCadaver Nov 17 '16 at 21:15
  • But you are talking about `Carrying` and not overriding, or? – JOUM Nov 17 '16 at 21:15
  • I just want the variable `$profile_viewer` to be set in a session and be carried forward to php file 2, so I can call the variable. – Paul Nov 17 '16 at 21:17
  • Just what I said... – AbraCadaver Nov 17 '16 at 21:18
  • @AbraCadaver ok, so I changed my code to what you put and now it appears the variable is set (I think) because it doesn't throw the UND variable, but when I try to add it to my query, the error says that the $profile_viewer` cannot be null. – Paul Nov 17 '16 at 21:21
  • @AbraCadaver I added my query code to my question so you can see. The error is coming from the execute line. – Paul Nov 17 '16 at 21:24
  • Dunno 1. `$user_id` doesn't exist 2. `date` is a reserved word in MySQL probably others. – AbraCadaver Nov 17 '16 at 21:28

1 Answers1

1

The only variables that get carried between scripts are $_SESSION['xxx']. Ordinary variables like $profile_user don't persist. The assignment

$_SESSION['viewer'] = $profile_user;

doesn't make $profile_user get copied, it copies its value into $_SESSION, and you have to pull it out of there in the other script. So script 2 should start with:

session_start();
$profile_user = $_SESSION['viewer'];
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • That is what I have, unless I am over-looking something. I just updated my question. – Paul Nov 17 '16 at 21:30
  • Error message: `Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'friend_two' cannot be null' in /add-friend.php:20 Stack trace: #0 /add-friend.php(20): PDOStatement->execute(Array)` – Paul Nov 17 '16 at 21:32
  • That's not the same error you showed in the question. – Barmar Nov 17 '16 at 21:33
  • Do you have `session_start()` in the second script? – Barmar Nov 17 '16 at 21:33
  • Yes, I have session start and $user_id defined in an init file. – Paul Nov 17 '16 at 21:34
  • The following: `array(3) { ["user"]=> string(2) "55" ["token"]=> string(32) "ec849610020b943844cb0692fcfb7764" ["viewer"]=> NULL }` – Paul Nov 17 '16 at 21:36
  • Run @Barmar! Run! – AbraCadaver Nov 17 '16 at 21:38
  • There must be some mistake when you're assigning the session variable in the first script, or some other script is overwriting it with `null`. – Barmar Nov 17 '16 at 21:38
  • The only other occurence of the variable $profile_user in the first file is this: `if($profile_user == $user_id) {` – Paul Nov 17 '16 at 21:40
  • Is there some other user of `$_SESSION['viewer']` in the first file? – Barmar Nov 17 '16 at 21:42
  • Something is changing the value of the session variable to `null` after you assign it. – Barmar Nov 17 '16 at 21:42
  • I just found this on the last line of the source code: `Notice: Unknown: Skipping numeric key 24 in Unknown on line 0
    ` 24 is the value of the `$profile_user`.
    – Paul Nov 17 '16 at 21:43
  • See http://stackoverflow.com/questions/18797251/notice-unknown-skipping-numeric-key-1-in-unknown-on-line-0 – Barmar Nov 17 '16 at 21:44
  • It sounds like you wrote `$_SESSION[$profile_user]` somewhere. – Barmar Nov 17 '16 at 21:45
  • Clearing it did not help. I did a ctr - f search on the page for all `$_SESSION`'s the only thing that appeared was the one I posted above and then this `$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );` – Paul Nov 17 '16 at 21:49
  • Delete your `PHPSESSID` variable and start fresh. – Barmar Nov 17 '16 at 21:53
  • @Barmar Do you think a global config would cause an issue, such as this: `$GLOBALS['config'] = array( 'session' => array( 'session_name' => 'user', 'token_name' => 'token' ) );` – Paul Nov 17 '16 at 21:55
  • I also have a session class, which I added to my question. – Paul Nov 17 '16 at 21:57
  • `Delete your PHPSESSID variable and start fresh` This is after the `$profile_user` session. – Paul Nov 17 '16 at 22:00
  • I don't see how the global variable could affect this. But make sure you don't have something like `Session::put($profile_user)`. "Skipping numeric key" means that there's some place in your script where it users the value of `$profile_user` as the key into `$_SESSION`. – Barmar Nov 17 '16 at 22:05
  • It has the numeric key line I told you on the last line of the source code, but on the first line it has just `24`. But..... when I look on at the source code with firefox (different browser) it does not show it in the source code. – Paul Nov 17 '16 at 22:09
  • PHP runs on the server, you can't see the source code in the browser. – Barmar Nov 17 '16 at 22:10
  • The error message says line 0 because it doesn't detect the error until the script finishes and it's saving all the session variables to disk. You need to search your code for some place where it's using the variable instead of the name of the session variable. – Barmar Nov 17 '16 at 22:12
  • I just added file 1 to my question, trimmed down, without css, JS, metas, etc to show you how it is set up. I don't have an instance of what you are referring to. – Paul Nov 17 '16 at 22:16
  • I don't see `session_start();`. Is it in `init_account.php`? Maybe the problem is in there. – Barmar Nov 17 '16 at 22:18
  • Yes, it is in the init file. I tried adding it over the $profile_user variable and it throws the following error : `Notice: A session had already been started - ignoring session_start()` – Paul Nov 17 '16 at 22:21
  • You can ignore that warning, it's not a problem. – Barmar Nov 17 '16 at 22:22
  • Not that it should matter, but why aren't you using the `Session` class to set `$_SESSION['viewer']`? – Barmar Nov 17 '16 at 22:24
  • I am not sure how to add it to the class. It appears adding the `session_start()` made this work. I have no idea how though because it is in the first line of my init file? ` – Paul Nov 17 '16 at 22:38