PHP - Curl With Session/cookie
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.. Similar TutorialsI am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated 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. 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. Hi,
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,
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 Hi All, I have a secure website which always checks the cookies is not expired and the session id is set. When someone doesn't browse for the period of the cookie it will expire however the session id stays valid until he logout. A lot of people don't logout so the pages will still be accessable for them or others who use their pc. Is there a way to destroy the session id when the cookies expires? Marco The default PHP Session name on my webspace server is PHPSESSID. Does that mean that the session cookie will be called PHPSESSID? The reason i ask is that in a couple of places i can't use PHP to update the information in the session cookie (because PHP is parsed before the webpage loads) and so i need to use Javascript to update a cookie which i would prefer to be the session cookie used by PHP. I guess i'm asking what the name of the cookie is, how i would refer to it in Javascript (if that is even possible) so that i can update it and whether this would cause any issues with the info already stored in the session cookie by PHP. Cheers NM Hi, I'd like to know the security of assuming session variables and using them for secure membership systems. Could a malicious user not create a session, then change the session username to another user and effectively login as that user? As I see it, no. Because session data is stored on the server and only a session id is stored on the client by way of a cookie. But what if we used cookies? What is the solution to this? Because I know I could easily change ANY variables within a cookie. I guess storing cookie data via db would help. But what is the best practice solution? I see a lot of code which simply checks for a cookie with the variable 'logged_in' to true. It then manages the user by username or userid which are stored within the cookie but which can be changed with ease by a malicious user. Hi, I am just recently getting this error message:Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/XXX/chordsandguitar.com/index.php:46) in /home/jchords/chordsandguitar.com/index.php on line 48 this is no doubt related to the fact that my site has been hacked along with 1000's of others that are on dreamhost. I don't know if it's related to php file permissions some of my files may have had had their permission set for read-write when they should not have been. They have all been changed to the more restrictive 755 or 644. So here is how I am using the session_start to store some variables: Code: [Select] session_start(); if (!isset($_SESSION["count"])) { $_SESSION["count"]=0; } else $_SESSION["count"]++; if ($_SESSION["count"] == 0) { $scale_menu = 'C'; $variation_menu = 'maj'; $code_id = '1'; } else { //allows retreiving the value of the drop-downs after the Select button has been pushed // has to be skipped on the first access or overwrites starting vars. to null if (isset($_GET['s_menu'])) $scale_menu = $_GET['s_menu']; else $scale_menu = $_GET['scale_menu']; } So any ideas why I am getting this error? Thanks, Jacques 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. hey guys im using a session cookie to store a user_id, only if user has clicked to remember me on the login form...that way when autenticating it checks id in db and if matching a user it logs in automatically.
now the problem i want to just remove user_id from a session cookie. if i use the code below to delete the user_id session then it will remove all session cookies.
is there a way just to remove 1 session cookie? thank you
// create session cookie session_start(); session_set_cookie_params('3600', 'C:\Users\Ricky\Desktop\www\BiSi\private\tmp\session', 'http://127.0.0.1/', true, true); ini_set('session.gc_probability', 1); session['user_id'] = 1; //delete session cookies setcookie (session_name(), null, time() - 3600); session_regenerate_id(true);any help/advise would be greatful...cheers guys I don't know why but I'm failing hard at GoogleFu today. I can't find a tutorial on how to store a session id in a cookie and then call it on the server. session_id says it replaces the cookie it makes if you set the id via session_id, even if it's the same id...but I'm not sure if that really matters. Can anyone help point me in the right direction to a good tutorial/give me some insight on this subject? I want to store the session id in a cookie to keep a user logged in for 2 weeks or so (unless they log out of course). I did find some tutorials on how to re-route the session handlers for open/close/read/write session functions which allow me to store the session in a database. Is this what I want? Sorry for the newbie question, Thanks, Justin Hi, I am having trouble with my cURL call because when I run the exec method I loose my current login state in the session. I have tried the two options below, but they have yet to succeed. If there is anything else you want me to tell you that will help you understand my issue, please let me know. $sessionfile = fopen("sessionfile.txt", "w"); fputs($sessionfile, session_encode( ) ); fclose($sessionfile); $c->setopt(CURLOPT_COOKIEFILE, $sessionfile); $c->setopt(CURLOPT_COOKIEJAR, $sessionfile); $sessName = session_name(); $_COOKIE[$sessName] = session_id(); $_COOKIE['aud_logged_in'] = Session::isLoggedIn(); session_write_close(); $c->setopt(CURLOPT_COOKIE, $sessName."=".$_COOKIE[$sessName].";"); I am confused why I am getting the following error and was wondering if I could get a 2nd pair of eyes.. error: [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cache limiter - headers already sent (output started at /home/curren11/public_html/mysite***.com/file_monitor.php:2) in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 Here is the code: <?php session_start(); $root_path = realpath(getcwd()); $error_monitor_file = $root_path.'/file_modify.txt'; $hour = date("H"); $today = date("m-d-Y"); $myFile2 = "file_monitor.php.log"; $fh3 = fopen($myFile2, 'a'); $log_msg = "Last ran on: ".$today." at: ".$hour." \n"; fwrite($fh3, $log_msg); function scan_dir($path) { $out = array(); $files = opendir($path); while ($f = readdir($files)) { $extension = substr($f,-3); if ($f=='.' or $f=='..' or $extension=='jpg' or $extension=='JPG' or $extension=='png' or $extension=='gif' or $f=='file_monitor.php' or $f=='file_modify.txt' or $f=='file_monitor.php.log' or $f =='error_log' ) { continue; } if (is_dir($path.'/'.$f)) { $out = array_merge($out, scan_dir($path.'/'.$f)); } //if (((!is_dir($path.'/'.$f)) && ($f!='.' or $f!='..' or $extension!='jpg' or $extension!='JPG' or $extension!='png' or $extension!='gif')) else // { $out[] = $path. '/'. $f; //} } $_SESSION['all_files'] = $out; return $out; } $a = scan_dir(getcwd()); $count_array = count($_SESSION['all_files']); $loop_count=0; while($loop_count < $count_array) { // file in directory when was it last changed ? $filechange1 = date("m-d-Y-H", filemtime($_SESSION['all_files'][$loop_count])); // was it chnaged today and have I sent out an alert yet? if($filechange1 == $today."-".$hour) { $fh2 = fopen($error_monitor_file, 'a'); fwrite($fh2, "\n alert, file: ".$_SESSION['all_files'][$loop_count]." was changed today within the last hour ! \n"); fclose($fh2); } $loop_count ++; // log file? was it changed this past hour? if (file_exists($error_monitor_file)) { $filechange_log = date("m-d-Y-H", filemtime($error_monitor_file)); if ( ($loop_count == $count_array ) && ($filechange_log == $today."-".$hour ) ) { email(); } } } // function for email... function email() { require_once ('class.phpmailer.php'); $mail = new PHPMailer(); $mail->IsSMTP(); // send via SMTP $mail->Host = "localhost"; // SMTP servers $mail->SMTPAuth = true; // turn on SMTP authentication $mail->Username = "**c66@***ar.com"; // SMTP username $mail->Password = "*****"; // SMTP password $mail->From = "***@***.com"; $mail->FromName = "Colonial Cottage File Changed"; $mail->AddAddress("email@*****.com"); $mail->WordWrap = 50; // set word wrap //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment //$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); $mail->IsHTML(true); // send as HTML $mail->Subject ="Unauthorized file changed today!"; $mail->Body = "" ; $mail->AltBody = "This is the text-only body"; if(!$mail->Send()) { exit(); } } if ((file_exists($error_monitor_file)) && $hour == "00") { unlink($error_monitor_file); } fclose($fh3); exit(); ?> Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 These are my error messages, here is my code. I don't know if it is the UTF-8 code at the start, but if it is can anyone recommend a binary editor to remove this. If it isn't what is the problem? <?php session_start(); $username = $_POST['username']; $password = base64_decode($_POST['password']); $errors = array(); if($username == 'User Name' || $username == ''){ $errors[] = 'Please enter a valid username'; } if($password == 'Password' || $password == ''){ $errors[] = 'Please enter a valid password'; } $link = mysql_connect("localhost","*****","******") or die ("Could not connect!"); mysql_select_db("chef"); $query = mysql_query("SELECT * FROM `users` WHERE `username`='$username'"); $numrows = mysql_num_rows($query); if ($numrows!=0) { while($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } if ($username==$dbusername&&$password==$dbpassword) { $_SESSION['user'] = $username; while ($row = mysql_fetch_array($res)) { $type = $row['Type']; } if ($type == "0") { header("location: chefpanel.php"); }else{ header("location: restpanel.php"); } } else $errors[] = 'Username or Password Incorrect'; } else $errors[] = 'Username or Password Incorrect'; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> Im trying to access a page that uses a session hash in the url. How do I accomplish this. The url looks like: http://www.somesite.com/findagent/MapController.aspx?action=getAgentsByRadius&distance=5&filter=PL&sessionhash=%3F%01j%23%3Eo%0AH%05h%0B%3FU%0B%3F%3F%3F%7B%3F%3C&zip=91111 I guess getting the session id and urlencoding on my end wouldnt work? I would have to grab their session id and encode somehow? Hi girls and boys I am trying to set a variable if a session OR a cookie has been set, but am unsure on how to write the statement... if (isset($_SESSION['name'])||isset($_COOKIE['name'])) {$variable = $_SESSION['name']||$_COOKIE['name'];} Obviously not working there, but just need a pointer here. any help is appreciated... what would be the best way to automate/force session destroy and cookie erase i have a facebook iframe, with facebook login which gets the activation token now the user is not logged out from the login script after he logs out of facebook. any ideas how to force cookie timeout without a logout button? im playing with Code: [Select] <?php session_start(); //Global User Object Var //loggedInUser can be used globally if constructed if (isset($_SESSION['userCakeUser'])) { $obj = casttoclass('stdClass', $_SESSION['userCakeUser']); $_SESSION['userCakeUser'] = $obj; $_SESSION['start'] = time(); // taking now logged in time $_SESSION['expire'] = $_SESSION['start'] + (1 * 60) ; // ending a session in 1 minute } if(isset($_SESSION["userCakeUser"]) && is_object($_SESSION["userCakeUser"])) { $loggedInUser = $_SESSION["userCakeUser"]; } ?> |