PHP setcookie工作但不是在所有目录中

I am implementing a 'remmeber me' system in PHP, setting a cookie to keep the user logged in. Here is a snippet of my 'sign in code' :

if(password_verify(trim($_POST['password']), $hash) == false) {
        $incorrect_err = true;
} else {

       // Excellent! All good
       $_SESSION['signed_in'] = true;
       $_SESSION['id'] = $id;
       $_SESSION['username'] = $username;
       $_SESSION['first_name'] = $first_name;
       $_SESSION['last_name'] = $last_name;
       $_SESSION['email'] = $email;
       $_SESSION['hash'] = $hash;
       $_SESSION['profile_picture'] = $profile_picture;

       // Update 'last activity' in database
       $sql = 'UPDATE `users` SET `last_activity` = CURRENT_TIMESTAMP, `times_signed_in` = `times_signed_in` + 1 WHERE `id` = ' . strval($_SESSION['id']);
       mysqli_query($conn, $sql);

        //Set cookie if necessary
        if(!empty($_POST['keep-me-signed-in-input'])) {
             $days = 30;
             $value = $_SESSION['hash'];
             setcookie("rememberme",$value,time()+ ($days * 24 * 60 * 60), '/');

       // Go to correct page
       if(!empty($_SESSION['destination'])) {
       $location = 'location: ' . $_SESSION['destination'];
       } else {
           header('location: dashboard');

However, now when I sign in, I am not taken to the dashboard page as expected. Also, it seems the cookie can only be read by pages in the same directory (pages/users/) as the sign in page, even though I put a "/" into my setcookie statement.

This is how my main.php (included at the start of every page load) looks:

if(!($_SESSION['signed_in'] == true)) { // User is logged out

    if(isset($_COOKIE['rememberme']) && $sign_in_from_cookie !== false) {
        $hash = $_COOKIE['rememberme'];
        $sql = 'SELECT * FROM `users` WHERE `id` = "' . $hash . '"';
        if($result = mysqli_query($conn, $sql)) {
            $row = mysqli_fetch_assoc($result);
            $_SESSION['email'] = $row['email'];
            $_SESSION['first_name'] = $row['first_name'];
            $_SESSION['last_name'] = $row['last_name'];
            $_SESSION['signed_in'] = true;
            $_SESSION['hash'] = $hash;
            $_SESSION['username'] = $row['username'];
            $_SESSION['profile_picture'] = $row['profile_picture'];
            $_SESSION['id'] = $row['id'];


Does anybody know what in the world I have done wrong?

duanpai1033 还有其他东西可以为子目录设置记忆cookie吗?最具体的cookie获胜。如果您查看开发人员工具中的cookie列表,您应该能够看到它们。
大约一年之前 回复
douquanhui5735 哎呀-我会解决的
大约一年之前 回复
douhui1630 为什么你乘以1000?过期时间以秒为单位,而不是毫秒。
大约一年之前 回复
Csdn user default icon
php setcookie有效期问题

使用session时,cookie有效期在服务器端设置的,传递到客户端,如果客户端电脑的时钟不正确,cookie能正确地被处理吗? 比如,假设服务器的时间是对的,服务器设置一个当前时间+3600秒的cookie,但客户端的时钟不对,且时钟快2个小时,那这样的一个cookie不是刚刚被下发下来就失效了吗,请大神指点。

php - 在setcookie之后获取cookie

<div class="post-text" itemprop="text"> <p><code>Notice: Undefined index: posts_notification</code> while it's set.</p> <pre><code>functions.php : add_action( 'init', 'my_setcookie_example' ); function my_setcookie_example() { if (!isset($_COOKIE['posts_notification'])){ setcookie( 'posts_notification', 'value', time() + 60,COOKIEPATH, COOKIE_DOMAIN); } } print_r($_COOKIE['posts_notification'] ); </code></pre> <p>I should refresh 2 time to get this value !!!</p> </div>

PHP的setcookie()函数不起作用。 怎么了?

<div class="post-text" itemprop="text"> <p>I really need some help here. I wrote this script to track my website's traffic. I <strong><em>was using</em></strong> cookies to help the server know when a client has visited a page once already for the day, which allowed me to track visitors by two (2) counters/categories: UNIQUE hits and "REFRESH" hits.</p> <p>I store the information in directories named by date. For example, the file located at <code></code> would store a number like 62, which would mean I got 62 unique hits to the <code>about.php</code> page on December 31st, 2015.</p> <p>Each page calls the script <code>counter.php</code>. Everything seems to work fine, but both of my counters continue to read the same number, as if every hit is unique. I knew something was wrong when I saw the two sets of numbers, and I confirmed it by refreshing the index page several times. What it means is that the cookies are not being set. The PHP script in <code>counter.php</code> tests for the cookie to see if it has been set. I have been also checking the cookies from my browser settings and it shows no cookies. I refresh each page several times and re-check for the cookies several times, but still no luck!</p> <p>What in the world is going on here?!? It was working before!</p> <p>The following shows how each page calls the <code>counter.php</code> script:</p> <p><code></code>:</p> <pre><code>&lt;?php include_once("log/counter.php"); ?&gt; &lt;!doctype html&gt; &lt;html&gt; ... &lt;/html&gt; </code></pre> <p>The following is my PHP code called <code>counter.php</code>:</p> <p><code></code></p> <pre><code>&lt;?php // THIS LINE WAS NOT PART OF MY ORIGINAL SCRIPT ob_start(); // THIS IS THE PAGE THAT IS CALLING THIS SCRIPT, // FOR EXAMPLE: ABOUT, INDEX, CONTACT, ETC. $page = basename($_SERVER["SCRIPT_FILENAME"], ".php"); // THE DIRECTORY WHERE THIS SCRIPT IS LOCATED // RELEVANT TO THE CALLING PAGE $cwd = dirname(__FILE__) . "/counter/"; date_default_timezone_set('America/Chicago'); // TIMEZONE FOR HOUSTON, TEXAS. THIS WAY, ALL // DATE &amp; TIME INFO IS SET IN THAT TIMEZONE $currentYear = date("Y"); // EX: 2015 $currentMonth = date("m"); // EX: 12 $currentDay = date("d"); // EX: 31 // THIS PREPARES THE DIRECTORY FOR TODAY'S DATE $today = $currentMonth."/".$currentDay."/".$currentYear; $current = $currentYear."/".$currentMonth."/".$currentDay."/"; $currentHour = date("H"); $currentMinute = date("i"); $currentSecond = date("s"); // THE FOLLOWING IS USED FOR THE COOKIE EXPIRATION PARAM $secondsRemaining = 60 - $currentSecond; $minutesRemaining = 59 - $currentMinute; $hoursRemaining = 23 - $currentHour; $totalSecondsRemaining = ($hoursRemaining * 60 * 60) + ($minutesRemaining * 60) + $secondsRemaining; if ($totalSecondsRemaining&lt;=0) { $totalSecondsRemaining = 86400; } // 86400 SECONDS = 24 HOURS / 1 DAY $ucFile = $cwd . "unique/" . $current . $page; // UNIQUE-HITS COUNTER $rcFile = $cwd . "refresh/" . $current . $page; // REFRESH-HITS COUNTER // MAKE SURE ALL DIRECTORIES EXIST if (!file_exists($cwd."unique/")){ mkdir($cwd."unique", 0755); } if (!file_exists($cwd."unique/".$currentYear)){ mkdir($cwd."unique/".$currentYear, 0755); } if (!file_exists($cwd."unique/".$currentYear."/".$currentMonth)){ mkdir($cwd."unique/".$currentYear."/".$currentMonth, 0755); } if (!file_exists($cwd."unique/".$currentYear."/".$currentMonth."/".$currentDay)){ mkdir($cwd."unique/".$currentYear."/".$currentMonth."/".$currentDay, 0755); } if (!file_exists($cwd."refresh/")){ mkdir($cwd."refresh", 0755); } if (!file_exists($cwd."refresh/".$currentYear)){ mkdir($cwd."refresh/".$currentYear, 0755); } if (!file_exists($cwd."refresh/".$currentYear."/".$currentMonth)){ mkdir($cwd."refresh/".$currentYear."/".$currentMonth, 0755); } if (!file_exists($cwd."refresh/".$currentYear."/".$currentMonth."/".$currentDay)){ mkdir($cwd."refresh/".$currentYear."/".$currentMonth."/".$currentDay, 0755); } // ALL DIRECTORIES NOW EXIST. SO FAR, NO PROBLEMS! // UNIQUE COUNTER... if (!isset($_COOKIE[$page])){ // THIS ALWAYS GETS CALLED... if (file_exists($ucFile)){ // IF PAGE HAS BEEN COUNTED... $file = fopen($ucFile, "r+"); // 1. OPEN THE COUNTER FILE FOR PAGE $count = fgets($file); // 2. GET THE CURRENT COUNT fclose($file); // 3. CLOSE THE FILE $file = fopen($ucFile, "w"); // 4. RE-OPEN FILE AND CLEAR IT fputs($file, $count+1); // 5. REPLACE WITH CURRENT COUNT+1 } if (!file_exists($ucFile)){ // IF THIS IS THE FIRST TIME TODAY... $file = fopen($ucFile, "w"); // 1. CREATE A COUNTER FOR THIS PAGE fputs($file, "1"); // 2. PUT 1 AS THE CURRENT COUNT } $works = setcookie($page, "Today is ".$today, $totalSecondsRemaining); // SET A COOKIE INDICATING THAT THIS PAGE HAS BEEN // VISITED ALREADY BY THIS GUEST. } // REFRESH COUNTER... if (file_exists($rcFile)){ // IF PAGE HAS BEEN COUNTED... $file = fopen($rcFile, "r+"); // (REPEAT STEPS ABOVE, 1-5) $count = fgets($file); fclose($file); $file = fopen($rcFile, "w"); fputs($file, $count+1); } if (!file_exists($rcFile)){ $file = fopen($rcFile, "w"); fputs($file, "1"); } // AGAIN, NOT PART OF THE ORIGINAL SCRIPT. ob_end_flush(); // ALWAYS RETURNS TRUE... echo "&lt;!-- $works --&gt;"; ?&gt; </code></pre> <p>I have tried everything I can think of to get this script working again. To the best of my knowledge, I never changed anything in the code; it just stopped working one day.</p> <h2>So, what I've already checked so far is:</h2> <ul> <li>I know there is <strong>NO</strong> output before the headers are sent.</li> <li>I know that PHP thinks the cookie is being set, because <code>setcookie()</code> returns true</li> <li>I know the cookie expiry date is set in the future.</li> <li>I know the expiry date is <strong>NOT</strong> larger than PHP's integer max-size <ul> <li>PHP Integer maximum value is about 32 bits, mine is no more than 5 characters</li> </ul></li> <li>I know that neither <code></code> nor simply <code></code> change the script's behavior</li> </ul> <p>I have also tried the following:</p> <pre><code>setcookie($page, "Today is ".$today, $totalSecondsRemaining); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/"); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", ""); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", ""); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", ""); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "*"); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", ""); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", 0); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", 0); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "*", 0); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", 0); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", false); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", false); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "*", false); setcookie($page, "Today is ".$today, $totalSecondsRemaining, "/", "", false); </code></pre> <p>I isolated the problem to the PHP <code>setcookie()</code> function. Any help is really, really, greatly appreciated.</p> <p>P.S.</p> <p>Admittedly, I'm sure that it would be better to store this information in a MySQL Database, but I'll work on that once I get this problem fixed.</p> </div>

php setcookie,域名没有正确限制在chrome但是在Firefox中

<div class="post-text" itemprop="text"> <p>I'm setting a cookie in php:</p> <pre><code> setcookie('testcookie[test_id]', "testvalue", (time()+(60*60*24*31)), "/", ".".$_SERVER['SERVER_NAME'],"1"); </code></pre> <p>My live site domain value is like "" and the test site is similar but shorter, e.g. "". </p> <p>Here is the funny thing: The cookie is set fine, both on my testing server and live server. On my testing server, I can see both cookies, the cookie is duplicated! </p> <p>So, for example when I navigate from my live server to my testing server, the cookies is duplicated and I can see both live and testing versions when browsing the test stie in Chrome. In FireFox, I only see one copy of the cookie in either site, which is desired result. </p> <p>I have an entry in /etc/hosts on my machine to direct "" to my test site.</p> <p>So, am I doing something wrong in how I'm setting cookies, or is this a quirk of Chrome?</p> </div>

PHP setcookie返回null

<div class="post-text" itemprop="text"> <p>I am working on localhost. I have already a cookie is created with two keys. i want to store the third key, but i couldn't save this third key inside the cookie. It always return null. Also this new key is not available after page refresh. Here is my code</p> <pre><code>$cart_data = array ('1','2'); $test = setcookie('user_cart', serialize($cart_data), time() + (60 * 20),'/',false,false,false); var_dump($test); die; </code></pre> <p>// Checking output like this. (This code is in other file)</p> <pre><code>if(isset($_COOKIE['user_cart'])){ echo '&lt;pre&gt;'; print_r($_COOKIE); die; } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>whenever the ajax page is called, i run:</p> <pre><code>setcookie($filtersCookie, $cookieVal, time() + 86400); // 1 day </code></pre> <p>and when the page is refreshed, i use the following code to see if there were any past filters saved:</p> <pre><code>if(isset($_COOKIE[$filtersCookie])) { </code></pre> <p>but the cookie never exists after a page refresh. any ideas as to why this may happen?</p> <p>setcookie is used before any browser output from the ajax call.</p> </div>

Setcookie PHP问题localhost vs普通域名

<div class="post-text" itemprop="text"> <p>I was working on my website on localhost (where it worked correctly) and then I moved it to classic domain, but there is issue with PHP setcookie function.</p> <p>Here is my setcookie sample, basically it will take data from URL paramater called "ID" and then save it as cookie and then it will redirect to website to hide URL paramater.</p> <p>Yes it works on localhost, but on normal website no..I dont know what to do please help me :)</p> <pre><code>if (isset($_GET['id'])) { $hafcookie = $_GET['id']; setcookie( 'lolcookies', $hafcookie, time() + (10 * 365 * 24 * 60 * 60), COOKIEPATH, COOKIE_DOMAIN ); header( "refresh:0; url=" ); } </code></pre> </div>

setcookie()不在Internet Explorer或safari中工作

<div class="post-text" itemprop="text"> <p>I had the following code:</p> <pre><code>setcookie('username', $email, false, 'affiliates/', ''); </code></pre> <p>It wasn't working in IE or Safari. Then I changed it to:</p> <pre><code>setcookie('username', $email, time()+60*60*24, 'affiliates/', ''); </code></pre> <p>And it started working. Now, 2 days later, it doesn't work again. I don't think I changed anything. The setting of the cookie is being checked in another file, with this code:</p> <pre><code>if( isset($_COOKIE['username']) ) { ... } else { print( "&lt;meta HTTP-EQUIV='REFRESH' content='0; url=index.html'&gt;" ); exit(); } </code></pre> <p>It always redirects to index.html (in Safari and IE). Any ideas why this would cease to work? (I've made sure cookies are enabled in both browsers).</p> <p>One thing I did during the time it stopped working was test the site running on localhost. I changed the code to:</p> <pre><code>setcookie('username', $email, time()+60*60*24, 'affiliates/', null); </code></pre> <p>But only for the localhost version.</p> </div>

在Chrome中的php COOKIE setcookie故障,在FF中工作正常[重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/20316870/php-setcookie-not-working" dir="ltr">PHP - setcookie(); not working</a> <span class="question-originals-answer-count"> 4 answers </span> </li> </ul> </div> <p>This is my php cookie code,</p> <pre><code>setcookie("city_id", $cityData[0]['city_id'], 2147483647, "/", "localhost"); setcookie("cityname", $cityData[0]['cityname'], 2147483647, "/", "localhost"); echo $_COOKIE['city_id']; echo $_COOKIE['cityname']; </code></pre> <p>Above code is working fine on FF, but not working in Chrome.... Any suggestions....</p> </div>

使用JS发布时,php setcookie不起作用

<div class="post-text" itemprop="text"> <p>I have a strange problem- In my website <a href="" rel="nofollow noreferrer"></a> I have this JS code, triggered on some JS event:</p> <pre><code>$.post( '', { storageData: storageData }, function(data) {console.log(data)} ); </code></pre> <p>In <a href="" rel="nofollow noreferrer"></a>, the file save_cookie.php looks like this:</p> <pre><code>$test = setcookie('test_cookie', '1', time() + (10 * 365 * 24 * 60 * 60), '/'); echo $test; </code></pre> <p>When I trigger the JS event, I can see in the network tab that everything is okay, that the request sent successfully to the url <a href="" rel="nofollow noreferrer"></a>, and I can see "1" printed in the console, from the callback function.</p> <p>But in <a href="" rel="nofollow noreferrer"></a>, <code>$_COOKIE['test_cookie']</code>, is <code>null</code>. However, If I just browse the url, and check the variable <code>$_COOKIE['test_cookie']</code> after that, I can see that the value is '1', as expected. Any ideas why the cookie is not set when posting the request with ajax?</p> <p>Thanks!</p> </div>

php setcookie没有按预期工作

<div class="post-text" itemprop="text"> <p>I am learning PHP now. Any one can take a look at this and see why the cookie is not set and keep showing as empty?</p> <pre><code>&lt;?php if ($_COOKIE["name"]) { echo "welcome back" . $_COOKIE['name']; } else { $fname = $_POST["fname"]; $age = $_POST["age"]; if ($fname) { echo "your name is ".$fname; setcookie("name", $fname, time()+6000); echo "cookie" . $_COOKIE['name']; } if ($age) { echo "your age is " . $age; } } ?&gt; &lt;html&gt; &lt;body&gt; &lt;form action="index.php" method="post"&gt; Name: &lt;input type="text" name="fname"&gt; Age: &lt;input type="text" name="age"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;a href="info.php"&gt;info&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div>


``` <?php setcookie("color","red"); echo $_COOKIE["color"]; /*color is red*/ /* your codes and functions*/ setcookie("color","blue"); echo $_COOKIE["color"]; ?> ``` ![图片说明](


<div class="post-text" itemprop="text"> <p>I have problem with seting and reading cookie on wordpress site.</p> <p>Here is what I'm doing:</p> <p>1.Sending over js id to php</p> <p><strong>ajax.js</strong></p> <pre><code>"/wp-content/themes/mytheme/ajax.php", {post_id: post_id}, function(data){ }); </code></pre> <p><strong>ajax.php</strong></p> <pre><code>setcookie('myids', $_COOKIE['myids'].$_POST['post_id'], time()+3600*24*100, '/'); </code></pre> <p>2.When I read that cookie ( echo $_COOKIE['myids']; )in /wp-content/themes/mytheme/<strong>index.php</strong> </p> <p>I get value which I set and that is ok but when i try to read that cookie in /wp-content/themes/mytheme/ajax.php I am not getting cookie.</p> <p>What I am doing wrong?</p> </div>


<div class="post-text" itemprop="text"> <p>I need to set cookies in an assignment. When I set them using a string, ie <code>setcookie('Name', 'John', time() + 86400)</code> it works, but when using a PHP variable, ie <code>setcookie('Name', $name, time() + 86400)</code> the cookie is not set.</p> <p>I'm not sure what I am doing wrong. I have echoed out the $name variable on my page and it shows up so I know that is being set. When I display the cookie using <code>$_COOKIE['Name']</code>, it works when it received a string, but doesn't when it's a <code>PHP variable</code>.</p> <h1>order01.php</h1> <pre><code>&lt;form action="order02.php" class="formLayout"&gt; &lt;div class="formGroup"&gt; &lt;label&gt;First name:&lt;/label&gt; &lt;input type="text" name="fname" class="textbox" autofocus required placeholder="First name" title="first name" maxlength="20" pattern="[A-Za-z'-]{2,20}"&gt; &lt;/div&gt; &lt;div class="formGroup"&gt; &lt;label&gt; Car model:&lt;/label&gt; &lt;div class="formElements"&gt; &lt;input type="radio" name="model" required value="Mustang"&gt;Ford Mustang&lt;br&gt; &lt;input type="radio" name="model" required value="Subaru"&gt;Subaru WRX STI&lt;br&gt; &lt;input type="radio" name="model" required value="Corvette"&gt;Corvette&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $name = $_GET['fname']; $model = $_GET['model']; //write cookies for name and model for 1 day setcookie('Name', $name, time() + 86400); setcookie('Model', $model, time() + 86400); ?&gt; </code></pre> <h1>order02.php</h1> <pre><code>if(isset($_COOKIE['Name'])){ echo "Cookie ".$_COOKIE['Name']." is set"; } else{ echo "&lt;div class='pageContainer'&gt;"; echo "&lt;h2 class='containerText, centerText'&gt;Failed to validate inputs"; echo "&lt;br&gt;&lt;br&gt;"; echo "&lt;a href='order01.php'&gt;&lt;button&gt;Go Back&lt;/button&gt;&lt;/a&gt;"; echo "&lt;/div&gt;"; exit(); } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I have a login script in which i authenticate the user, and as soon as authentication is completed, i want to set cookies for him. but my script is executing perfectly till authentication, but it's not executing further after setcookie, may be it's not able to execute this function. Here is my code.</p> <pre><code>$validCredentials = checkCredentials($loginEmail, $loginPassword); if ($validCredentials === 1) { if(isset($_POST['rememberMe'])) { $yearExpire = time() + 60*60*24*365; // 1 Year setcookie('rememberedUser', $loginEmail, $yearExpire); setcookie('loggedIn', $loginEmail, $yearExpire); } else { if(isset($_COOKIE['rememberedUser'])) { $pastExpire = time() - 100; setcookie('rememberedUser', '', $pastExpire); } $shortExpire = time() + 60*60*24; setcookie('loggedIn', $loginEmail, $shortExpire); die(msg(0,"Logged In !")); } } </code></pre> <p>Please tell me whats wrong in my code. Please help !!</p> </div>

setcookie()在jquery get()请求

<div class="post-text" itemprop="text"> <p>My problem is that the cookie won't set. I tried removing the <code>/</code> in the <code>setcookie</code> function but it changes nothing. Also, the path is correct. If I <code>echo</code> something after the <code>setcookie</code> line, and I <code>alert</code> the data in the javascript function, the echo works.</p> <p>index.php:</p> <pre><code>$.get('inserts/queries?q=1', function(data) { undisplay('cookiesMenu'); }); </code></pre> <p>inserts/queries.php:</p> <pre><code>if ($_GET['q'] == 1) { setcookie('cookies', '', time() + 3600 * 24 * 365, '/'); } </code></pre> </div>

php setcookie没有错误

<div class="post-text" itemprop="text"> <p>I'm trying to set cookies with PHP. I wrote a login script that checks data received from the user with database data and then if data matched, it sets a cookie that stores username and password to be used in the next two hours. This is a PHP script to handle an HTTP POST request and output JSON to be used in a react app.</p> <p>I used ob in my code and I am sure that there are no headers sent before setting cookies.</p> <p>This is how my code looks like.</p> <pre class="lang-php prettyprint-override"><code> &lt;?php ob_start(); function cook($user, $pass, $time){ setcookie("user", $user, time() + $time, "/", "localhost", 0); setcookie("pass", $pass, time() + $time, "/", "localhost", 0); } header('Content-Type: application/json'); //login code(receive data, check password, ...) cook($user, hash("sha512", $pass), 7200); $output = //my code output object echo json_encode($output); ob_end_flush(); </code></pre> <p>There is no errors and exception.</p> <p><strong>UPDATE:</strong> I am using cross-origin request. My client is on localhost:3000 and PHP scripts are running on localhost:8080</p> </div>

php setcookie不起作用

<div class="post-text" itemprop="text"> <p>Below are my test files. This is all they contain.</p> <p>File test.php:</p> <pre><code>&lt;?php setcookie("test", "test", time() + 3600); header("Location:test2.php"); </code></pre> <p>File test2.php:</p> <pre><code>&lt;?php if(!isset($_COOKIE['test'])) { echo 'cookie not set'; } else { echo 'cookie set'; } </code></pre> <p>When I try to display the test.php page I got "cookie not set". This is driving me crazy...</p> <p>Here is what i checked so far:</p> <ul> <li>I tested with Safari / Chrome / Firefox,</li> <li>My browsers accept cookies,</li> <li>As you can see in my example there is no output sent to browser before calling setcookie function,</li> <li>When displaying the result of the setcookie function, I got true,</li> <li>it works on my local computer, but not on my server,</li> </ul> <p>Last point let me believe there is something wrong in the server configuration? I'm on a share hosting server so there is not much I can do about that.</p> </div>


<div class="post-text" itemprop="text"> <p>I have a curl script that acts as proxy between client and main server.</p> <p>......</p> <pre><code>$field_array= array( 'Accept' =&gt; 'HTTP_ACCEPT', 'Accept-Charset' =&gt; 'HTTP_ACCEPT_CHARSET', 'Accept-Encoding' =&gt; 'HTTP_ACCEPT_ENCODING', 'Accept-Language' =&gt; 'HTTP_ACCEPT_LANGUAGE', 'Connection' =&gt; 'HTTP_CONNECTION', 'Host' =&gt; 'HTTP_HOST', 'Referer' =&gt; 'HTTP_REFERER', 'User-Agent' =&gt; 'HTTP_USER_AGENT' ); $curl_request_headers=array(); foreach ($field_array as $key =&gt; $value) { if(isset($_SERVER["$value"])) { $server_value=$_SERVER["$value"]; $curl_request_headers[]="$key: $server_value"; } }; $curl_request_headers[]="Expect: "; session_write_close(); //Open connection $curl_handle = curl_init(); curl_setopt($curl_handle,CURLOPT_COOKIE,session_name()."=".session_id().";"); //Set the url, POST data curl_setopt($curl_handle, CURLOPT_URL, $curl_url); curl_setopt($curl_handle, CURLOPT_POST, !empty($user_post_data)); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $user_post_data); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_AUTOREFERER, TRUE); curl_setopt($curl_handle, CURLOPT_HEADER, 1); curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, false); curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $curl_request_headers); curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($curl_handle); //Close connection curl_close($curl_handle); list($headers,$content)=explode(" ",$result,2); foreach (explode(" ",$headers) as $hdr) { if(preg_match("/Transfer-Encoding:.*chunked/i", $hdr)) { // Remove chunked headers. Not properly handled by browsers } else { header($hdr); }; } echo $content; </code></pre> <p>Now, on main server, I set a cookie in an script and then try to read its value in another script. I cannot read the value. So there is some problem passing the value around in curl. How to fix?</p> <p>thanks</p> <h2>FOUND SOLUTION:</h2> <p>Actually, a stupid problem. I need to explicitly set cookies in CURLOPT_COOKIE. Following code now works for me:</p> <pre><code>...... $_COOKIE[session_name()]=session_id(); $cookie_string=""; foreach( $_COOKIE as $key =&gt; $value ) { $cookie_string .= "$key=$value;"; }; //Open connection $curl_handle = curl_init(); curl_setopt($curl_handle,CURLOPT_COOKIE, $cookie_string); ...... </code></pre> </div>


今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...





String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...


文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

将一个接口响应时间从2s优化到 200ms以内的一个案例

一、背景 在开发联调阶段发现一个接口的响应时间特别长,经常超时,囧… 本文讲讲是如何定位到性能瓶颈以及修改的思路,将该接口从 2 s 左右优化到 200ms 以内 。 二、步骤 2.1 定位 定位性能瓶颈有两个思路,一个是通过工具去监控,一个是通过经验去猜想。 2.1.1 工具监控 就工具而言,推荐使用 arthas ,用到的是 trace 命令 具体安装步骤很简单,大家自行研究。 我的使用步骤是...


微信上收到一位读者小涛的留言,大致的意思是自己只有高中学历,经过培训后找到了一份工作,但很难胜任,考虑要不要辞职找一份他能力可以胜任的实习工作。下面是他留言的一部分内容: 二哥,我是 2016 年高中毕业的,考上了大学但没去成,主要是因为当时家里经济条件不太允许。 打工了三年后想学一门技术,就去培训了。培训的学校比较垃圾,现在非常后悔没去正规一点的机构培训。 去年 11 月份来北京找到了一份工...


JVM内存结构和Java内存模型都是面试的热点问题,名字看感觉都差不多,网上有些博客也都把这两个概念混着用,实际上他们之间差别还是挺大的。 通俗点说,JVM内存结构是与JVM的内部存储结构相关,而Java内存模型是与多线程编程相关,本文针对这两个总是被混用的概念展开讲解。 JVM内存结构 JVM构成 说到JVM内存结构,就不会只是说内存结构的5个分区,而是会延展到整个JVM相关的问题,所以先了解下

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Google 与微软的浏览器之争

浏览器再现“神仙打架”。整理 | 屠敏头图 | CSDN 下载自东方 IC出品 | CSDN(ID:CSDNnews)从 IE 到 Chrome,再从 Chrome 到 Edge,微软与...


loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...








蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?



提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...






私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...






本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...




当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...


HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...