PHP - Avoiding Race Conditions When Opening A File For Writing
I have the following code:
$fp = fopen(“path_to_file”, ‘a’); flock($fp, LOCK_EX); fwrite($fp, $string); flock($fp, LOCK_UN); fclose($fp);If I try to lock the file in two different places at the same time, this will cause a race condition. How can I prevent this? I know in Java, for example, it has a concurrent library which contains reentrant lock, which basically tries to get the lock and if can't waits. What can I do in PHP? Similar TutorialsDo race conditions usually exist when writing OR appending to an existing file? Code: [Select] $f1 = fopen($filename1, 'r+'); $f2 = fopen($filename2, 'a'); flock($f1, LOCK_EX); flock($f2, LOCK_EX); fwrite($f1, 'foo'); fwrite($f2, 'foo'); flock($f1, LOCK_UN); flock($f2, LOCK_UN); fclose($f1); fclose($f2); What would happen if this code ran at the exact same time? Is there a chance that the data could be corrupted in the aforementioned code example? I've got a script where the client can upload pictures. The pictures are then resized, thumbnailed, and added to the database. In the process I'm trying to search the database for a duplicate file name and create a new name if necessary: Code: [Select] $userfile = 'userfile' . $i; $tmpLoc = $_FILES[$userfile]['tmp_name']; $name = $_FILES[$userfile]['name']; $error = $_FILES[$userfile]['error']; $type = $_FILES[$userfile]['type']; $temp = 'album' . $i; $album = $_POST[$temp]; if($error > 0) { echo "Error on $name: "; switch ($error) { case 1: echo "File exceeded upload_max_filesize"; break; case 2: echo "File exceeded max_file_size"; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } echo "</div>"; exit; } // Check for name duplicates and deal with $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if($result) $dup = true; while($dup) { echo "Duplicate file name $name <br />"; $ext; if($type == 'image/gif') $ext = '.gif'; else if($type == 'image/jpeg') $ext = '.jpg'; else if($type == 'image/png') $ext = '.png'; else die("Error: Unsupported file type"); $x = 0; $name = $x . $ext; echo "Checking $name <br />"; $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if(!$result) { $dup = false; echo "File successfully renamed to $name to avoid duplicate <br />"; } $x++; } I don't get any errors of any sort, it just never enters the loop 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. Hey all, I'm just having a problem with this code.. the local server says it has an error on a particular line that will be pointed out in the coding section. Code: [Select] <?php $hd = fopen('content.txt', 'r'); $line = fgets($hd); $content = array(); while($line) { $word = explode(',', $line); $content [$word[0]] => array('img_path' => $word[1], 'description' => $word[2], 'price' => $word[3]); // the error message is indicating this line is broken!! Is it because of an equal sign missing? I tried putting an equal sign, but still it doesn't run. $line = fgets($hd); } fclose($hd); ?> Your help is greatly needed.. Hi. I am working with some rather large files. Sometimes I am just opening a file and trying to find an entry on a single line. Sometimes I am opening a file and working on each line.
Whats the most efficient way to work with a large file?
If I open a file, and place all lines into an array, I will use a lot of memory.
If I open a file, and work on it line by line, I should use much less memory, but will the process take longer?
Whats most efficient?
I have underlined my main question above.
Thanks :-)
if (!file_exists('../images/flags/imNum.txt')) { $file1 = fopen('../images/flags/imNum.txt','c'); fclose($file1); } why won't that work =\ it makes no sense to me 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...'); } // ... ?> 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. 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" > 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 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? 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 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); <?php $file = 'test.txt'; $lastfm = file_get_contents('http://www.last.fm/group/Rishloo/members'); preg_match_all('/id="r4_([\d]+)">/', $lastfm, $matches); file_put_contents($file, $matches[1]); sleep(100000); ?> That puts the array in a file but I need each value on a new line but it bunches it all up.. this just puts "Array" in file [php] <?php $file = 'test.txt'; $lastfm = file_get_contents('http://www.last.fm/group/Rishloo/members'); preg_match_all('/id="r4_([\d]+)">/', $lastfm, $matches); file_put_contents($file, $matches[1]."\n"); sleep(100000); ?> what do I need to do to print all of the values on a new line? Thanks 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. 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 have a file named example.xml I want to know how to write to the 3rd line on this file? What function to use? I want to be able to write to this xml file right after the <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> tag. Please someone tell me how? Much appreciated. Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://www.example.com/sitemap1.xml.gz</loc> <lastmod>2004-10-01T18:23:17+00:00</lastmod> </sitemap> <sitemap> <loc>http://www.example.com/sitemap2.xml.gz</loc> <lastmod>2005-01-01</lastmod> </sitemap> </sitemapindex> 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 a newbie to php and am trying to copy mysql data to a text file. The format I need to create is 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!!! |