PHP - Extract 2 Variables From A Text File
For example:
I am using this code: Code: [Select] $myFile = "newuser.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 5); fclose($fh); echo $theData; and it displays: Code: [Select] Bob 2 Which I am reading from my newuser.txt file! Which corresponds to the username bob, and he has the ID of 2. Now I want to make that linkable like this: Code: [Select] <a href=.?act=Profile&id=$IDFROMTEXTFILE(2)>$NAMEFROMTEXTFILE(BOB)</a> this is possible? If so, Thanks! Similar TutorialsHello. I have one programming problem. I have this log, from witch i have to read specific area of text: webtopay.log OK 123.456.7.89 [2012-03-15 09:09:59 -0400] v1.5: MIKRO to:"1398", from:"865458961", id:"13525948", sms:"MCLADM thing" So i need the script to extract word "thing" from that log. Also that script has to check if there is new entries in the log, and extract text from the last one. (Explaining in other words, that script should extract word AFTER MCLADM. Every time its a different word) p.s. I need that script to be integrated here (this has to send command to server "/manuadd (text from log)" : Code: [Select] <?php try{ $HOST = "178.16.35.196"; //the ip of the bukkit server $password = "MCLietuva"; //Can't touch this: $sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("error: could not create socket\n"); $succ = socket_connect($sock, $HOST, 4445) or die("error: could not connect to host\n"); //Authentification socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1) or die("error: failed to write to socket\n"); //Begin custom code here. socket_write($sock, $command = "/Command/ExecuteConsoleCommandAndReturn-SimpleBroadCast:broadcast lol;", strlen($command) + 1) //Writing text/command we want to send to the server or die("error: failed to write to socket\n"); sleep(2); // This is example code and here has to be that script i want to make. //while(($returnedString = socket_read($sock,50000))!= ""){ $returnedString = socket_read($sock,50000,PHP_NORMAL_READ); print($returnedString) //} print("End of script"); socket_close($sock); }catch(Exception $e){ echo $e->getMessage(); } ?> I hope i made things clear and you will help me Thanks It's been a while since I've dealt with text files and currently I am unable to write the contents of a variable to a text file, only the literal is being written. Should I be de-referencing or is this even possible? Also the problem is compounded by the fact that i also want to write the contents of a class display function into the text file. Is there a way to use extract to make session variables? If so how would you go about doing it? hello, I want to extract a youtube video variable from users comments, i make a simple function but it works just for one url, if they posted more urls in the same comment, it will return just the first video. this is what i've done before now: Code: [Select] function get_youtube ($youtube){ $findme = 'youtube.com/watch?v='; $pos = strpos($youtube, $findme); if ($pos !== false) { parse_str( parse_url( $youtube, PHP_URL_QUERY )); echo $v; } } How can I make to extract all the $v from a comment with more url? thanks Hi, how do I extract just file extension? eg: $file="hello.xml"; $fileExt=??? print $fileExt; Any help much appreciated! Hi guys, I'm using this upload/extract zip script. I wonder if I can modify the script to link the file after it is unzip. Now it just unzip and show the content, I want to give the link to that content. Please let me know if this even possible with the code below. <form enctype="multipart/form-data" action="index.php" method="POST"> Upload a Zip Archive (*.zip): <input name="zip" type="file" /><input type="submit" value="Upload" /> </form> <?php /* UnZip on Server - using PHP by 3scriptz.com */ //check if file is uploaded if(isset($_FILES['zip'])){ require_once('pclzip.lib.php'); //include class $upload_dir = 'uploads'; //your upload directory NOTE: CHMODD 0777 $filename = $_FILES['zip']['name']; //the filename //move file if(move_uploaded_file($_FILES['zip']['tmp_name'], $upload_dir.'/'.$filename)) echo "Uploaded ". $filename . " - ". $_FILES['zip']['size'] . " bytes<br />"; else die("<font color='red'>Error : Unable to upload file</font><br />"); $zip_dir = basename($filename, ".zip"); //get filename without extension fpr directory creation //create directory in $upload_dir and chmodd directory if(!@mkdir($upload_dir.'/'.$zip_dir, 0777)) die("<font color='red'>Error : Unable to create directory</font><br />"); $archive = new PclZip($upload_dir.'/'.$filename); if ($archive->extract(PCLZIP_OPT_PATH, $upload_dir.'/'.$zip_dir) == 0) die("<font color='red'>Error : Unable to unzip archive</font>"); //show what was just extracted $list = $archive->listContent(); echo "<br /><b>Files in Archive</b><br />"; for ($i=0; $i<sizeof($list); $i++) { if(!$list[$i]['folder']) $bytes = " - ".$list[$i]['size']." bytes"; else $bytes = ""; echo "".$list[$i]['filename']."$bytes<br />"; } unlink($upload_dir.'/'.$filename); //delete uploaded file } ?> Thanks 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 Hi all, Does anyone know of a way of extracting/reading images from an excel file using PHP? This seems great (http://phpexcel.codeplex.com/) but I can't see a way of reading images from excel files. Any help would be greatly appreciated! Thanks Hello, Hi All, Bit of a strange one but i would like to be able to supply a URL to a page. This page will always contain an image and the copyright that goes with it for example http://www.geograph.org.uk/photo/693325 The copyright lies undearneath I would like to get some php code that would automatically grab the image and copy this to a directory on mt site and also take the creative commons copyright notice as a string ( which i will then display along side the image when i add it to my site) How can i do this through php I know that the word "copyright" only ever appears once on the page ( as part of the bit im trying to grab) so can i use this somehow to grab the whole string? Basically im being lazy and would like to automate the process of grabbing the image and copywrite without having to download it to my computer first and reload to my server ( as i will be doing this quite a lot) Any ideas much appreciated Thanks Hey folks, I am trying to create a small script that will retrieve content from a site, strip it of everything but human readable words, then remove numbers, single letters, and words that I specify. I have the following code which is live on http://salesleadhq.com/tools/crawler/meta.php?url=http://www.cooking.com. My problem is that it is not removing all of the the words I specify, only some... ?? I think i would rather an external word list as well... if anyone can assist me with that. Thank you! Code: [Select] <?php $url = (isset($_GET['url']) ?$_GET['url'] : 0); $str = file_get_contents($url); ####################################################################3 function get_url_contents($url){ $crl = curl_init(); $timeout = 5; curl_setopt ($crl, CURLOPT_URL,$url); curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); $ret = curl_exec($crl); curl_close($crl); return $ret; } #--------------------------------------Strip html tag---------------------------------------------------- function StripHtmlTags( $text ) { // PHP's strip_tags() function will remove tags, but it // doesn't remove scripts, styles, and other unwanted // invisible text between tags. Also, as a prelude to // tokenizing the text, we need to insure that when // block-level tags (such as <p> or <div>) are removed, // neighboring words aren't joined. $text = preg_replace( array( // Remove invisible content '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<object[^>]*?.*?</object>@siu', '@<embed[^>]*?.*?</embed>@siu', '@<applet[^>]*?.*?</applet>@siu', '@<noframes[^>]*?.*?</noframes>@siu', '@<noscript[^>]*?.*?</noscript>@siu', '@<noembed[^>]*?.*?</noembed>@siu', // Add line breaks before & after blocks '@<((br)|(hr))@iu', '@</?((address)|(blockquote)|(center)|(del))@iu', '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', '@</?((table)|(th)|(td)|(caption))@iu', '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', '@</?((frameset)|(frame)|(iframe))@iu', ), array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",),$text ); // Remove all remaining tags and comments and return. return strtolower( $text ); } function RemoveComments( & $string ) { $string = preg_replace("%(#|;|(//)).*%","",$string); $string = preg_replace("%/\*(?:(?!\*/).)*\*/%s","",$string); // google for negative lookahead return $string; } $html = StripHtmlTags($str); ###Remove number in html################ $html = preg_replace("/[0-9]/", " ", $html); #replace by ' ' $html = str_replace(" ", " ", $html); ######remove any words################ $remove_word = array("amp","carry","serious","for","re","looking","accessories","you","used","wright","none","selection","come","second","you","new","a","able","about","across","after","all","almost","also","am","among","an","and","any","are","as","at","be","because","been","but","by","can","cannot","could","dear","did","do","does","either","else","ever","every","for","from","get","got","had","has","have","he","her","hers","him","his","how","however","i","if","in","into","is","it","its","just","least","let","like","likely","may","me","might","most","must","my","neither","no","nor","not","of","off","often","on","only","or","other","our","own","rather","said","say","says","she","should","since","so","some","than","that","the","their","them","then","there","these","they","this","tis","to","too","twas","us","wants","was","we","were","what","when","where","which","while","who","whom","why","will","with","would","yet","you","your"); foreach($remove_word as $word) { $html = preg_replace("/\s". $word ."\s/", " ", $html); } ######remove space $html = preg_replace ('/<[^>]*>/', '', $html); $html = preg_replace('/\s\s+/', ', ', $html); $html = preg_replace('/[\s\W]+/',', ',$html); // Strip off spaces and non-alpha-numeric #remove white space, Keep : . ( ) : & //$html = preg_replace('/\s+/', ', ', $html); ###process######################################################################### $array_loop = explode(",", $html); $array_loop1 = $array_loop; $arr_tem = array(); foreach($array_loop as $key=>$val) { if(in_array($val, $array_loop1)) { if(!$arr_tem[$val]) $arr_tem[$val] = 0; $arr_tem[$val] += 1; if ( ($k = array_search($val, $array_loop1) ) !== false ) unset($array_loop1[$k]); } } arsort($arr_tem); ###echo top 20 words############################################################ echo "<h3>Top 20 words used most</h3>"; $i = 1; foreach($arr_tem as $key=>$val) { if($i<=20) { echo $i.": ".$key." (".$val." words)<br />"; $i++; }else break; } echo "<hr />"; ###print array##################################################################### echo (implode(", ", array_keys($arr_tem))); ?> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=321546.0 $text = "wow {one|two|three}fsasfa happy ness"; preg_match('/\b{*+}\b/i', $text, $matches); print_r($matches); Basically, $matches will contain "one|two|three" - but all I got is an array with "}" This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=359179.0 Hi, How do I open all HTML file contained in a folder, then search for the title of the page, and save the title in the database? Also, is it possible to do this using functions? Cheers. So I have been working on my website for a while which all is php&mysql based, now working on the social networking part building in similar functions like Facebook has. I encountered a difficulty with getting information back from a link. I've checked several sources how it is possible, with title 'Facebook Like URL data Extract Using jQuery PHP and Ajax' was the most popular answer, I get the scripts but all of these scripts work with html links only. My site all with php extensions and copy&paste my site links into these demos do not return anything . I checked the code and all of them using file_get_contents(), parsing through the html file so if i pass 'filename.php' it returns nothing supposing that php has not processed yet and the function gets the content of the php script with no data of course. So my question is that how it is possible to extract data from a link with php extension (on Facebook it works) or how to get php file executed for file_get_contents() to get back the html?
here is the link with code&demo iamusing: http://www.sanwebe.c...-php-and-jquery
thanks in advance.
Hi all I am having some issues basically Code: [Select] $sftp->put("server.properties", "allow-nether=".$nether." level-name=".$lname.""); is not printing the variables. $sftp is part of the phpseclib and the fuction is in the same format as fwrite(), I have tried and failed using fwrite as well! I can echo out the 1st variable correctly, but as soon as I add the second I just get Code: [Select] allow-nether= level-name= The variables $nether and $lname exist and I have echo'd them to check. I guess this is a formatting problem, just cant work it out! So say I have a file with the contents.. Code: [Select] ; this is a comment var2 : variable ; another comment var3 : file.txt how would I be able to do <?php echo $var2; ?> That would echo "variable" and <?php $file = file($var3); ?> So its reading the file to get the variable from the text file and if the line starts with ";" its disregarded.. Thanks Right, so I've made a very simple web app that allows.... 1.) People to register (adding them to the MySQL database) 2.) Login (providing they're in the database) I've gotten it all working, but I'm stuck at the last hurdle. If someone logs in using the correct username and password, it takes them to login_success.php. Here I query the database and use "SELECT * FROM Users WHERE Username = '$name'" I would have thought, that it would have returned that user's entry in the database. But instead I just get a blank page. Am I right in thinking that's because the contents of the $name variable aren't passed from log.php to login_success.php If so, how do I fix it? ---------------------------------------------------------------------------------------------------- LOGIN.PHP Code: [Select] <?php include_once "Common/header.php"; session_name("MyLogin"); $page = (isset($_GET['login']) ? strtolower($_GET['login']) : NULL); if($page == "failed"){ print $_GET['cause']; } ?> <div id="main"> <br />   <br />  <br /> <h2>Sign In</h2>   <form name="form1" method="post" action="log.php?action=login"> <b>Username:</b>  <input type="text" name="uname"/><br />  <br /> <b>Password:</b>                 <input type="password" name="pword" /><br />  <br /> <input type="submit" value="submit" /> </form> <?php include_once "Common/footer.php"; ?> LOG.PHP Code: [Select] <?php session_name("MyLogin"); session_start(); if($_GET['action'] == "login") { $conn = mysql_connect("localhost", "root", ""); $db = mysql_select_db("test"); $name = ($_POST['uname']); $word = ($_POST['pword']); $sql = "SELECT * FROM Users WHERE Username='$name' and Password='$word'"; $q_user = mysql_query($sql) or die(mysql_error() . ' <br /> in ' . $sql); if(mysql_num_rows($q_user) == 1){ $_SESSION['uname'] = $_POST['uname']; header("Location: login_success.php"); exit; } else{ header("Location: login.php?login=failed&cause=".urlencode('Invalid Username or Password')); exit; } } else{ header("Location: login.php?login=failed&cause=".urlencode('Invalid User')); exit; } if(session_is_registered("name") == false) { header("Location: login.php"); } ?> LOGIN_SUCCESS.PHP Code: [Select] <?php include_once "Common/header.php"; $connect=mysql_connect("localhost", "root", "")or die ("Could not connect to database"); $data = mysql_query("SELECT * FROM Users WHERE Username ='$name'") or die(mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>First Name:</th> <td>".$info['First_Name'] . "</td> "; Print "<th>Last:</th> <td>".$info['Last_Name'] . " </td></tr>"; } Print "</table>"; ?> Login Successful <?php include_once "Common/footer.php"; ?> Hi, I am trying to create a login system in PHP, but I am not the greatest at PHP so I am using a source code which I found online as I found it to be more secure as it uses things like salted passwords. Anyway I am trying to add more fields to the register system so it adds them to the mysql, the source has a way to do this with arrays, but it is quite complicated so I am just using variables from the original file. There are 2 files: register.php and class.loginsys.php which contains all the functions. At first the query syntax was incorrect so I decided to use the variables created in register.php in the class.loginsys, but now it's giving me an out of memory error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 28672 bytes) in C:\xampp\htdocs\ls\class.loginsys.php on line 34 Which I am unsure of how to fix. I have tried using different variable names, checking the line, checking the whole register.php file for anything rogue. Here is the code: Top part of register.php <?php include "config.php"; ?>Config.php: <?php require "class.loginsys.php"; $LS=new LoginSystem(); ?>Then actual register part from register.php: <?php if( isset($_POST['submit']) ){ $firstname2 = $_POST['firstname']; $lastname2 = $_POST['lastname']; $user2 = $_POST['username']; $sex2 = $_POST['sex']; $country2 = $_POST['strCountryChoice']; $email2 = $_POST['email']; $pass2 = $_POST['pass']; $pass3 = $_POST['pass2']; $birthdate2 = $_POST['birthdate']; $created2 = date("Y-m-d H:i:s"); //need to add a lot more validation functions.. AKA Check if email exists and username. Password > 5 chars if( $user2=="" || $email2=="" || $pass2=='' || $pass3=='' || $firstname2=='' || $lastname2=='' || $sex2=='' || $country2=='' || $birthdate2=='' ){ echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields."; exit; } if( !$LS->validEmail($email2) ){ echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid"; exit; } if( !ctype_alnum($user2) ){ echo "Invalid Username", "The Username is not valid. Only ALPHANUMERIC characters are allowed and shouldn't exceed 10 characters."; exit; } if($pass2 != $pass3){ echo "Passwords Don't Match","The Passwords you entered didn't match"; exit; } $createAccount2 = $LS->register($user2, $pass2, array( "email" => $email2, "name" => $firstname2, "lastname" => $lastname2, "gender" => $sex2, "country" => $country2, "DOB" => $birthdate2, "created" => date("Y-m-d H:i:s") // Just for testing ) ); //$createAccount = $LS->register($firstname,$lastname,$user,$sex,$country,$email,$pass,$birthdate,$created); if($createAccount2 === "exists"){ echo "User Exists."; }elseif($createAccount2 === true){ echo "Success. Created account."; } } ?>And the function from the class: /* A function to register a user with passing the username, password and optionally any other additional fields. */ public function register( $id, $password, $other = array() ){ if( $this->userExists($id) && (isset($other['email']) && $this->userExists($other['email'])) ){ return "exists"; }else{ $randomSalt = $this->rand_string(20); $saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}"); if( count($other) == 0 ){ /* If there is no other fields mentioned, make the default query */ //old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)"); //new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)"); $sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)"); }else{ /* if there are other fields to add value to, make the query and bind values according to it */ //old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)"); //new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)"); $keys = array_keys($other); $columns = implode(",", $keys); $colVals = implode(",:", $keys); //l= $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)"); //INSERT INTO MyGuests (firstname, lastname, email)cLUES ('John', 'Doe', 'john@example.com') $sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (username,email,password,password_salt,name,lastname,created,gender,country,DOB) VALUES ('$username2','$email2','$pass2','$saltedPass','$firstname2','$lastname2','$created2','$gender2','$country2','$birthdate2')"); print($sql); foreach($other as $key => $value){ $value = htmlspecialchars($value); $sql->bindValue(":$key", $value); } } /* Bind the default values */ $sql->bindValue(":username", $id); $sql->bindValue(":password", $saltedPass); $sql->bindValue(":passwordSalt", $randomSalt); $sql->execute(); return true; } }Thanks for your help. I am doing this because for a hobby I am trying to create a browser based game in which I use this login system to login the user to a main page then code all of the other pages myself. I have posted on stackoverflow and someone on their suggested that I should use a framework. If this is the case, can someone point me in the right direction? Thanks again, if you need any info ask. |