PHP - File Get Contents With Complicated (?) Login First
i am trying to do a "file get contents" from the following website http://www.bet365.com/home/ It is necessary to input your account username and password here, and then I want to get the contents of this page http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1 I have tried a couple of scripts but just can't seem to get it to work. I have tried $context = stream_context_create(array( 'http' => array( 'header' => "Authorization: Basic " . base64_encode("$username:$password") ) )); $data = file_get_contents($url, false, $context); echo $data; with the username and password and url entered as variables. but get the message Warning: file_get_contents(http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1) [function.file-get-contents]: failed to open stream: HTTP request failed! in "myscript's address" on line 13 Maybe i don't need to visit the homepage first to log in? Any ideas please? Thank youapologies for the message being in code quotes, I wrote it in Word but then couldn't paste it, even using the special Word paste button. Hope the message comes out ok. Thank you. Similar TutorialsI have a Login page which i want to check if the user details (username, password and activation) are valid then redirect user dependent on his/her "accessLevel" (admin, member and none)
Admin will be directed to "index.php"
Member will be directed to "tasks.php"
and none will be redirected to "notActive.php"
here is my current code which half works;
<?php include ('connect.php'); if(isset($_POST['submit'])) { // Initialize a session: session_start(); // Define $username and $password $username=$_POST['username']; $password=$_POST['password']; // To protect MySQL injection $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM ecmt_members WHERE username='$username' and password='$password' AND Activation IS NULL"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $username and $password, table row must be 1 row if($count==1){ // Register $username, $password and redirect to file "index.php" $role = mysql_fetch_array($result); $_SESSION['username']= $username; $_SESSION['password']= $password; //$_SESSION['role']= $role['accessLevel']; if($role['accessLevel'] == "admin"){ $_SESSION['adminuser']=$role['accessLevel']; header("location:index.php"); exit(); } elseif($role['accessLevel'] == "member"){ $_SESSION['user']=$role['accessLevel']; header("location:tasks.php"); exit(); } else { echo "Error: Username, Password or Access Level incorrect! Go Home, you're Drunk!!!"; } } } // End of the main Submit conditional. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login Form</title> <!-- jQUERY --> <script src="//code.jquery.com/jquery-latest.js"></script> <!-- Add Main CSS --> <link rel="stylesheet" type="text/css" href="../tool/css/main.css"> <!-- Font-Awesome --> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <style> body { background: url(../tool/images/bg1.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .exactCenter { width:auto; height:auto; position: fixed; top: 50%; left: 50%; margin-top: -200px; ; } </style> </head> <body> <div class="exactCenter"> <div id="login-container"> <img src="../tool/images/bigLogo.png" /><br /> <form action="login.php" method="post" class="form"> <fieldset class="group"> <input class="input" type="text" id="username" name="username" size="25" placeholder="username"/> <img src="../tool/images/spacer.png" width="5" height="5" /> <input class="input" type="password" id="password" name="password" size="25" placeholder="password"/> <img src="../tool/images/spacer.png" width="5" height="5" /> </fieldset> <input type="hidden" name="formsubmitted" value="TRUE" /> <button type="submit" name="submit" class="btn btn-blue" ><i class="fa fa-unlock-alt"></i> Login</button> <img src="../tool/images/spacer.png" width="5" height="5" /> <a href="Register.php"><button type="button" class="btn btn-green" ><i class="fa fa-hand-o-up"></i> Register</button></a> </form> </div></div> </body> </html>When i test it with admin login credentials i get the page refresh again without error, when i login with member credentials it shows tasks.php and when i try to log in with unactivated account "acivation column is not NULL" i get a page refresh also with no error. Can someone help me make it work for each role and perhaps have some sort of error reporting depending on error. im pulling my hair out here and this is the first time i have worked with login conditions, and im VERY confused. Edited by jacko_162, 28 October 2014 - 05:12 PM. Hi all, I'm trying to scrape the contents of a page that is behind a login screen; namely: http://my.mail.ru/apps. Here's my code. It almost works, but doesn't appear to be properly logging in -- I just get a login screen on the url download. Any ideas? Thanks much. Here's my code <?php $ch=login(); $html=downloadUrl('http://my.mail.ru/apps', $ch); echo $html; function downloadUrl($Url, $ch){ curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_REFERER, "http://my.mail.ru/cgi-bin/login?noclear=1&page=http%3a%2f%2fmy.mail.ru%2fapps%2f"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); return $output; } function login(){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://my.mail.ru/cgi-bin/login?noclear=1&page=http%3a%2f%2fmy.mail.ru%2fapps%2f'); //login URL curl_setopt ($ch, CURLOPT_POST, 1); $postData=' page=http%3A%2F%2Fmy.mail.ru%2Fapps%2F &Login=username &Domain=mail.ru &Password=password'; curl_setopt ($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt ($ch, CURLOPT_MAXREDIRS, 10); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $store = curl_exec ($ch); return $ch; } ?> I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help Hello friends, if i have the following $path = "http://*site*.com"; why can't i write the following $ORGtext= file_get_contents('$path'); it works only if i write $ORGtext= file_get_contents('http://*site*.com'); but i want to put $path instead of the url at file_get_contents is it possible and if yes then how ? thank you Hello, I have a simply query that will if a simple two different things: Code: [Select] $cssyn = mysql_query("SELECT `12` FROM `12345` WHERE `abc` = '$_SESSION[number]'"); $cssy = mysql_fetch_row($cssyn); if($cssy[0] == "YES") { echo "Yes"; } else { echo "No"; } The YES or NO result is stipulated earlier on so thats not the problem. But basically before I added the if statement simply would have echoed a table with all the rows etc from another query. However I would like to give the user a choice between echoeing the results into one table or a neater two. I have separated the code for the table and the queries into two separate files but say if I use: file_get_contents then it just prints the HTML and doesnt actually populate it will the queried parts. Nor if I use something like include() then it wont echo anything, which it wouldnt unless called so what I am asking is: Is there a way to get EVERYTHING from the file if the answer is YES or the other file if NO. eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. Hi, I assigned a project where i have to import the mobile numbers from the file, but i have no idea how to proceed this. What kind of file to accept as input and how to read. Thanks Hello, I am a PHP newbie, and have been mostly playing around with PHP/MySQL in a CMS ares (i.e. building my own CMS). Now I am trying to expand my knowledge outside of the basic php commands, and a particular subject caught my attention. Getting page source code, parsing out bits from it, and displaying it. This is more of my personal goal to get it working, to learn more about some of PHP's abilities, and especially search parameter flag thingies D: http://nexrem.com/scripts/get_source/ That is my webpage i made real quick, as you can see it shows basic stuff. Code for it is: Code: [Select] <html> <head> <title>Content Site</title> </head> <body> <p>This is intro text</p> <a href="http://google.com" title="Search Engine">Google Link</a><br /> <a href="http://yahoo.com" title="">Yahoo Page</a></br > <a href="http://http://www.phpfreaks.com" title="Awesome Site">PHP Freaks Help</a><br /> Bottom of file </body> </html> Now, I have a php file called get_link.php >> http://nexrem.com/scripts/get_source/get_links.php Code: [Select] <?php $url = 'http://nexrem.com/scripts/get_source/'; $needle = 'google'; $contents = file_get_contents($url); if(strpos($contents, $needle)!== false) { echo 'found'; } else { echo 'not found'; } // The \\2 is an example of backreferencing. This tells pcre that // it must match the second set of parentheses in the regular expression // itself, which would be the ([\w]+) in this case. The extra backslash is // required because the string is in double quotes. $html = $contents; echo $contents; preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); foreach ($matches as $val) { echo "matched: " . $val[0] . "\n"; echo "part 1: " . $val[1] . "\n"; echo "part 2: " . $val[2] . "\n"; echo "part 3: " . $val[3] . "\n"; echo "part 4: " . $val[4] . "\n\n"; } ?> From what I understand, file_get_contents gets what the user sees? Or it gets the source code, and I just can't output it as such, cause my browser renders it? Question 1: Is it possible to get the html code of the page, rather than what the html renders it to be? How? Question 2: I can just Right click > view source and paste that result into a text file. I think I know how to search for a specific string, but how would I do it recursively, along the lines of: Search for text between <a href=" and " so I get the raw link Then add the results to an array. And then use foreach to output all the links from the array? Any help, hints are appreciated! Thank You! P.S. I quite frankly, got no idea what "/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/ is... Can someone refer me to a page where I can learn about those expressions? Hi All, sure this is simple but I'm still new to php/mySQL so errors are abundant! I have a simple form with one input: a browse button so the user can find a .csv file on their computer. User then clicks button, upon which I would like the file to be read and the contents put into an array, and the values to be added to the database. I do not need the file to be stored (uploaded). So far my code is not erroring, it just doesn't add the values to the db. I'm wondering if it's just that I HAVE to upload and save the file to the webserver else I can't read it? if(isset($_FILES['file_path']['tmp_name'])&& $_FILES['file_path']['tmp_name'] !=''){ $file_to_import = $_FILES['file_path']['tmp_name']; $import_data = file($file_to_import); print_r($import_data); if ($import_data !=''){ for($index = 1; $index < sizeof($import_data); $index++){ $order_data = explode(",",$import_data[$index]); tep_db_query("UPDATE orders SET act_shipping_cost = '" . $order_data[8]. "' WHERE orders_id = '". $order_data[0]."'"); echo "done it"; } }else{ echo 'error cant read file!'; } } else{ ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> etc etc etc <form id="shipping_costs_upload" name="csv_file_reader" method="post" action="shipping_cost_upload.php"> <div class="main" id="info_text"><h2>Upload Actual Shipping Costs CSV</h2><p>To upload actual shipping cost data, browse to your csv and click the Upload Data button.<br /><br /></p> <div class="date" id="file"> <strong>CSV File: </strong><input type="file" name="file_path" id="file_url" /> </div> <div class="date"><input type="submit" value="Upload Data"> </div> </form> etc etc etc Apologies if I'm being a complete dunce! is there a way to print the file as it appears. I want to print the HTML and PHP within a file rather than just the output. Example: File contains: <?php echo "Hello World"; ?> i would like to echo: <?php echo "Hello World"; ?> instead of just hello world which is what i get with file_get_contents() Hi, I have a file which contains settings for a user. Similar to wordpress except simpler like setting a default email for error messages or something. The idea is that it's used as an installation script for web-ware where someone fills in a form with their database details, my script will hard-code them into the settings file and then delete itself. I'll admit I did get the idea from wordpress. Only the way it's coded currently requires a certain combination of characters at the end and seems really messy. The script looks like this (and does work): $endpos = strpos ( $contents, '"; //replace with name//', $startpos); The settings file looks like this: $hard_name = "Smith"; //replace with name// As you can see I use the comment in the settings file, which follows what I'm actually changing, to find the end of the variable. I am sure there must be a better way of doing things but don't know what. It just seems really inefficient because if the comment is removed the script breaks. Any info and tips would be much appreciated. IceKat I'm trying to extract the contents of a zip file to a folder. I found the ZipArchive class and followed the examples to get it to work for the most part. But I want to extract the files in the folder inside the zip file but leave the folder out. So it should extract just the files to my given destination. I found this on php.net. Code: [Select] If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder). <?php $path = 'zipfile.zip' $zip = new ZipArchive; if ($zip->open($path) === true) { for($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $fileinfo = pathinfo($filename); copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']); } $zip->close(); } ?> For some reason that 'copy' line is not working for me. Obviosly I've changed the variables in the line to the correct variables. Can someone help me out. Thanks Mike I set up a Twilio number so a client could have a SMS keyword response setup... but I don't know how to get the contents of a file to be returned as the response. I am using the php functions.. I setup a system so that my client could change the responses to different keywords. Basicly it uses a webform to change the contents of a file which gets returned as a response. What I need to know is how to read in the contents of the file into this function: BTW... this works fine and will return "READ_FILE_CONTENTS_INTO_HERE" function app(){ $response = new Services_Twilio_Twiml(); $response->sms("READ_FILE_CONTENTS_INTO_HERE"); echo $response; } I tried this but it stopped the script dead: function app(){ $response = new Services_Twilio_Twiml(); $response->sms("<?php include 'file.txt'; ?>"); echo $response; } Any ideas? Thanks BTW... below is the entire php script: <?php /* Include twilio-php, the official Twilio PHP Helper Library, * which can be found at * http://www.twilio.com/docs/libraries */ include('Services/Twilio.php'); /* Controller: Match the keyword with the customized SMS reply. */ function index(){ $response = new Services_Twilio_Twiml(); $response->sms("Thank You For Contacting SweetLeafAZ.com - Reply with one of the following keywords: APP = Make Appt, CS = Current Strains, DP = Delivery Prices, SP = Current Specials."); echo $response; } function app(){ $response = new Services_Twilio_Twiml(); $response->sms("http://www.vcita.com...01f2c7d/home"); echo $response; } function cs(){ $response = new Services_Twilio_Twiml(); $response->sms("http://mobile.dudamo...sweetleafaz2"); echo $response; } function dp(){ $response = new Services_Twilio_Twiml(); $response->sms("As of Sept 26 2014, Our Delivery Rates are $2 per mile during the hours of 9am to 6pm. No deliveries will be made after 6pm."); echo $response; } function sp(){ $response = new Services_Twilio_Twiml(); $response->sms("We are currently offering FREE delivery within 10 miles for orders over $100."); echo $response; } /* Read the contents of the 'Body' field of the Request. */ $body = $_REQUEST['Body']; /* Remove formatting from $body until it is just lowercase characters without punctuation or spaces. */ $result = preg_replace("/[^A-Za-z0-9]/u", " ", $body); $result = trim($result); $result = strtolower($result); /* Router: Match the ‘Body’ field with index of keywords */ switch ($result) { case 'app’': app(); break; case 'cs': cs(); break; case 'dp': dp(); break; case 'sp': sp(); break; /* Optional: Add new routing logic above this line. */ default: index(); } So, I'm trying to get this read my text document "news.txt" and display the contents. My code: Code: [Select] div.newscontent{ padding:0px; margin-top:60px; margin-bottom:0px; margin-left:400px; margin-right:0px; position:absolute; width:457px; height:330px; text-align:center; color:#FFFFFF; } Code: [Select] <div class='newscontent'> <?PHP $filename = "news.txt"; $arr = file($filename); foreach($arr as $line){ print $line . "<br/>"; } ?> </div> This is the output I get: Code: [Select] "; } ?> Whats wrong? ok so say I have a file with .. this information in one file Code: [Select] 548402354 7e99c2c49be0ad1a95fd3b4a2f65fc941e9cf194 548402225 9e0b2788f21a317eb76159f3e0c4e4a090492f2a 548402329 1aa382935c94d73f58bdb3203686cc0124fb3443 548402596 c41655fa8f14346cbd8a656a18ecb82caa3c1f9c 548402535 558e1ee14f2423681668a168a3980304ac54bd15 548402456 48ee03332c417cab51eaec13b415fde8c0b6a641 548400202 5bf3400e3c074eb8b42a962dc7e60777d2b2848a 548400842 cc672d4785ec5b9e22db7b60e203286c840c4f37 548400682 547c8ac38243b0f9a94609177d0dd12194059aa5 548400810 54afebbb3e884fea5563c017b18dd390ff1ff034 548400581 ec7305326b5514cbf05ab4a78647ed756da9db55 548400431 b3dcaa272c759ebe4e5b00053ef390b21b23f60c and I want to take and split the contents into 6 different files.. So it would take the first 2 lines and write to filename 1.txt, then it would take the 2 lines after that and write a file named 2.txt, so on and so forth Any help is appreciated, thanks I have a base64 encoded image -> http://pastebin.com/698ES5t0
Im trying to export this as a png file.
$picture = {data on paste bin}; $picture = base64_decode($picture); file_put_contents('/home/picture.png', $Picture);Now this creates a file picture.png and i can open it in Preview/Gimp etc. However, if i upload the file to my website, the image does not render in chrome/firefox, however it does render in Safarai. It seems that there is no height/width/depth data. I'm going to be blunt, I've been working on a website for quite some time now and I never really stopped to think about the effects that an over abundant amount of queries could actually slow things down. I'm quite new to the whole PHP / MySQL thing so I am still learning. While reading through some things about optimization of queries I've learned some valuable information, such as working with Indexes, and not running unnecessary queries which the data doesn't seem to change that often. So for a few aspects of my site which don't really change in particular periods of time, I've decided to write the contents of them into a text file then retrieve and display them as normal through my site. Things that last an hour, or a day, will no longer be queries on each page load; tremendously reducing the amount of queries which my database would take. Currently I have the following code: if($database->numrows($query) > 0) { $myFile = 'testFile.txt'; if($fh = fopen($myFile, 'w')) { $i = 0; while($row = $database->fetchassoc($query)) { ++$i; $stringData = '' . $row['id'] . '--' . $row['name'] . '--' . $row['color'] . '--' . $row['bdaytest'] . '--' . $row['gmtoffset'] . "\n"; fwrite($fh, $stringData); } fclose($fh); } } Which Prints Out Quote 32--User3--0--1939-10-03--+0.0 27--User7--0--1979-10-04--+17.0 28--User65--150--1969-10-05--+17.0 30--User1--0--1959-10-06--+6.0 31--User9--0--1949-10-07--+3.0 29--User5--0--1989-10-08--+17.0 The problem stems from pulling the information from the file and exploding it. That file would be for yesterday's up to 7 days from now's birthdays. The amount of lines could change, possibly messing up the possibility of an array. I was thinking about pulling the information into an array, than exploding it from within that array, posting it to variables.. and then have it display all in a while. Am I on the right track, or is there some other alternative I can use? Only data that will always be visible on the website, will be held in these text files. Any suggestions on how I pull the information from the text file and explode it to display exactly how I need it to be displayed? Hello, I have a form that ends up creating a file. The file has one of two values in the file: specials.php specials8.php Within several of my web pages, I have an image map, and I would like one of the href values to be the value that PHP would get from the underlying file. How would I code this to make the image map function accordingly? Notice the "Daily Specials" entry within the image map. It is this href that I need to become the value from the file. The unsuccessful code that I tried is: <?php $file38a = "test/activate.txt"; $file38b = file_get_contents("$file38a"); echo "<img src=\"sample2/sidebar1.jpg\" alt=\"Collegeville Diner\" width=\"94\" height=\"330\" border=\"0\" align=\"top\" usemap=\"#Map2\" longdesc=\"http://collegevillediner.com\" />"; echo "<map name=\"Map2\" id=\"Map2\">"; echo "<area shape=\"rect\" coords=\"8,102,88,152\" href=\"about.htm\" target=\"_self\" alt=\"About the Diner\" />"; echo "<area shape=\"rect\" coords=\"7,159,90,204\" href=\"menu.htm\" target=\"_self\" alt=\"Our Menu\" />"; echo "<area shape=\"rect\" coords=\"7,214,90,262\" href=\"$file38b\" target=\"_self\" alt=\"Daily Specials\" />; <area shape=\"rect\" coords=\"0,275,86,320\" href=\"desserts.htm\" target=\"_self\" />"; echo "</map>"; ?> Seems this should be easy, but I'm not finding the solution. Functions like scandir, readdir, and glob that I've been looking at all seem to need me to actually know more about my directory path than I can ahead of time. Here's what I want to do: 1. expand a .tar file (consists of directory, subdirectories, files, and is variable) that I've uploaded to the server 2. look through that expanded directory for a subdirectory named ".pn" -- (note that all my .tar files will have this folder deep in several subdirectories that will be variable in number and have different names depending on the original .tar file) 3. copy the entire contents of the .pn folder to another folder already on my server The hosting company, no doubt, has likely blocked some of the functions I'll need as well, but if someone can point me in the right direction to start, it would be greatly appreciated. Thanks! Satre |