PHP - Using Php To Update Config File
I have a very simple password protection set-up on a page as a temporary measure until I can set something better up. The person I set it up for wants to be able change the Username and Password occasionally but wants me to set up a simple form which will overwrite the data in the config file (connection.php) instead of having to open the file himself (don't ask!).
I have has a read round to see if there is any obvious and simple solutions but none seem as simple as I had hoped. I intend to work on a system via MySQL where there can be multiple users and passwords but as time is tight at the moment I just want to get something basic and working. The nature of the 'hidden' content is not sensitive (it is just a football clubs live commentary stream that they are hoping to get people to subscribe to) so there are no issues at this moment with security. All he needs to do is choose a new Username and Password every game and email it to the subscribers. The data that he wants to update in connection.php, via a form, is Code: [Select] $username = "user"; $password = "pass"; The code in the actual page with the log-in is Code: [Select] <?php require_once('connection.php'); if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) { ?> <h1 style="color: #FFF">Login</h1> <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <p class="white_text"><label for="txtUsername">Username:</span></label> <br /> <input type="text" title="Enter your Username" name="txtUsername" /></p> <p class="white_text"><label for="txtpassword">Password:</label> <br /> <input type="password" title="Enter your password" name="txtPassword" /></p> <p><input type="submit" name="Submit" value="Login" /></p> </form> <?php } else { ?> CONTENT TO BE SHOWN................Is there a simple way of creating a form just to update those two bits in the connection.php or will I have to bite the bullet and set it up via MySQL from the off? Thanks in advance Steve Similar TutorialsHey all. I've created a script that updates a website's config in a database. The script itself works fine but I feel it is rather uncanny. Where can I look to find better methods of achieving what I'm trying to accomplish? Here's my script that updates my table with columns id, showlogin, colorscheme, blogmenu, aboutus. I explain the script below it. if (isset($_POST['submit'])) { // id will always be 1 and only query if only submit was pressed $sql = "UPDATE config SET id=1"; // showlogin values are 1 for show login form and 2 for don't if(!empty($_POST['showlogin'])) { $showlogin = $_POST['showlogin']; $sql .= ", showlogin='$showlogin'"; } if(!empty($_POST['colorscheme'])) { $colorscheme = $_POST['colorscheme']; $sql .= ", colorscheme='$colorscheme'"; } if(!empty($_POST['blogmenu'])) { $blogmenu = $_POST['blogmenu']; $sql .= ", blogmenu='$blogmenu'"; } else { $sql .= ", blogmenu=2"; } if(!empty($_POST['aboutus'])) { $aboutus = $_POST['aboutus']; $sql .= ", aboutus='$aboutus'"; } else { $sql .= ", aboutus=2"; } mysql_query($sql, $connect) or die (mysql_error()); } It works like this. I have a form with a few selects and checkboxes. The selects are the colorscheme and showlogin. The checkboxes are blogmenu and about us, both defaulting to the number 2 if they are not checked. 1 means show this item on the live site and 2 means do not show. This is pulled out of the database on page loads. So, I hope I was clear as my mind is spaghetti right now. Cheers! where does the connection details go and in what manner order etc, server url, username, password <?php define( "DB_DSN", "); define( "DB_USERNAME", " ); define( "DB_PASSWORD", " ); define( "PAGE_SIZE", 5 ); define( "TBL_", " ); define( "TBL_", "" ); ?> I have a PHP script that is encrypted with Ion Cube. Since I don't want to violate the license, I can't modify anything in the script. The script makes calls to an XML based config file. I want to create a database to store the config data and then feed it to the encrypted script based on the referer URL that made the request. Basically, I want to "virtualize" the config XML file so I can feed the encrypted script the data I want based on the referer URL. Any ideas? I'm really embarrassed asking this.. I have two files. config.php & program.php config.php<php $max_columns = 3; ?> program.php<?php include ('config.php'); echo $max_columns; ?> I can't get the script to echo anything. I have tried... $max_columns = '3'; $max_columns = "3"; include_once include ("config.php"); include ('/path/to/file/config.php'); require .....etc. etc. Any thoughts? PLEASE, I'm going nuts here. Thanks for you patience with what must be a very trivial question for you guys Hi there, I am trying to create a custom registration form and connect the file to mysql using a config.php file. I created the file with a tutorial. I placed both the config.php and the registration.php in a "page-templates folder" inside the "theme folder". Using wordpress "add new page" I am able to select the registration.php file as a template. I am able to open the newly created page and type in information like username and password. I am able to press submit and I get redirected to a new page.
Problem: I would really appreciate your help. Siegfried This is my first post on your forums. I've some problems with a registration form that I've been trying to work out for 2+ days now, asking about it here is a last resort - I have a config.php file located at config/config.php there's a register.php file in the sites root directory and a includes/form_handlers/register.php
My config.php file is: <?php ob_start(); session_start(); $timezone = date_default_timezone_set("America/Cancun"); $servername = "localhost"; $username = "root"; $password = ""; $database = "social"; $conn = mysqli_connect($servername, $username, $password, $database); if (mysqli_connect_error()) { echo "Failed to connect: " . mysqli_connect_error(); } ?> This is my register.php file: <?php require 'config/config.php'; require 'includes/form_handlers/register.php'; ?> <!-- REMOVED THE <HEAD> SECTION --> <body class="login-img3-body"> <div class="container"> <form class="login-form" action="includes/form_handlers/register.php" method="POST"> <div class="login-wrap"> <p class="login-img"><i class="icon_lock_alt"></i></p> <div class="input-group"> <span class="input-group-addon"><i class="icon_profile"></i></span> <input type="text" class="form-control" name="fname" placeholder="First Name" value="<?php if(isset($_SESSION['fname'])) { echo $_SESSION['fname']; } ?>" required> <br> <?php if(in_array("Your first name must be 2-50 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your first name must be 2-50 characters long.</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_profile"></i></span> <input type="text" class="form-control" name="lname" placeholder="Last Name" value="<?php if(isset($_SESSION['lname'])) { echo $_SESSION['lname']; } ?>" required> <br> <?php if(in_array("Your last name must be 2-50 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your last name must be 2-50 characters long.</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_mail_alt"></i></span> <input type="text" class="form-control" name="email" placeholder="Email" value="<?php if(isset($_SESSION['email'])) { echo $_SESSION['email']; } ?>" required> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_mail_alt"></i></span> <input type="text" class="form-control" name="email2" placeholder="Confirm Email" value="<?php if(isset($_SESSION['email2'])) { echo $_SESSION['email2']; } ?>" required> <br> <?php if(in_array("Email already in use<br>", $error_array)) echo "<span style='color: #AD0303;'>Email already in use</span><br>"; else if(in_array("Invalid Email<br>", $error_array)) echo "<span style='color: #AD0303;'>Invalid Email</span><br>"; else if(in_array("Emails don't match<br>", $error_array)) echo "<span style='color: #AD0303;'>Emails don't match</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_key_alt"></i></span> <input type="password" class="form-control" name="pwd" placeholder="Password" required> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_key_alt"></i></span> <input type="password" class="form-control" name="pwd2" placeholder="Confirm Password" required> <br> <?php if(in_array("Your passwords don't match.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your passwords don't match.</span><br>"; else if(in_array("Your password must contain English characters or numbers.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your password must contain English characters or numbers.</span><br>"; else if(in_array("Your password must be 5-30 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your password must be 5-30 characters long.</span><br>"; ?> </div> <input class="btn btn-info btn-lg btn-block" type="submit" name="register" value="Register"> </div> <?php if(in_array("<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>", $error_array)) echo "<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>"; ?> </form> </div> </body> </html> and my includes/form_handlers/register.php file: <?php //error variables $fname = ""; $lname = ""; $email = ""; $email2 = ""; $pwd = ""; $pwd2 = ""; $date = ""; $error_array = array(); if(isset($_POST['register'])) { //form values $fname = clean($_POST['fname']); $_SESSION['fname'] = $fname; $lname = clean($_POST['lname']); $_SESSION['lname'] = $lname; $email = clean($_POST['email']); $_SESSION['email'] = $email; $email2 = clean($_POST['email2']); $_SESSION['email2'] = $email2; $pwd = strip_tags($_POST['pwd']); $pwd2 = strip_tags($_POST['pwd2']); $date = date('Y-m-d'); //signup date if($email == $email2) { //validate email format if(filter_var($email, FILTER_VALIDATE_EMAIL)) { $email = filter_var($email, FILTER_VALIDATE_EMAIL); //does email exist?? $email_check = mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"); //number of rows returned $num_rows = mysqli_num_rows($email_check); if($num_rows > 0) { array_push($error_array, "Email already in use<br>"); } } else { array_push($error_array, "Invalid Email<br>"); } } else { array_push($error_array, "Emails don't match<br>"); } //first name length if(strlen($fname) > 50 || strlen($fname) < 2) { array_push($error_array, "Your first name must be 2-50 characters long.<br>"); } //last name length if(strlen($lname) > 50 || strlen($lname) < 2) { array_push($error_array, "Your last name must be 2-50 characters long.<br>"); } if($pwd != $pwd2) { array_push($error_array, "Your passwords don't match.<br>"); } else { if(preg_match('/[^A-Za-z0-9]/', $pwd)) { array_push($error_array, "Your password must contain English characters or numbers.<br>"); } } if(strlen($pwd) > 30 || strlen($pwd) < 2) { array_push($error_array, "Your password must be 5-30 characters long.<br>"); } if(empty($error_array)) { $pwd = md5($pwd); //encrypts password $username = strtolower($fname . "_" . $lname); $check_username = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); //assign unique username if original is taken $snum = 0; while(mysqli_num_rows($check_username) != 0) { $snum++; $username = $username . "00" . $snum; $check_username = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); } //assign a random profile pic $rand = rand(1,3); switch ($rand) { case '1': $profile_pic = "assets/images/profile_pics/default/01.jpeg"; break; case '2': $profile_pic = "assets/images/profile_pics/default/02.jpeg"; break; case '3': $profile_pic = "assets/images/profile_pics/default/03.jpeg"; break; } $query = mysqli_query($conn, "INSERT INTO users VALUES (NULL, '$fname', '$lname', '$username', '$email', '$pwd', '$date', '$profile_pic', '0', '0', 'no', ',')"); array_push($error_array, "<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>"); //clear session variables $_SESSION['fname'] = ""; $_SESSION['lname'] = ""; $_SESSION['email'] = ""; $_SESSION['email2'] = ""; } } //polish user imput function clean($data) { $data = str_replace(" ","", $data); $data = htmlspecialchars($data); $data = stripslashes($data); $data = strip_tags($data); $data = trim($data); return $data; } ?> I can't get the reg. form handler to recognize the $conn variable from the config.php file. if I add require '../../config/config.php'; to it I get this error:
Warning: require(../../config/config.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/qcicnews/includes/form_handlers/register.php on line 3 I don't know why it can't find that file, but the way I understand PHP is that I don't need that line because it's in the register.php. When I don't use it I get a party of errors all connected to it not recognizing the $conn variable:
Notice: Undefined variable: conn in /opt/lampp/htdocs/qcicnews/includes/form_handlers/register.php on line 43
There's about 6 more that look like the ones above but from different lines where $conn is referenced, I just deleted them for brevity sake. I'm pretty new to PHP and this is the most difficult situation I've encountered so far, can someone help me find the way here?
To me it is logical to store config data such as site name, meta, etc in a php file rather than storing ina table in mysql database. This will reduce the number of calls to the mysql database, as these are key parameters and needed in every page. But, a well-developed CMS like Wordpress uses a mysql table to store such basic data. What is your idea? Ain't it better to reduce mysql loads? Hey guys, Just lately I have been trying to start a specific project for myself. I started off by designing the pages etc on HTML, and then a friend of mine helped me convert them to PHP.
At the moment, when a user registers to the site, they only require to enter a Username and Password. I would like to add their email to it too, due to adding slightly extra security. It would also be used for future reasons such as sending emails out etc.
I'm not sure about adding this, I know that most likely it is going to be VERY similar to how it already is, but I couldn't seem to get it to work when I tried.
Ill give the coding which I am using for this below (the documents which I believe would need editing) :
Register.php
<?php require($_SERVER['DOCUMENT_ROOT'] . '/TruckWorld/includes/config.php'); $sOutput .= '<div id="register-body">'; if (isset($_GET['action'])) { switch (strtolower($_GET['action'])) { case 'register': // If the form was submitted lets try to create the account. if (isset($_POST['username']) && isset($_POST['password'])) { if (createAccount($_POST['username'], $_POST['password'])) { $sOutput .= '<h1>Account Created</h1><br />Your account has been created. You can now login <a href="login.php">here</a>.'; }else { // unset the action to display the registration form. unset($_GET['action']); } }else { $_SESSION['error'] = "Username and or Password was not supplied."; unset($_GET['action']); } break; } } // If the user is logged in display them a message. if (loggedIn()) { $sOutput .= '<h2>Already Registered</h2> You have already registered and are currently logged in as: ' . $_SESSION['username'] . '. <h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4> <h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; // If the action is not set, we want to display the registration form }elseif (!isset($_GET['action'])) { // incase there was an error // see if we have a previous username $sUsername = ""; if (isset($_POST['username'])) { $sUsername = $_POST['username']; } $sError = ""; if (isset($_SESSION['error'])) { $sError = '<span id="error">' . $_SESSION['error'] . '</span><br />'; } $sOutput .= '<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Truck World - Register</title> <!-- Core CSS - Include with every page --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="font-awesome/css/font-awesome.css" rel="stylesheet"> <!-- SB Admin CSS - Include with every page --> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body> <div align=center><img src="images/logintitle.png" alt="LoginTitle" /></div> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-panel panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Register To Join Truck World!</h3> </div> <div class="panel-body"> ' . $sError . ' <form name="register" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=register"> <fieldset> <div class="form-group"> <input class="form-control" placeholder="Username" name="username" type="username" autofocus=""> </div> <div class="form-group"> <input class="form-control" placeholder="Password" name="password" type="password" value=""> </div> <div class="form-group"> <input class="form-control" placeholder="Email" name="email" type="email" value=""> </div> <!-- Change this to a button or input when using this as a form --> <input type="submit" class="btn btn-lg btn-success btn-block" name="submit" value="Register" /> <a href="login.php"class="btn btn-lg btn-success btn-block">Login</a> </fieldset>'; } $sOutput .= '</div> </div> </div> </div> </div> <div align=center><h5><small>Copyright - Lewis Pickles 2014 - All Rights Reserved</small></h5></div> <!-- Core Scripts - Include with every page --> <script src="js/jquery-1.10.2.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script> <!-- SB Admin Scripts - Include with every page --> <script src="js/sb-admin.js"></script> </body> </html> '; // display our output. echo $sOutput; ?>Functions.php (Not sure if this would need editing, I think it might, Correct me if I'm wrong) <?php function createAccount($pUsername, $pPassword) { // First check we have data passed in. if (!empty($pUsername) && !empty($pPassword)) { $uLen = strlen($pUsername); $pLen = strlen($pPassword); // escape the $pUsername to avoid SQL Injections $eUsername = mysql_real_escape_string($pUsername); $sql = "SELECT username FROM users WHERE username = '" . $eUsername . "' LIMIT 1"; // Note the use of trigger_error instead of or die. $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // Error checks (Should be explained with the error) if ($uLen <= 4 || $uLen >= 11) { $_SESSION['error'] = "Username must be between 4 and 11 characters."; }elseif ($pLen < 6) { $_SESSION['error'] = "Password must be longer then 6 characters."; }elseif (mysql_num_rows($query) == 1) { $_SESSION['error'] = "Username already exists."; }else { // All errors passed lets // Create our insert SQL by hashing the password and using the escaped Username. $sql = "INSERT INTO users (`username`, `password`) VALUES ('" . $eUsername . "', '" . hashPassword($pPassword, SALT1, SALT2) . "');"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); if ($query) { return true; } } } return false; } /*********** string hashPassword (string $pPassword, string $pSalt1, string $pSalt2) This will create a SHA1 hash of the password using 2 salts that the user specifies. ************/ function hashPassword($pPassword, $pSalt1="2345#$%@3e", $pSalt2="taesa%#@2%^#") { return sha1(md5($pSalt2 . $pPassword . $pSalt1)); } /*********** bool loggedIn verifies that session data is in tack and the user is valid for this session. ************/ function loggedIn() { // check both loggedin and username to verify user. if (isset($_SESSION['loggedin']) && isset($_SESSION['username'])) { return true; } return false; } /*********** bool logoutUser Log out a user by unsetting the session variable. ************/ function logoutUser() { // using unset will remove the variable // and thus logging off the user. unset($_SESSION['username']); unset($_SESSION['loggedin']); return true; } /*********** bool validateUser Attempt to verify that a username / password combination are valid. If they are it will set cookies and session data then return true. If they are not valid it simply returns false. ************/ function validateUser($pUsername, $pPassword) { // See if the username and password are valid. $sql = "SELECT username FROM users WHERE username = '" . mysql_real_escape_string($pUsername) . "' AND password = '" . hashPassword($pPassword, SALT1, SALT2) . "' LIMIT 1"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // If one row was returned, the user was logged in! if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['loggedin'] = true; return true; } return false; } ?>The Database for the email is as follows: Edited by Lewis2212, 06 August 2014 - 10:20 AM. I'm very fresh to php coding, and embedding it in html, so I'm a bit lost here. I have made a script for doing backups of mysql on the QNAP box, I want to make a page to set the variables in it, so the users don't have to change directly in the script like they do now. First the page should read in the current config, and display that in the form, and then users can change the values, and press save, quite simple I'm sure for the experienced php coder :-) I'm not sure if it's a HTML or PHP question, so here goes, if it's in the wrong forum, maybe the moderator will forgive me, and move the topic to the right one. THe page I've currently created looks like this: Code: [Select] <html><body> <h1>Mysql Backup Script</h1> <?php $config=parse_ini_file("config.txt"); ?> <form action="writeconfig.php" method="post"> <p>Days to save config: <input type="text" name="configdays" value="<?php echo $config('configdays'); ?>"/> <br> <p>Name of Backup location (share): <input type="text" name="share" value="<?php echo $config('share'); ?>"/> <br> <p>MySQL Backup User: <input type="text" name="user" value=<?php echo $config('user'); ?>"/> <p>Errorlevel (0=off, 1=error, 2=error+warn, 3=error+warn+info: <select name="error"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> </select> <br> <p><input type="submit" value="Save" /> </form> </body></html> The problem is that it doesn't show the variables in the value fields, but rather the php code And the writeconfig.php looks like this: Code: [Select] <?php $configdays = $_POST['configdays']; $share = $_POST['share']; $user = $_POST['user']; $error = $_POST['error']; $int_options = array("options"=>array("min_range"=>1, "max_range"=>100)); if (!filter_var($configdays, FILTER_VALIDATE_INT, $int_options)) die("Value for number of config days is incorrect allowed value is 1-100"); $fp = fopen("config.txt", "w"); fwrite($fp, "configdays=" . $configdays . "\r\n" . "share=". $share . "\r\n" . "user=". $user . "\r\n" . "error=". $error . "\r\n"); fclose($fp); echo "Config file successfully written" ?> It's all still very raw, but the write part works ok, still needs a lot of input validation of course. As you can see, I'm still in the beginning part of this, so if I'm doing something wrong, or there's another way to do it properly, let me know! Well hello there, I want to create a script that writes a few PHP constants to a file called config.php. It does not work however, with the way I wrote it as below: Code: [Select] $configdata = "<?php //Configuration File \define("DBHOST", $dbhost); //DB Hostname \define("DBUSER", $dbuser); //DB Username \define("DBPASS", $dbpass); //DB Password \define("DBNAME", $dbname); //Your database name \define("DOMAIN", $domain); //Your domain name (No http, www or . ) \define("SCRIPTPATH", $scriptpath); //The folder you installed this script in \define("PREFIX", $prefix); ?>"; $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); I am getting this error 'syntax error, unexpected T_STRING in ...', and I have no idea how to fix it. Strangely the below codes using PHP variables work flawlessly: Code: [Select] $configdata = "<?php //Configuration File \$dbhost = '{$dbhost}'; //DB Hostname \$dbuser = '{$dbuser}'; //DB User \$dbpass = '{$dbpass}'; //DB Password \$dbname = '{$dbname}'; //Your database name \$domain = '{$domain}'; //Your domain name (No http, www or . ) \$scriptpath = '{$scriptpath}'; //The folder you installed this script in \$prefix = '{$prefix}'; ?>"; //Write the config.php file... $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); This confuses me, all I did was to change the string to output from a list of variables to a list of constants, and it gives weird errors that I have absolutely no idea how to fix. Can anyone please lemme know what I did wrong? Thanks. files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
So i write to an external file for my signatures storage...and dont yell at me about the joys of databases...i got it all worked out. anyways so my script changes the external file and then the external file is read and part of it is echoed on the page. Everything gets written adn everything but when i write to the file i have to refresh in order to echo the new info. I thought moving the script that changes the material in the file to the top would solve this...yet for some odd reason no change. fiddling around with it i found out that for some reason the file content dosnt actually change until I refresh. stranger still is that when I fwrite a str_replace it echos the new information just fine...hmm...help please! where am I going wrong here? Code: [Select] <?php $message = null; $allowed_extensions = array('csv'); $upload_path = 'c:\wamp\tmp'; if (!empty($_FILES['file'])) { if ($_FILES['file']['error'] == 0) { // check extension $file = explode(".", $_FILES['file']['name']); $extension = array_pop($file); if (in_array($extension, $allowed_extensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) { if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) { $keys = array(); $out = array(); $insert = array(); $line = 1; while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { foreach($row as $key => $value) { if ($line === 1) { $keys[$key] = $value; } else { $out[$line][$key] = $value; } } $line++; } fclose($handle); if (!empty($keys) && !empty($out)) { $conndb = mysql_connect("localhost", "root", ""); mysql_select_db("master", conndb); foreach($out as $key => $value) { $sql = "UPDATE `master` SET `LOCATION` = '{$LOCATION}', `Location Name` = '{$Location Name}' WHERE `Asset Number` = {$Asset Number}"; mysql_query($sql); } mysql_close($conndb); $message = '<span class="green">File has been uploaded successfully</span>'; } } } } else { $message = '<span class="red">Only .csv file format is allowed</span>'; } } else { $message = '<span class="red">There was a problem with your file</span>'; } } ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8" /> <title>Upload CSV to MySQL</title> <meta name="description" content="" /> <meta name="keywords" content="" /> <link href="/styles/core.css" rel="stylesheet" type="text/css" /> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <section id="wrapper"> <form action="" method="post" enctype="multipart/form-data"> <table cellpadding="0" cellspacing="0" border="0" class="table"> <tr> <th><label for="file">Select file</label> <?php echo $message; ?></th> </tr> <tr> <td><input type="file" name="file" id="file" size="30" /></td> </tr> <tr> <td><input type="submit" id="btn" class="fl_l" value="Submit" /></td> </tr> </table> </form> </section> </body> </html> Line 55 errors saying: ( ! ) Parse error: syntax error, unexpected T_STRING, expecting '}' in C:\Documents\PHPRunnerProjects\Jobs3\output\importtest.php on line 55 the line in question is: $sql = "UPDATE `master` SET `LOCATION` = '{$LOCATION}', `Location Name` = '{$Location Name}' WHERE `Asset Number` = {$Asset Number}"; There are 50 csv files. each csv file have the same column's name. some content in the column are the same, some don't. eg:test1.csv, example1.csv, hello.csv, world.csv.......test70.csv. now, i want to make a change to two column's content. a, all csv files have a column named qty. whose rows content are all 0. now, i want to change it into Code: [Select] 888 b, all csv files have a column named image. whose rows content are all Code: [Select] upload/img1.jpg upload/img2.jpg upload/img3.jpg upload/img01.jpg upload/img14.jpg upload/img01.jpg .......If i open each csv file then do a search and replace. i fell it too bored. Thank you in advance. i want to delete Uploadin the image column, change 0 to 888 in the qty column. i using the file change.php to update the record. one csv file. http://phplist.xxmn.com/women.csv the code: Code: [Select] <?php $dir = getcwd(); $files = array_diff(scandir($dir), array('..', '.','change.php')); foreach ($files as $file) { if (($handle = fopen($file, "r")) !== FALSE) { $new_content = ''; while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { //var_dump($data); $data[2]=888; $new_content .= implode(',', $data); //var_dump($new_content); } file_put_contents($file, $new_content); echo 'down'; } } ?> the code doesn't work how to correct it . thank u I have the following code for a very simple registration form handler -
//require('../../config/config.php'); require('reg_functions.php'); //assign clean form variables $firstname = clean_names($_POST['firstname']); $lastname = clean_names($_POST['lastname']); $username = clean_names($_POST['username']); $email = clean_email($_POST['email']); $email2 = clean_email($_POST['email2']); $password = clean_password($_POST['password']); $password2 = clean_password($_POST['password2']); $date = date("Y-m-d"); if(isset($_POST['register_button'])) { //validate & confirm emails match if($email == $email2) { if(filter_var($email, FILTER_VALIDATE_EMAIL)) { $email = filter_var($email, FILTER_VALIDATE_EMAIL); // I THINK I COULD DEF MAKE THIS EMAIL CHECK CLEANER - WORK ON THAT LATER //check if email exists in system already $email_check = mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"); //number of rows returned with the email (this should be 0 to proceed) $number_rows = mysqli_num_rows($email_check); if($number_rows > 0) { echo "Email already in use <br>"; } else { echo "email is correct <br>"; } } else { echo "Invalid email format <br>"; } } else { echo "Emails don't match <br>"; } echo "First Name: " . $firstname . "<br>"; echo "Last Name: " . $lastname . "<br>"; echo "Username: " . $username . "<br>"; echo "Number of Rows: " . $number_rows . "<br>"; } the code that starts with the mysqli_query() function to check for matching emails is where it fails (white screen). I figured it may be because the $conn variable wasn't being associated with the $conn variable in the config.php file. So I added the require config.php at the top. Now it only works if both are commented out. So in reality this could be 2 issues and I struggled with how not to ask too many questions in one post though they may be the same issue. I'm really new to php. Can someone explain the mechanics of whats going on (or not going on). to recap, this is the code that caused the white screen initially - // I THINK I COULD DEF MAKE THIS EMAIL CHECK CLEANER - WORK ON THAT LATER //check if email exists in system already $email_check = mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"); //number of rows returned with the email (this should be 0 to proceed) $number_rows = mysqli_num_rows($email_check); if($number_rows > 0) { echo "Email already in use <br>"; } else { echo "email is correct <br>"; } and I realized it had no association to the $conn variable in the config.php file so I added the require config.php line at the top. This above code is obviously still not working and if I comment it out, the require config.php line still causes a white screen. This is my config file - ob_start(); session_start(); $timezone = date_default_timezone_set("America/xxxxxxxx"); $db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "qcic"; $conn = mysqli_connect( $db_host, $db_user, $db_pass, $db_name ); if( $conn->connect_errno) { printf( "Connect Failed: %s\n", $conn->connect_error); exit(); } else { echo "Connected to database"; } ob_end_flush(); and I get the "Connected to database" echo so I have no idea what the problem is. Anyone with some time and more experience that can explain some of these things? thanks $connet = mysql_connect("host", "db_username", "pass") or die(mysql_error()); $user = $_SESSION['SESS_FIRST_NAME']; mysql_select_db('db_name, $connet) or die(mysql_error()); mysql_query("SELECT members Get $earn='earned' WHERE $user='username' LIMIT 1;"); $earn = $total_earn; ?> <a>$<?php echo "$total_earn";?></a> Where do PHP configuration settings (e.g. Error-Handling Levels) exist? I believe they are in a file somewhere?! Thanks, Debbie I work for a small web design company who use their own servers. When I write PHP scripts on their server i can pass variables over pages and then grab them on the other side by just using that variable again. Like if I had a form input like: <input type="text" name="bob"> Then when the form is submitted I can use $bob on the next page without having to do somthing like: $bob = $_POST['bob']; But when using xampp or some other hosting that I have used I HAVE to use the $_POST['bob'] or $_GET['bob'] to grab the variable. What setting is it that makes this possible, is it in the PHP ini? Thanks for any answers Hi! I am new to PHP and I googled a lot before coming here. I have trouble accessing localhost/community/admin/board_functions.php from a folder which path is localhost/community/boards/test/index.php, which script is the one below. What path should I put on require_once to access the script? Thanks in advance Code: [Select] <?php require_once "..admin/board_functions.php"; $board_location = explode("\\", __DIR__); $board_name = $board_location[5]; $board_title = board_title($board_name); echo $board_title; ?> Hi guys, I want to set up a php script to connect to php sources on another site, something is like this: <?php $mysql = array ( 'host' => 'http://www.mysite.com/myscript.php', } <?php try { include_once('mysql_connect.php'); } Is the source is correct to use that I want to read the script while hide the actual url in the config php script?? Thanks, Mark |