PHP - Curl Cookie Problem
Hey guys,
I have developed an script which opens or fetches a page using curl, now the problem is the url i am trying to fetch follows lot of redirects(say 302) and in between it stores several cookies also which i don't know or guess. So i was just thinking, is there any way so that i can automatically store the cookies in a particular file which server wants to store, and let it sent in request as per the asking of a request in request header? I hope you would have got what i mean to say here, for example suppose i want to open http://www.example.com and now that above url faces lot of redirects probably 5-6 and then ends up on http://www.test.com now in between it stores some cookies in clients computer and then it fetches them also. Since i don't know which cookie it gonna store, I must put this responsibility to PHP itself to store and send the requested cookies in request headers. Also i want to send the referrer also in request header, and it must be the last page that or request sent to the server, no matter whether it's in betwen redirects or to the final page. In short i mean to create the complete emulation of browser for this URL. Similar TutorialsHi,
I'd stumbled upon a problem around doing curl on an asp website which use cookie.
I use username n session id to determine the cookie file, on a case when a second browser open up it should have different session id, hence it may create new cookies instead of using the active previously-made cookie file, please do correct me if I'm wrong.
So question is....how to detect a user is logged or not in such situation ?
Or perhaps how is the proper way to determine a cookie file in such situation ?
Thanks in advance,
I am working on a website that depends on a complex cookie being set. In an effort to fix problems before they become big problems, I want to monitor that the cookie is getting set correctly with a cron job. I can setup the cron job just fine, but I can't figure out how to get the value of the cookie. By visiting the main site the cookie is set automatically, and I've also made a special script on that server that only gets me that cookie value and spits it out. I am trying to use cURL to call the main page, and then right after that, call the get-cookie.php page which should then have cookie data to display. Here is how I am trying to do it now: <?php $c = curl_init(); // making the initial call to the real website curl_setopt($c, CURLOPT_URL, 'http://domain.com'); curl_setopt($c, CURLOPT_HEADER, false); curl_exec($c); curl_close($c); $c = curl_init(); // now making a call to the script that spits out the cookie curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_URL, 'http://domain.com/get-cookie.php'); curl_setopt($c, CURLOPT_HEADER, false); $output = curl_exec($c); curl_close($c); echo 'output: ' . $output . "\n\n"; ?> I've tried a few different things here, but so far no luck. Anyone have any ideas on how I can make this work? Thanks so much!
I'm trying to login to a site, navigate a couple of pages deep, and then scrape a table. I had all this working, but the site changed their login workflow...and I can't figure out what I need to do to make this work. Hi to everyone, I'm new to the forum and I'm posting here because I ended up in a logical problem for my next script development.
I need to get some data of external websites (with vbulletin board), perfectly legal.
Using file_get_contents i can print the page content on my server and then use jquery's powerful selectors to get my data.
The problem is that these data are shown only to logged in users so i would need this script (maybe using cURL?) to either login to the external website and then persists the connection or maybe if the user who is executing my script is already logged in that website then use his login? (most likely impossible I think..)
This is my code so far (found on some sites and merged into this)
$data = array('vb_login_username' => 'Scanu', 'vb_login_password' => 'grgfgrgrfbtgbt'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/login.php?do=login"); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec($ch); curl_close($ch); $pattern = "#Set-Cookie: (.*?; path=.*?;.*?)\n#"; preg_match_all($pattern, $result, $matches); array_shift($matches); $cookie = implode("\n", $matches[0]); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/"); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $result = curl_exec($ch); curl_close($ch); echo $result; ?>It just shows the same page for unregistered users. Any help or advice is appreciated, i'm very new to this type of script.. hi today i was checking a site as i m learning more about curl. i see i was not able to get image with curl. they have stopped hotlinking and was not finiding anyway to show me image on my localhost so making this thread for any pro help. here is my code: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.pixhost.org/show/2019/5530476_banner.png"); curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.24 Version/10.54"); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIE, 'pixhostads=1'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec ($ch); echo $result ; if i run that script it will show me that page but it says pictures is hotlinked and cant display, so i tried to see cookie but i m not sure if i am doing it right. on that url u must need to click "Click to continue" before u can see image. Please can someone help why its not showing me the correct image and any way to pass it? thanks Hello, I am new to this forum and joined in hope I could get some help in relation to some PHP problems I have stumbled across within my work. I am currently working on an online store I am building from scratch. I have already built the basic system behind it and am now starting to implement a more user friendly design to it with JS validation, stylesheets and imaging layout. I have however come across a COOKIE problem with my login script. The purpose behind it is to only allow users into an area if they have logged in and declared cookies. I declare the cookies with 'setcookie()' then try and retrieve them with '$_COOKIE['firstname'];'. However since implementing my new design layout it has stopped being able to retrieve the cookies. Here is some of the script. I would greatly appreciate any help given ... Login.php Code: [Select] <?php //Validating input details and executing mysql query if ($username && $pass) { mysql_connect("$dhost","$dname","$dpass"); //Connection to mysql server @mysql_select_db("$dbase") or die ("Unable To Select Database!"); //Connection to stated database $query = "SELECT firstname, lastname, username FROM userdata WHERE password=SHA('$pass')"; //Retrieves firstname and lastname for username and password combination $result = @mysql_query ($query); $row = mysql_fetch_array ($result,MYSQL_NUM); //Return a record, if applicable if ($row) { setcookie('firstname', $row[0], time()+3600); setcookie('lastname', $row[1], time()+3600); setcookie('username', $row[2], time()+3600); //Set the cookies echo "<p class='Body-error-P'><span class='Body-text-T'>Login successful. If you are not redirected in 15 seconds click <A HREF='./index.php'>here</A></span></p>"; print "<meta HTTP-EQUIV='REFRESH' content='5 url=./index.php'>"; } else { //no record matched the query echo "<p class='Body-error-P'><span class='Body-text-T'>The username and password you entered are not valid.</span></p>"; } mysql_close(); //close database connection } } Index.php Code: [Select] <?php include_once ("config.php"); if(isset($_COOKIE['firstname'])) //if not cookie present, redirect the user { echo "<p class='Body-text-P'><span class='Body-text2-T'>You are now logged in, <b>".$_COOKIE['firstname'].' '.$_COOKIE['firstname']."</b></span</p>"; } else { echo '<p class="Body-text-P"><span class="Body-text-T">You are not logged in at this current time. Please login or register.</span</p>'; } ?> Let me know if you need anymore coding... I'm having trouble setting a cookie in php. When a user logs in I send an ajax request to an file which contains this code to set the cookie setcookie("userCookie", $_SESSION['username'], time()+60*60*24*30); However when I include the following code to check to see if the cookie has been set is says is hasn't if(isset($_COOKIE['userCookie'])) { echo("cookie set"); } else { echo("cookie not set"); } I check to see that my browser is accepting cookies and it definitely is so I'm not sure what causing the problem. Thanks for any help. Hello A few days back I searched for a (very) easy php login script, basicly just to show hidden content that's not for everyone. This is the script I found (and it works): <?php $username = "Username"; $password = "Password"; $randomword = "one"; if (isset($_COOKIE['MyLoginPage'])) { if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) { ?> <?php include 'projecten_.php'; $name = "0"; ?> <?php exit; } else { echo "<p>Bad cookie. Clear please clear them out and try to login again.</p>"; exit; } } if (isset($_GET['p']) && $_GET['p'] == "login") { if ($_POST['name'] != $username) { echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>"; exit; } else if ($_POST['pass'] != $password) { echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>"; exit; } else if ($_POST['name'] == $username && $_POST['pass'] == $password) { setcookie('MyLoginPage', md5($_POST['pass'].$randomword)); header("Location: $_SERVER[PHP_SELF]"); } else { echo "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>"; } } ?> <body style="background:url(images/repeat.gif) repeat-x #0a0a09; height:106px; margin:0px; padding:0px; text-align: center;"> <div style="margin-left: auto; margin-right: auto; position: relative; top: 120px; width: 250px; text-align: left; line-height: 28px;"> <img src="images/zenze.png" alt="Zenze" style="position: absolute; top: -100px; left: -375px;" /> <h5 style=" font-weight: none; font-size: 18px; font-family: verdana; margin: 0px; margin-bottom: 20px; color: #96ff00">Login</h5> <form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post"> <label><input type="text" name="name" id="name" /><span style="color: #999999; font-size: 12px; font-family:verdana"> Name</span></label><br /> <label><input type="password" name="pass" id="pass" /><span style="color: #999999; font-size: 12px; font-family:verdana"> Password</span></label><br /> <input type="submit" id="submit" value="Login" style="margin-top: 10px;" /></form> </div> </body> The only problem is, there is no log out fuction. I see this script works with cookies and I gave it a try, and I ended up with nothing but errors. Does anyone one has an idea to how a logout script would look like for this script? Thanks in advance, Crow Alright so I have coded a login system, and logging in works. But I just noticed that logging out did not work. I tried making a test cookie at the very top of my document, and it worked. I couldn't find out why, because there's really nothing in between than can be causing it. I tried moving the code down line by line until it stopped working, it happened after a block of html code. Makes no sense to me at all. Here's the working code, it sets the cookie and returns "Set": Here's the same code a few lines down, cookie is not being set and returns "Not set": Why? XD I tried removing that entire div-block but then the code would just stop working a bit further down in my document. It's a challenge to you, phpfreaks Hello community, I am trying to create a login script, but in the HTTP Header it only sends the last cookie set. I first tried this code: $expire=time()+60*60*24; setcookie("gcg_user",$userid,$expire); setcookie("gcg_name",$username,$expire); setcookie("gcg_pass",$password,$expire); But it only set the gcg_pass cookie. Someone else suggested me to use header(): $expire=date(DATE_RFC822,time()+60*60*24); header('Set-Cookie: gcg_user="'.$userid.'"; expires='.$expire.';'); header('Set-Cookie: gcg_name="'.$username.'"; expires='.$expire.';',false); header('Set-Cookie: gcg_pass="'.$password.'"; expires='.$expire.';',false); But again it only sets the last cookie. The first code has been working fine on another server. Do I have to adjust anything in php.ini? Running XAMPP Lite: Quote ###### Apache Friends XAMPP Lite (Basis Package) version 1.7.3 ###### + Apache 2.2.14 (IPV6 enabled) ... + PHP 5.3.1 (PEAR) ... Any help on that? Thanks in Advance! hello all, I have a client that wants to protect their web page with a password protected landing page. Once the password is entered the user is directed to a "disclaimer" page that they have to agree to first before going into the site. I have put both the landing page and the disclaimer page in my root directory and then the site I put in a sub directory /cms/ in the main site index.php I check for the post password and then set a $_COOKIE for the user that will expire in 1 month <?php // this goes on the very top of the index.php file in the template you are using //check if user has entered password and needs cookie set if(isset($_POST['fpass']) && !isset($_COOKIE['fpass'])) setcookielive('fpass', $_POST['fpass'], strtotime( '+1 month' )); function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) { //set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access $_COOKIE[$name] = $value; return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly); } The next thing I do is check if a user is trying to access the main site with having the COOKIE - if so I redirect the user to the landing page //check if user has not entered password if (!isset($_COOKIE['fpass']) || $_COOKIE['fpass'] == "") header('location: http://www.mypage.com'); This works fine up to this point. Now my problem is that I also need to check if a user has the month long cookie set but is trying to access the main page without viewing the disclaimer page first. I thought this would work: //check if the user has a cookie set but is on a new session if (isset($_COOKIE['fpass']) && !isset($_SESSION['fpass'])) header('location: http://www.mypage.com/disclaimer.php'); But this only throws the user into a loop of "disclaimer" -> "landing page" -> "disclaimer" etc. They can never get into the main site. How do I check for the cookie and whether the user has visited the disclaimer page - but then allow the user to continue once they go to the disclaimer page? NB: the $_SESSION is not set until the main site. I have a web application in which there are two php files index.php and include.php . include.php is loaded to a DIV tag inside index.php on click of button using Jquery . Both these php files share a common varible through cookie which is used to keep track of the data retrived by include.php . This variable will be updated each time include.php retrives data . These php code work fine Mozilla and chrome but not in IE . When i checked the cookie value it is same through out without setting . Please help . Thanks in advance , Rahul I have a very odd cookie problem that's hard to explain so please bare with me... The first piece of code found below is the login process, where the login is checked and the cookie is created or not, the second piece of code below is a library which is called to display the login menu and get the connection to the database. The problem I'm having is I cant put these 2 files in the same folder. The cookie gets created if i put the process login into a directory and the library into a sub directory called inc ... then i "include("inc/library.php");" in the login process. I then point the form for the login to http://www.alcaeos.com/blog/loginProcess.php... If I do these 2 things then the cookie is created but if I place both files in the inc folder (The code below is the example of when both files are IN the inc folder) then the cookie does not get created. the login system still works and tells the user if they successfully logged in or not, it just wont create the cookie... It's an odd problem I think. Has anybody got any ideas... Thanks Code: [Select] <?php include("library.php"); connectToDatabase(); $username = $_GET['username']; $password = $_GET['password']; $sql = "SELECT * FROM theUsers WHERE user = '$username' AND pass = '$password';"; $result = mysql_query($sql) or die(mysql_error()); if ($obj = mysql_fetch_object($result)) { $expire=time()+60*60*24*30; setcookie("shopusername",$username,$expire); echo "<A HREF='http://www.alcaeos.com/blog/test.php'>You are logged in</A>"; } else { loginScreen(); echo "You are NOT Logged In"; } $db->close(); ?> Code: [Select] <?php function loginScreen() { $output = <<<LOGIN <FORM method ="GET" action="http://www.alcaeos.com/blog/loginProcess.php"> <table> <tr> <td>Username: </td> <td><INPUT TYPE = "text" NAME = "username"></td> </tr> <tr> <td>Password: </td> <td><INPUT TYPE = "password" NAME = "password"></td> </tr> </table> <INPUT TYPE="submit"> </FORM> LOGIN; echo $output; } function connectToDatabase() { $dbhost = 'mysql*******'; $dbuser = 'kem*******'; $dbpass = 'ya****'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql'); $dbname = 'ke********'; mysql_select_db($dbname); } I'm writing a cookie using VB in an ASPX file: Code: [Select] username = "myname" If Request.Cookies("username") Is Nothing Then Response.Cookies.Set(New HttpCookie("username", username)) Response.Write("newcookie <br />") Else Response.Cookies.Set(Request.Cookies("username")) Response.Write("not nothing <br />") End If Response.Cookies("username").Expires = DateTime.Now.AddYears(1) and I can read it in PHP: Code: [Select] if (isset($_COOKIE['username'])) { $username = $_COOKIE['username']; } But when I kill it with PHP ... Code: [Select] if (isset($_COOKIE['username'])) { setcookie ("username", NULL, time()-3600*24*300 ); //300 days unset($_COOKIE["username"]); } ... the VB in the ASPX file still sees it and thinks it's an empty string, since it returns: "not nothing" It would seem that the cookie is still alive somewhere, no? And how do I kill it completely, so that the VB writes a new cookie with the same name? Hello, I am having trouble setting a cookie with a future expiration. I am using PHP Version 5.1.6. Here is my code: $expire = time() + 60*60*24*30; // 30 days setcookie("TestCookie",$value, $expire); The cookie gets set, however, the cookie is not persistent and expires when I close my browser. This should not be the case but should expire in 30 days. The time() is correct on the server. Here is the raw http headers: Status: HTTP/1.1 200 OK Date: Sat, 26 Mar 2011 15:12:27 GMT Server: Apache/2.2.3 (CentOS) X-Powered-By: PHP/5.1.6 Set-Cookie: TestCookie=my+cookie+value; expires=Mon, 25-Apr-2011 15:12:27 GMT Content-Length: 126 Connection: close Content-Type: text/html; charset=UTF-8 However, when I open Firefox or Chrome they both say that the cookie will expire when I close the browser. I know that my browser is accepting cookies properly because I see other cookies from other websites in the cookie list that expire with future dates. I've tried setting a cookie in the future with javascript and it works fine, like the following: $jsExpire = date("D, j M Y H:i:s e", $expire); echo " <script> <!--// document.cookie = 'jscookie=testcookie; expires=$jsExpire; path=/' //--></script> "; However, when still trying to set the cookie (before headers are sent which is how php operates), php fails to set the cookie properly. Is there any kind of setting in php ini that could effect cookie expiration dates? Obviously it's not a browser problem since I can set cookies correctly with javascript but not php. I even tried sending cookie with header() like this and it doesn't set in the futu header("Set-Cookie: TestCookie=my+cookie+value; expires=Mon, 25-Apr-2011 17:26:45 GMT; path=/; domain=.mydomain.com"); Any help appreciated. I'm trying to submit to my site using this script that I made: <?php session_start(); $title = "<title>CS</title>"; $url = "http://cheatskape.com/wtag/sendchat.php"; $token = md5(uniqid(rand(), true)); $_SESSION['token'] = $token; $ch = curl_init(); //Initalize a new cURL session $name = "PROBLEM"; $msg = "LOL"; $postfields = "token=".$token."&name=".$name."&url=&message=".$msg.""; echo $title; //set the title of the window curl_setopt($ch, CURLOPT_POST, 1); //set the type, curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); //and what fields to use curl_setopt($ch, CURLOPT_URL, $url);//Set the URL to use curl_exec($ch); //execute it echo "<br /><br /><br />"; print_r(curl_getinfo($ch)); //Print info of the cURL execution curl_close($ch); //Close our current cURL session ?> However, it refuses to post.. What am I doing wrong? This is my first time using cURL the curl info shows me this: Quote Array ( [url] => http://cheatskape.com/wtag/sendchat.php [content_type] => text/xml; charset=UTF-8 [http_code] => 200 [header_size] => 439 [request_size] => 208 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.39 [namelookup_time] => 0 [connect_time] => 0.188 [pretransfer_time] => 0.188 [size_upload] => 68 [size_download] => 2039 [speed_download] => 5228 [speed_upload] => 174 [download_content_length] => 2039 [upload_content_length] => 0 [starttransfer_time] => 0.39 [redirect_time] => 0 [certinfo] => Array ( ) ) This works fine on localhost, but the same code just won't update my live website cookie. Here's the code: index.php Code: [Select] $lg->updateCookies($username, $hashSalt[0]); updateCookies function: Code: [Select] $site = '.ciadacapa.com.br'; // --------------------------------------------------- // Updates the cookies // --------------------------------------------------- function updateCookies($username, $hash){ setcookie('ciadacapaUser', '', time()-3600, '/', $this->site); setcookie('ciadacapaHash', '', time()-3600, '/', $this->site); setcookie('ciadacapaUser', $username, time()+3600*24*7, '/', $this->site); setcookie('ciadacapaHash', $hash, time()+3600*24*7, '/', $this->site); return true; } Although the class is receiving the correct values, the cookie just retains the old value it had and never updates. Any ideas on this? Thanks in advance! Hello, hello i need use curl with proxy. but i get "undefined variable offset 1" error . here is the standart code i use. please help me about it thanks curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_REFERER, $referer); curl_setopt($ch, CURLOPT_USERAGENT, $agent); |