PHP - Variables Inside A File...
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 Similar TutorialsHello. Trying to learn MVC better by creating my own little framework to understand how it works. Things were going OK til now. I have a base class: <?php /** * Base class most classes will extend from. * Simply put, this class just has methods that * most, if not all, classes will need. */ class Application { public function includer($path) { if (is_readable($path) == true) { include_once($path); } else { die("404 not found =["); } } } ?> So the above method 'includer' just sees if a file exists/is readable and if so, include it. Here's where I am using said method. class Index extends Application { function __construct($method = 'view') { // load the index model include(ROOT . '/app/models/model.index.php'); // Invoke requested method. $this->$method(); } public function view() { $name = 'Smith'; $this->includer(ROOT . '/app/views/view.index.php'); # Problem here, i think } } view.index.php just contains <?php echo $name; ?> All that is called from the index page, with this line of code Application::includer($controller_path); Now, in line $this->includer(ROOT . '/app/views/view.index.php'); # Problem here, i think If i get rid of $this->includer, the script will work and say 'Smith'. If i have $this->includer(...) or parent::includer(...), it doesn't work. why? I am trying to pass a variable from inside of a function in a file that is included eg include.php Code: [Select] <? function noms(){ $foobar = "apples"; } ?> main.php Code: [Select] <? include("include.php"); noms(); echo "these ". $foobar. " are most delicious... OM NOM NOM"; ?> I am essentially using a include file for a mysql connection and based on the connection outcome i am either setting a value to true or false. It prints "Connected succesfully" and what not just fine, but, after that it wont pass on the variables data. I know its the function because, it passes the data if i put the variable before the function... i just dont get it.. any help would be great. Thanks. Ansel I have the following loop in which I receive Parse error: $letters = array ("A", "B", "C", "D","E", "F", "G", "H","I", "J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "Æ", "Ø", "Å"); for ($i = 1; $i < 29; $i++) { if ($_POST['$letters['$i']']){ echo "You have selected the following products:" . "<br>" . $_POST['$letters['$i']]; } } or is it possible to write something like that: for ($i = 1; $i < 300; $i++) { if ($_POST['$i']){ echo "You have selected the following products:" . "<br>" . $_POST['$i']; } } Please, help me. I need to use array and variables inside _POST[]. <td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. I have the array defined and print_r (outside the function is show what I need...) However, I need to somewhay pass those three arguments - name, price, shipping (keys & values) into the "all_products" function and assign (inside the function) each element to a variable {name, price, shipping}. Code: [Select] function all_products($key,$value) { # This is where I'm lost - I know the values are passed to the function but how to I assign them to below variable? echo "$name"; echo "$price"; echo "$shipping"; // Products array defined to send values into "all_products" function & loop to display item name & individual pricing (using WHILE LOOP) $products = array('Product1' => array ( 'name' => 'item one', 'price' => '30.00', 'shipping' => '0.00'), 'Product2' => array ( 'item two', 'price' => '19.50', 'shipping' => '0.10'), 'Product3' => array ( 'item three', 'price' => '21.99', 'shipping' => '0.10') ); while (list($keys, $values) = each($products)) { while (list($k, $v) = each($values)) echo "Checking Looped Data Outside Function: <strong>$k: </strong> $v<br/>"; # echo "<pre>"; # print_r($value); # echo "</pre>"; # Trying to send array elements into "all_products" function & echo (name, price, shipping) keys and values inside that function all_products($k,$v); } Hello all, I have a 14 column csv that I load into an array, retrieving only the required fields, load the array into columns and perform a sort: Code: [Select] foreach ($array as $key => $row) { $firstname[$key] = $row["firstn"]; $lastname[$key] = $row["lastn"]; $address1[$key] = $row["addr1"]; $address2[$key] = $row["addr2"]; $address3[$key] = $row["addr3"]; $city[$key] = $row["cit"]; $stateprov[$key] = $row["state"]; $country[$key] = $row["cntry"]; $membernumber[$key] = $row["num"];} array_multisort($membernumber,$lastname,$firstname,$address1,$address2,$address3,$city,$stateprov,$country,$array);When I pass say the first three letters of a last name ($find = "smi"), all records matching the search criteria are returned: Code: [Select] foreach ($array as $key => $row) { if (strncasecmp($find, $lastname[$key], strlen($find)) == 0) { echo "<tr><td>" . $firstname[$key] . "</td>"; echo "<td>" . $lastname[$key] . "</td>"; echo "<td>" . $address1[$key] . "</td>"; echo "<td>" . $address2[$key] . "</td>"; echo "<td>" . $address3[$key] . "</td>"; echo "<td>" . $city[$key] . "</td>"; echo "<td>" . $stateprov[$key] . "</td>"; echo "<td>" . $country[$key] . "</td>"; echo "<td>" . $membernumber[$key] . "</td></tr>" . chr(13); }}}So far so good. However, I'd like to put the search part into a function so I can call it a number of times without having to reload the entire csv: Code: [Select] function FindMember() { foreach ($array as $key => $row) { if (strncasecmp($find, $membernumber[$key], strlen($find)) == 0) { echo "<tr><td>" . $firstname[$key] . "</td>"; echo "<td>" . $lastname[$key] . "</td>"; echo "<td>" . $address1[$key] . "</td>"; echo "<td>" . $address2[$key] . "</td>"; echo "<td>" . $address3[$key] . "</td>"; echo "<td>" . $city[$key] . "</td>"; echo "<td>" . $stateprov[$key] . "</td>"; echo "<td>" . $country[$key] . "</td>"; echo "<td align='right'>" . $membernumber[$key] . "</td></tr>" . chr(13); }}}}The search criteria would come from a second txt file with every line containing 2 numbers, separated by a comma: Code: [Select] foreach ($lines as $member => $numbers) { $exploded = explode(",", $numbers); $find = $exploded[1]; FindMember();here $exploded[1] corresponds to $membernumber[$key], so this is where I would call the function, but this is where I run into trouble, nothing gets returned. Does this have something to do with the scope of variables inside a user-defined function? I'd appreciate it if someone could point me in the right direction. TIA This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=359179.0 Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error. I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables. $dummyObject = new CommonLibrary; unset($dummyObject); echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered. Anyone recommend any better ways of doing this? Thanks in advance! I have a php file that generates a string that I need to use in a .js (javascript)file. Being that php developers sometimes using javascript with php, Im hoping someone can help me with this, cause i dont know any javascript. Code: [Select] //This is the varible inside the .js file var suggestionText = "I need to be able to include my string generated by the php file here..."; im trying to create a table for a site admin. bsicaly all he has to do is fill out a form and the values of the form are turned into the table name. im using a .sql file as a template but to create the table i need the php genarated table name to be inserted into the .sql file. <?php include("config.php"); $con details $tbl_name = "static_name_for_now"; if (mysql_query("seat_plan.sql")) { echo "success"; } else{ echo "fail"; } ?> sql file snippet INSERT INTO `<?php $tbl_name ?>` VALUES('A', 1, 0, 'Y'); also tried INSERT INTO `<?php echo $tbl_name ?>` VALUES('A', 1, 0, 'Y'); thanks hi i have this form that runs with ASP. [this is a must since i didn't create that form] and must run in the wordpress header.php... is this even possible? 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 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! 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. So here is what I have going. #1 - My weather station software processes a file and enters variables and then uploads it as a php file. #2 - Currently the station also just uploads every file to the site and enters the data in the html, but I would rather have it only upload this one file and the other pages grab data from it and print it out. I have a few php scrips in there to preform certain functions (if temp <= 32 it echos that data in blue and so on) but would rather make most of it php so I have less files being uploaded every 5 minutes. This is what the station sends to the web, but I have no idea how to get the other pages to read it and input the variables from it. I am working PHP project on localhost using wamp, for debug process we using error_log() function, every time error_log() stored details of the error in wamp/logs, how can I view my error in the same project folder like wamp/www/goodgoal/ eg: wamp/www/goodgoal/logs/error_log.log Note : Pls recommend PHP Quick Debug Tricks Edited July 5, 2019 by aveevaFor 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! So I have a text file "name.txt" in the text file I have ids and auth keys set up like this 1234564 abcdfhu 3123900 sdkoao etc How could I make it to where the ids are $ids and the auth keys are $auth_keys? I've tried using foreach() but I cant get it 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.
I have a php file with a bunch of variables declared. I now need a function to put data on a separate page that pulls variables from the required page. <?php function getplayer($position) { // start function //$new_position = "$" . $position; $new_position = $position; $file = "their.php"; require "$file"; //echo $qb1; this displays the name John Doe...as $qb1 is declared in the required file $db_select_their = "bschultz_their"; $servername = "localhost"; $username = "user"; $password = "pass"; $dbname = "db_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM (select number as position_number, name as position_name, pronunciation as position_pronunciation, pos as position_pos, height as position_height, weight as position_weight, year as position_year, city as position_city, state as position_state, notes as position_notes FROM $db_select_their WHERE name = '$new_position') as position"; //$sql = "SELECT * FROM bschultz_their WHERE name = $new_position"; echo $sql; //exit; /* this displays this text... SELECT * FROM (select number as position_number, name as position_name, pronunciation as position_pronunciation, pos as position_pos, height as position_height, weight as position_weight, year as position_year, city as position_city, state as position_state, notes as position_notes FROM bschultz_their WHERE name = '') as position The name is empty */ $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "#: " . $position_number . " - Name: " . $position_name . ""; } } else { echo "0 results"; } } // end function getplayer("${$qb1}"); $conn->close(); ?>Edited September 8, 2019 by bschultz |