PHP - Check To Make Sure Writing To File Was Successful.
I have a function to writes data I want to make sure it was successful.
my function: Code: [Select] function save_ini_file($filename,$content) { $File = "ini_files/". $filename . ".ini"; echo $File; $Handle = fopen($File, 'w'); $info = $content; fwrite($Handle, $info); fclose($Handle); return true; } the if statement that calls the function. Code: [Select] if(!save_ini_file($serial,$data)) { echo "did not write"; }else{ echo "did write"; } the file is being created but I am getting the "did not write" echoed Similar TutorialsHi guys, I'm running the following code: Code: [Select] $result = shell_exec("su user; scp /path/to/file/text.txt user@domain:/path/to/file/text.txt"); Now, the file get's transferred correctly. However, I need to put in place a check to check if the transfer was successful. $result seems to return the same whether the transfer was successful or not. I want to send an email to state whether the file transfer was successful so what do I need to do to check this? Thanks! So, I have a script that works downloading a file - excerpt below: Code: [Select] header("Pragma: public"); header("Expires: 0"); header('Content-type: "application/octet-stream"'); header("Cache-Control: private",false); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $f = "Content-Disposition: attachment; filename=\"".$myfile['downloadname'].".".$myfile['ext']."\""; header($f); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($file)); ob_clean(); flush(); readfile("$file"); exit(); I record elsewhere in a mysql database when the script is started. In addition, I'd like to be able to record whether the download completes (successfully or otherwise). As it is, the script can run and the user press cancel and it looks like a download but isn't. Is this possible? If so, how? Your help, as ever, gratefully received. I am adding new entries into a MySQL table via a php script. The script works fine, but I want to prevent duplicate entries. How can I check if an entry already exists on the table before initiating the query to write to the table. It is for a user registration type of system. The php script rights "AccountName" and "PassWord" to the table called "Accounts". This was my attempt to check if it exists: $query = "INSERT INTO Accounts(AccountName, Password)VALUES ('".$Accn."','".$Pwwd."')"; $Check = mysql_query("SELECT * FROM Accounts"); while($row = mysql_fetch_array($Check)) { $Account = $row['AccountName']; } if($accn != Account) { mysql_query($query); } Where $accn = the new accountname entered. I am trying to compare the new AccountName(accn) that was entered with the array of all AccountNames already in the database, and if does not already exists, then add it. I am fairly new to PHP and want to someone to check my reasoning and logic for a php query. I have a mySQL table that includes a field called authors. This field has 1+ authors names in it. If there is more than one author in the field, it has been concatenated in the following format: lastname1, firstinitial1., lastname2, first initial2., & lastname3, firstinitial3 Let's say I have three fields: lastname1, first initial1. lastname1, firstinitial1., lastname2, first initial2., & lastname3, firstinitial3. lastname3, firstinitial3. If I do a php count query on the author field I will get 1 count for the multiple field, 1 count for the lastname1 author, 1 count for the lastname3 author and 0 for the lastname2 author even though lastname1 author should be counted twice, correct? Is there anyway to write a query that will count each specific instance in the field as a hit? Am I logically tracking or off the bubble? Thanks! I need to add these lines to my .htaccess file via PHP Code: [Select] RewriteCond %{REQUEST_URI} checkout RewriteRule ^(.*)$ https://myurl.com/checkout/$1 [R,L] RIGHT after this line: Code: [Select] RewriteBase / AND before this line: Code: [Select] RewriteCond %{REQUEST_FILENAME} !-f This is how the current file looks w/o the new line addition: Code: [Select] RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php [L,QSA] It needs to look like this when the new lines are added(extra line breaks not necessary): Code: [Select] RewriteBase / RewriteCond %{REQUEST_URI} checkout RewriteRule ^(.*)$ https://myurl.com/checkout/$1 [R,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php [L,QSA] The line numbers may not match up, so I cannot use the line number. Greetings,
I am new to these forums, I am working on this assignment, and these are the current issues I am running into.
Notice: Undefined variable: year in G:\EasyPHP-5.3.2i\www\PHP_Projects\ChineseZodiacs\zodiac_year_switch.php on line 77
ie. $year = validateInput($year,"Birth Year");
Notice: Undefined variable: year_count in G:\EasyPHP-5.3.2i\www\PHP_Projects\ChineseZodiacs\zodiac_year_switch.php on line 138
ie. echo "<p>You are person " . $year_count . "to enter " . $year . "</p>\n";
Honestly, I believe they are linked, because what should be happening, as the user enters the year, and hits submit, it should create a file called counts/$year.txt - $year should equal the entered data in the textbox, any help would be appreciated.
Thank you for your help.
<!DOCTYPE html> <head> <title>Write to and From a File</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <?php $dir = "counts"; if ( !file_exists($dir)) { mkdir ($dir, 0777); } function validateInput($year, $fieldname) { global $errorCount; if (empty($year)) { echo "\"$fieldname\" is a required field.<br />\n"; ++$errorCount; $retval = ""; } else { // if the field on the form has been filled in if(is_numeric($year)) { if($year >=1900 && $year <=2014) { $retval = $year; } else { ++$errorCount; echo "<p>You must enter a year between 1900 and 2014.</p>\n"; } } else { ++$errorCount; echo "<p>The year must be a number.</p>\n"; } } //ends the else for empty return($retval); } //ends the function function displayForm() { ?> <form action = "<?php echo $_SERVER['SCRIPT_NAME']; ?>" method = "post"> <p>Year of Birth: <input type="text" name="year" /></p> <p><input type="reset" value="Clear Form" /> <input type="submit" name="submit" value="Show Me My Sign" /></p> </form> <?php } function StatisticsForYear($year) { global $year_count; $counter_file = "counts/$year.txt"; if (file_exists($counter_file)) { $year_count = file_get_contents($counter_file); file_put_contents($counter_file, ++$year_count); } else { $year_count = 1; file_put_contents($counter_file, $year_count); } return ($year_count); }?> </head> <body> <?php $showForm = true; $errorCount = 0; //$year=$_POST['year']; $zodiac=""; $start_year =1900; if (isset($_POST['submit'])) $year = $_POST['year']; $year = validateInput($year,"Birth Year"); if ($errorCount==0) $showForm = false; else $showForm = true; if ($showForm == true) { //call the displayForm() function displayForm(); } else { //begins the else statement //determine the zodiac $zodiacArray = array("rat", "ox", "tiger", "rabbit", "dragon", "snake", "horse", "goat", "monkey", "rooster", "dog", "pig"); switch (($_POST['year'] - $start_year) % 6) { case 0: $zodiac = $zodiacArray[0]; break; case 1: $zodiac = $zodiacArray[1]; break; case 2: $zodiac = $zodiacArray[2]; break; case 3: $zodiac = $zodiacArray[3]; break; case 4: $zodiac = $zodiacArray[4]; break; case 5: $zodiac = $zodiacArray[5]; break; case 6: $zodiac = $zodiacArray[6]; break; case 7: $zodiac = $zodiacArray[7]; break; case 8: $zodiac = $zodiacArray[8]; break; case 9: $zodiac = $zodiacArray[9]; break; case 10: $zodiac = $zodiacArray[10]; break; case 11: $zodiac = $zodiacArray[11]; break; default: echo "<p>The Zodiac for this year has not been determined.</p>\n"; break; } //ends the switch statement echo "<p>You were born under the sign of the " . $zodiac . ".</p>\n"; echo "<p>You are person " . $year_count . "to enter " . $year . "</p>\n"; } //ends the else statement ?> </body> </html> Edited by mstevens, 16 October 2014 - 06:36 PM. I am using a script I adapted from a tutorial to print the contents of a text box to a txt file. Basically, it's a really simple way of seeing who has logged in. I only have a handful of users. The problem is, although the text file is being created in the proper folder, it isn't being written to and just remains blank. <div align="center"> <table width="300" border="2" bordercolor="#FFFFFF" style="-moz-border-radius: 18px; -webkit-border-radius: 18px;" height="120" cellpadding="0" cellspacing="0"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" background="images/loginbg.jpg" style="-moz-border-radius: 15px; -webkit-border-radius: 15px;"> <tr align="center"> <td colspan="3"><font color="#FFFFFF"><strong>Family Login </strong></font></td> </tr> <tr> <td width="78"><font color="#000000">Username</font></td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"> <?php $myusername = $_POST['myusername']; $data = "$myusername\n"; //open the file and choose the mode $fh = fopen("logs/login.txt", "a"); fwrite($fh, $data); fclose($fh); ?></td> </tr> <tr> <td><font color="#000000">Password</font></td> <td>:</td> <td><input name="mypassword" type="password" id="mypassword"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Login"> </td> </tr> </table> </td> </form> </tr> </table> </div> I'm not sure what's going wrong but I'm guessing it's the placing of the php, or at least some of it. I'd quite like to add the time they logged in as well. Any idea's anyone? Hey Guys. I am trying to write to the file depending on which condition is met. The code works fine on my local machiene but not on my remote server. I have also tried to output any error messages to see if it would output anything, and I don't get anyting on my browser. Can anyone help me with this issue? Thanks <?php if($_SERVER['REQUEST_METHOD'] == "POST") { isset($_POST['interfax']) ? $option= "interfax" : $option= ""; isset($_POST['metrofax']) ? $option= "metrofax" : $option= ""; switch ($option) { case 'interfax': $file = "fax.php"; $fax_client = "interfax"; if(file_put_contents($file, "<?php ".'$fax_client = "' . $fax_client . '"'." ?>")) { echo "Successful"; } else { die("Can't write file"); } break; // By defualt all the orders go to metrofax so by selecting the variable it resets it self case 'metrofax': $file = "fax.php"; $fax_client = "metrofax"; file_put_contents($file, "<?php ".'$fax_client = "' . NULL . '"'." ?>"); break; } } ?> <form action="#" method="POST"> <input type="radio" name="interfax" value="interfax">Switch To Interfax<br> <input type="radio" name="metrofax" value="metrofax">Switch To Metrofax<br> <input type='submit' name="submit" > Ok, I know how to write to a file, but what I'm looking for is to check if a line of code exists, and if it is, don't recreate it. It would also be nice to not recreate the file either. Code: [Select] $file = fopen("index.html", "w"); fwrite($file,"This is a line of text"); fclose($file); I'm trying to write to a file with the following code. $fh = fopen("../inc/config.php", "a") or die("\r\nCan't open file."); $write = "\$config['database_host'] = {$mysqlh}; \$config['database_user'] = {$mysqlu}; \$config['datbase_pass'] = {$mysqlp}; \$config['datbase_name'] = {$dbn}; \$config['table_prefix'] = {$tp};"; fwrite($fh, $write); fclose($fh); It is printing out "Can't open file", which I guess means it can't find the file or I've given the wrong path. The file that is executing this code is /install and the file I'm trying to write to is /inc/config.php. I thought .. put you up a directory so if I do .. I will be at the root and then do /inc I will be in inc. Can someone please guide me on what I'm doing wrong? Thanks. I have a code for writing a log file... The code is working fine but it inserts the new details at the bottom of the file but i want to insert in the top... So what function should i use... Here is the file my_log.php Code: [Select] <?php $usname = $_SESSION['usname']; date_default_timezone_set('Asia/Calcutta'); $date = date("l dS \of F Y h:i:s A"); $file = "log.php"; $open = fopen($file, "a+"); fseek($open,289); fwrite($open "<b><br/>USER NAME:</b> ".$usname . "<br/>"); fwrite($open, "<b>Date & Time:</b> ".$date. "<br/>"); fwrite($open, "<b>What have they done :</b> ".$reason . "<br/><br/>"); fclose($open); ?> and here is my log.php file : Code: [Select] <?php session_start(); if($_SESSION['stage']!=1 || $_SESSION['stage2']!=2) {header('location:index.php'); die(" "); } ?> <?php if($_GET['valu']=="view_log") { $reason=" ".$_SESSION['usname']." Viewed the LOG"; include('my_log.php'); header('location:log.php'); die(""); } // bytes till here are 289 //LINE 1 : Log details have to insert here I want to insert every detail from the top of the page but just below the php code.. What should i do... ANy helo would be appreciated Pranshu Agrawal pranshu.a.11@gmail.com I need help! I cant get this to write the correct way! What i need is based on the value of what is posted to the script it has to write it in the config file and also make a folder! Please help Code: [Select] <?php $start = '$uploadpath=\''; $structure = '../banner/images/'.$_POST['FOLDER'].'\';\n'; $myFile = "PHP/confup.php"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "<?\n"; fwrite($fh, $stringData); $stringData = "$start $structure"; fwrite($fh, $stringData); $stringData = "?>\n"; fwrite($fh, $stringData); fclose($fh); // Desired folder structure // To create the nested structure, the $recursive parameter // to mkdir() must be specified. if (!mkdir($structure, 0777, true)) { die('Failed to create folders...'); } // ... ?> Is it possible to write to an exact line and column of a text file with PHP like with fwrite or something? Ok I need to write an array to a file here is the code if($place[2] < 10){ echo "Account Invalid"; $account = var_dump($account_data[$i][0]); echo $account; $fp3=fopen('invalid.txt', 'a+'); fwrite($fp3, $account); fclose($fp3);} when I try if($place[2] < 10){ echo "Account Invalid"; $account = var_dump($account_data[$i][0]); echo $account; $fp3=fopen('invalid.txt', 'a+'); fwrite($fp3, $account_data[$i][0]); fclose($fp3);} I just get "Array[1]" written to the file.. What can I do to write the array to the file? Thanks I just wrote a php page that pulls live data from a database and presents it in an XML layout. In Internet Explorer, I can Edit, Select All, then Copy-Paste and save as XML. The resulting XML works fine. In Firefox, I can click File, Save Page As, select Text Files, then name it as an XML. Again, it works fine as XML. So..... how do I skip the Copy/Paste (IE) or Save Page As (Firefox) steps and write the output directly to an XML file? I've played with stdout(), buffers, page capturing utilities (wget, cURL, httrack, etc....), but no luck so far. This creates a pretty intense page due to the amount of data involved (1.3+ MB). Any help is appreciated! i have this script where the user enters their name and their favorite quotes. It adds their favorite quotes and their names to quotes.txt and prints out their name and their quotes on view_quote.php. I need to use a foreach() loop to print out the name and the quotes, but I'm confused about how to set it up. Here's my files. add_quote.php Code: [Select] <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Add A Quotation</title> </head> <body> <?php // add_quote.php /* This script displays and handles an HTML form. This script takes text input and stores it in a text file. */ // Identify the file to use: $file = 'quotes.txt'; // Check for a form submission: if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form. if ( !empty($_POST['quote']) && ($_POST['quote'] != 'Enter your quotation here.' ) ){ // Need some thing to write. if (is_writable($file)) { // Confirm that the file is writable. file_put_contents($file, $_POST['quote'] . PHP_EOL, FILE_APPEND | LOCK_EX); // Write the data. file_put_contents($file, $_POST['name'] . PHP_EOL, FILE_APPEND | LOCK_EX); // Print a message: print '<p>Your quotation has been stored.</p>'; } else { // Could not open the file. print '<p style="color: red;">Your quotation could not be stored due to a system error.</p>'; } } else { // Failed to enter a quotation. print '<p style="color: red;">Please enter a quotation!</p>'; } } // End of submitted IF. // Leave PHP and display the form: ?> <form action="add_quote.php" method="post"> <p>Name:<input type="text" name="name"/><br /> <textarea name="quote" rows="5" cols="30">Enter your quotation here.</textarea><br /> <input type="submit" name="submit" value="Add This Quote!" /> </form> </body> </html>view_quote.php Code: [Select] <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>View A Quotation</title> </head> <body> <h1>View My Quotes</h1> <?php // view_quote.php /* This script displays and handles an HTML form. This script reads in a file and prints a random line from it. */ // Read the file's contents into an array: $data = file('quotes.txt'); // Count the number of items in the array: $n = count($data); // Pick a random item: $rand = rand(0, ($n - 1)); // Print the quotation: print '<p>' . trim($data[$rand]) . '</p>'; ?> </body> </html>and the quotes.txt file is blank until the user enters their names and quotes. Im trying to get this done kind of quick so any help would be awesome. Hi, I am a newbie to php and am trying to copy mysql data to a text file. The format I need to create is for($i=0; $i!=count($account_data); $i++){ echo "\n::: ".strtoupper($account_data[$i][0])." :::\n"; if($account_data[$i][1] != "" && stristr($account_data[$i][0], "@") && stristr($account_data[$i][0], ".")){ list($place[0],$place[1],$place[2],$place[3]) = authorize($account_data[$i], $game_link); if($place[2] > 1 && strlen($place[3]) == 40){ $filename = 'auth-keys.txt'; $fp = file($filename,'a+'); $data = $place[2]." ".$place[3]."\r\n"; file_put_contents($filename, $data, FILE_APPEND); echo $data; } else echo "Account Skipped: wrong password/email combo, or a login error...\n"; $echo = file_put_contents($filename, FILE_APPEND); } else echo "Account Skipped: invalid email or blank password...\n"; } echo "\n::: PROGRAM FINISHED, YOU CAN CLOSE THIS AT ANY TIME :::"; sleep(10000); You see where I tried to put $echo file_put_contents etc... On success the acct writes a security id and a security auth key to a file, ever acct puts the tokens on a new line every acct... now when an acct echos account skipped, how can I make it print the echo on the file new line instead of nothing being writen and it just skipping the account Hi, I am not that versed in PHP. I have been working with this snippet of code that I found on a tutorial site. It works like 97% and I get the format mostly like I need it. Except, I can not figure how to add an extra single node to the list. The code generates 20 random numbers and puts them into an array. The array is then used to create a numbers node in the xml file. It goes through and creates all the nodes. I can not seem to figure out how to put a single game numbernode at the top of all the numbers nodes. I am also not understanding how to write the output to create the actual xml file. I have written code in the past to write a string to a text file but I am not sure about this because it is in an array? The xml file will be appended every 5 minutes for data comparison down the road. I think I will need to add a routine that calls the data back in at the beginning of the script and looks for the last game number if it is there and add 1. The game number must increment each time it is appended. Any ideas on how to finish this up? The final out put will look like this. I only did a few lines instead of all 20 numbers to keep this short. Code: [Select] <?xml version="1.0"> <Container> <gamenumber>10</gamenumber> <numbers>47</numbers> <numbers>10</numbers> <numbers>5</numbers> <numbers>27</numbers> </Container> My Script Code: [Select] <?php $balls = range(1,80); shuffle($balls); $pick = array_slice($balls,1,20); //$drawn = implode(", ",$pick); $arraySize = sizeof($pick); // print ("Arraw is $drawn\n\n"); $doc = new DOMDocument(); $doc->formatOutput = true; $drawn = array(); $r = $doc->createElement( "Container" ); $doc->appendChild( $r ); for ($i=0; $i!= $arraySize; $i++){ $drawn [] = array( 'numbers' => $pick[$i], ); } foreach( $drawn as $draw ) { $numbers = $doc->createElement( "numbers" ); $numbers->appendChild( $doc->createTextNode( $draw['numbers'] ) ); $r->appendChild( $numbers); } echo $doc->saveXML(); ?> Thanks for your advise and help!!! Hello I am in need of writting to a txt file on a remote server. When trying I get this error: "failed to open stream: HTTP wrapper does not support writeable connections in /home....." How can I write to a siply txt file on a remote server? |