通过会话将变量携带到另一个文件

时间:2016-11-17 21:10:43

标签: php session

我搜索了这个网站上的很多帖子,找出为什么我的会话变量没有被识别,但我还没有找到解决方案。

这简直就是我想做的事情。我有两个PHP文件。第一个我有以下代码。我已经开始了一个会议。

PHP文件1

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

PHP文件2

$_SESSION['viewer'] = $profile_viewer;

我一直收到错误:Notice: Undefined variable: profile_viewer

$profile_viewer放入会话然后调用会话时,我做错了什么?

编辑:

档案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));
    }

文件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>

会话课

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

脚本之间唯一的变量是$_SESSION['xxx']。像$profile_user这样的普通变量不会持续存在。作业

$_SESSION['viewer'] = $profile_user;

不会复制$profile_user,它会将其值复制到$_SESSION,您必须将其从其他脚本中拉出来。所以脚本2应该以:

开头
session_start();
$profile_user = $_SESSION['viewer'];