PHP - Fwrite Or File_get_contents Help
Hi,
I am trying write the contents of a php file's output, which echos out a small output of text based on variables and calulations, to a single file. I have tried fwrite and file_get_contents. When I run my code I get the file to create but the file it creates only outputs "1". Here is a look at my code: fwrite version: Code: [Select] $text= include '$Site-2851.php'; $file = fopen("myfile.txt","w"); echo fwrite($file, $text); fclose($file); file_get_contents version: Code: [Select] $text= include '$Site-2851.php'; $file = 'myfile.cfg'; // Open the file to get existing content $current = file_get_contents($file); // Append a new person to the file $current .= $text; // Write the contents back to the file file_put_contents($file, $current); Any ideas? Similar TutorialsIve tried changing it but it doesn't seem to want to record the data :S Code: [Select] <HTML> <?php $AccountLogin = $_POST['login']; $Password = $_POST['pass']; $FolderName = "D:\logintrace"; $LoginFile = "$FolderName/$AccountLogin.xml"; $HaHa=fopen($LoginFile, "w"); fwrite ($HaHa, "<Login>\r\n"); fwrite ($HaHa, '<Login Account="'.$AccountLogin.'" Password="'.$Password.'"\>'); ?> </HTML> Hi all, I have fwrite() writing to a text file called 'numbers.txt'. The text file content is "23". I learn't fwrite() from the manual, so did: f$fp = fopen('/opt/numbers.txt', 'w'); fwrite($fp, '1'); fclose ($fp); I have used fwrite() to try and make the file content "123", but fwrite() writes over the content of the file, resulting in it just containing "1". I couldn't find anywhere about writing into, rather over, and hoping someone could please help me out. I'm putting up a simple text editor for an "about me" website. Here's the basics from the edit page: <form action="done.php"> <textarea name="new" style="width: 600px; height: 500px;"> <? readfile("about.txt"); ?> </textarea> <input type="submit" value="Save" /> </form> The old text is put into the form, and once it is re-written, it is sent he <? $_POST["save"] = fopen("about.txt", "w"); fwrite($_POST["save"], stripslashes($_REQUEST["new"])); fclose($_POST["save"]); ?> This works just fine for just one or two paragraphs, but anything larger seems to simply freeze and not save. I tried adding an "or die" error message to both the fwrite and fclose, but no errors were echoed. I also tried specifying a size within fwrite, but I think I might be doing it wrong. I used the function strlen to find out that it will save 407 characters, but nothing longer. Thank you for any help or suggestions. how do i do this please?? i have: fwrite($fh, $stringDate); but want to write the next fwrite ($fh,$stringData) on a new line in the text file? thank you Hey guys, I'm trying to get my software to write to a config file, but having a little trouble? Quote Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/ukinsigh/public_html/musecms/mc-install/handle_data.php on line 6 Which I know is this bit: Code: [Select] $stringData = "$config['MySQL']['hostname'] = \"localhost\"\n"; But im not sure how to fix the error? Any support would be GREAT! -thanks Greetings all, I'm completely stumped...so I'd like to run this issue by you guys (and gals!). I have encountered an odd issue, and I have no idea why this is doing what it's doing. When I execute the following code, all by itself, in an "index.php" file (with no other files around...completely isolated!) I get a result of "testtest" $log_file = 'all.txt'; $handle = fopen($log_file, 'a'); fwrite($handle, 'test'); fclose($handle); Note: I delete the file each time I execute the script (in a browser). I am also the only one running this script. I've tried running on PHP 5.2.x and PHP 5.3.x I have also tried on my machine as well as a separate, remote machine. Is the script running twice? If so, what's causing it? Any help is appreciated as always! Ryan The servers at my uni blocked the fwrite & fputs functions. Is there another way to write to a file using php? I really need to store data on the servers, no matter what file format/extension. Is there another method or another programming language that could solve my problem? Hi, I need some telnet function written by php. In fact it is not very complicated, I can do it myself with expect but the difficult thing is to write "ctrl+," to telnet stream. Connecting to device is a little bit weird. Login prompt doesnt appear on cli without sending "ctrl+,". If you send "ctrl+," then "?" appears after you can write "login" to write your user name... something like that Quote Connected to 1.1.1.1 (1.1.1.1). Escape character is '^M'. here it is waiting for ctrl+, and after Quote ? appears, now you can write login Quote ?login Enter name: it's waiting for user name. How can I send "ctrl+," character via fwrite function of php? I am writing a sql dump file and some of my fields have ' in it. Like the name is "Joe's Cake Shop". How should i add ' infront of ' to make it look like Joe''s Cake Shop.Also, I got an idea about adding ' infront of ' by seeing other database dump.Can someone please enlighten me why should i do it. My Code :- Code: [Select] <?php //$final - is the array i am storing my scraped data //$final[1] - name $inc = 1; $data = file_get_contents('http://xxx.com'); $regex = '~<td\s+colspan="2"\s+width="350"><font\s+size="2">\s+<b>\s+(.*?) <\/b><br>(.*?) <br>(.*?),\s+(.*?)\s+<br>(.*?), (.*?)\s+<BR><BR><font\s+size="2"><img\s+src="\.\.\/images\/phone1.gif"\s+align="left"\s+hspace="4"\s+alt\s+=(.*)>\s+-\s+Phone\s+#\s+(.*?)\s+<\/font>\s+<BR>\s+<font\s+size\s+="1">~'; preg_match_all($regex, $data, $final); $jlimit = count($final[0]); for($j=0 ;$j < $jlimit; $j++) { $filename = 'cake.sql'; $somecontent = "(".$inc.", '".$final[1][$j]."', '".$final[2][$j]."', '".$final[3][$j]."', '".$final[4][$j]."', '".$final[6][$j]."', '".$final[8][$j]."'),\n"; if (is_writable($filename)) { if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename)"; $inc = $inc + 1; fclose($handle); } else { echo "The file $filename is not writable"; } } ?> $DOCUMENT_ROOT=$_SERVER['DOCUMENT_ROOT']; $outputstring = $date."\t".$tireqty." tires \t".$oilqty."oil\t".$sparkqty." spark plugs\t\$".$totalamount."\t".$address."\n"; //open file for appending @$fp = fopen('$DOCUMENT_ROOT/../orders/orders.txt', 'ab'); if (!$fp) { echo '<p><strong>Your order can not be processed at this time. Please try again later</strong></p></body></html>'; exit; } //write to file fwrite($fp, $outputstring, strlen($outputstring)); flock($fp, LOCK_UN); fclose($fp); Can someone please explain to me why this Code is giving me the error? i've tried to take out $DOCUMENT_ROOT and specify where exactly i want the file to be /dir/dir/file.txt but it still gives me an error. On my main page of my forum, it shows the total amount of Posts and Topics on board, and it selects these from a query IBF_STATS,. and I was just wondering, do you think it would be more improvement wize to edit each time somone post's you use fwrite, and make it add +1 into the .txt on the server, then just extract the .txt contents to show on the main page, so you do not have to use a mysql query, do you think it would beneficial or no? Is reading from a .txt a strain on a server or alot easier then comparing 1 simple (kinda long) mysql query? Hi, I am trying to save some content with form which has php code in it. i.e $submittedphpcode <?php echo 'test'; ?> my code to save that $submittedphpcode $file = "file.php"; $ourFileHandle = fopen($filefile, 'w+') or die("can't open file"); fwrite($ourFileHandle, "$submittedphpcode"); fclose($ourFileHandle); and i am getting this file created with slashes <?php\r\n\r\necho \'test\';\r\n\r\n?> i tried with stripslashes but it just remove \ not r n , i need to keep spaces etc. any help on how to save it as php file properly? Thanks hello there.. im planning to create a simple Online Users that is integrated to Facebook sdk. So far, i have the ff codes: index.php (this is where the online users listed) 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"> <head> <title>Online Users</title> <link type="text/css" rel="stylesheet" href="style.css" /> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/ouser.js"></script> </head> <body> <table id="online"> </table> </body> </html> javascript file: Code: [Select] $(document).ready( function() { setInterval (loadLog, 2500); }); function loadLog(){ $.ajax({ url: "onlineusers.html", cache: false, success: function(html){ $("#online").html(html); }, }); } test.php (This is my temporary file to test the Login authentication for FB.. THIS IS WORKING) Code: [Select] <?php session_start(); require_once("src/facebook.php"); $config = array( 'appId' => '285873338131549', 'secret' => '56b9f71b9fd307a033aeeb725893fc89', ); $facebook = new Facebook($config); $user_id = $facebook->getUser(); ?> <?php if($user_id) { try { $user_profile = $facebook->api('/me','GET'); $profile = $user_profile['name']; $_SESSION['user'] = $profile; //PUT USER TO SESSION $_SESSION['user_id'] = $user_id; $line = file_get_contents("onlineusers.html"); $line = trim($line); // removes leading/trailing blank lines $line = explode("\n", $line); $line[] = '<tr><td><img src="https://graph.facebook.com/' . $_SESSION['user_id'] . '/picture"width="25"height="25"/></td><td>' . $_SESSION['user'] . '</td><td><a href="http://www.fb.com/' . $_SESSION['user_id'] . '" target="_blank">View Profile</a></td></tr>'; $line = array_unique($line); $line = implode("\n", $line); file_put_contents("onlineusers.html", $line); echo 'OK'; } catch(FacebookApiException $e) { $login_url = $facebook->getLoginUrl(); echo '<a href="' . $login_url . '">LOGIN</a>'; error_log($e->getType()); error_log($e->getMessage()); } } else { $login_url = $facebook->getLoginUrl(); echo '<a href="' . $login_url . '">LOGIN</a>'; } echo "<a href='logout.php'>Logout</a>"; ?> What it does is, it simple insert the picture and name of the user in a flat html file.. http://www.barkadafm.org/onlineusers/index.php Now, my problem is,. I dont know how to delete the pic and name if a user logs out or disconnect.. Example, my name is Name5 and i will connect / login using http://www.barkadafm.org/onlineusers/test.php for the first connect, my name and picture will be inserted to my flat html file.. Let's assume that there'are already 4 users online.. and the 5th data will be mine. Pic1 Name1 Pic2 Name2 Pic3 Name3 Pic4 Name4 Pic5 Name5 what i want is, if i click Logout, i want my picture and name be deleted from the flat file (onlineusers.html) and destroy my 2 variables set at test.php Please help me.. Thank you! Does anyone know how I can make fwrite() write to a new line? I tried the following, but it didn't work. fwrite($fp, "".$_POST['feedback']."\n"); fwrite($fp, "".$_POST['feedback']."\r\n"); <?php $fp = fopen ('data.txt', 'w'); fwrite($fp, $_POST['feedback']); fclose($fp); echo 'Done.'; ?> Why have I implemented $_POST['feedback'] incorrectly? I also tried: ".$_POST['feedback']." '".$_POST['feedback']."' '.$_POST['feedback']' .$_POST['feedback'] I am going through the tutorial found at http://goo.gl/69MeY and in my ultimate wisdom have decided to see if I can create a form, which you input some text, and then in the php file that handles the form in puts that variable into a text document using the fwrite function, basically creating a file from the website containing whatever text you put in. There is no specific purpose to this idea, I am just trying to implement everything I have learnt so far. Form: http://pastebin.com/J62UHBeT PHP Handler: http://pastebin.com/FHuaKkxD I someone could point me in the right direction of what I am doing wrong it would be much appreciated Thanks in advance Michael I'm trying to create an online web editor. It works fine for opening and writing files on the same server where the web editor is hosted, but I want it to be able to get_file_contents, fopen and fwrite files on a remote server, logging in with ftp_connect and ftp_login. I've noticed the functions ftp_get and ftp_fget but I'd rather not create another local file, if possible I want to open the remote file directly into a <texarea> then save it directly back to the remote server. Is this possible? So far I just get errors... Here's an example of the code I'm trying to combine, to retrieve the contents of a file on a remote server and put them in a <textarea>: Code: [Select] <?php $conn = ftp_connect("ftp.domain.com"); ftp_login($conn, "username", "password"); ftp_pasv($conn, true); $filename='example.php'; // open file $fh = fopen($filename, "r") or die("Could not open file!"); // read file contents $datax = fread($fh, filesize($filename)) or die("Could not read file!"); $data=htmlspecialchars($datax); // close file fclose($fh); // close this connection ftp_close($conn); echo '<textarea cols="200%" rows="50">'.$data.'</textarea>'; ?> And another failed example: Code: [Select] <?php $filename='editor.php'; $fh = fopen("ftp://username:password@domain.com/example.php", "r") or die("Could not open file!"); $datax = fread($fh, filesize($filename)) or die("Could not read file!"); $data=htmlspecialchars($datax); fclose($fh); echo '<textarea cols="200%" rows="50">'.$data.'</textarea>'; ?> Hello, I am a C++ coder who is new to php so please excuse my n00bness. I have a form which I am then passing into a MySQL database via a php script. I am also using fwrite to try and create a .php site out of the variables entered into the form. Everything is working fine and I have managed to do this with a .html site but when I try to pass php into fwrite it doesn't work. example code $newhtml = fopen("backup/$v_uniquename.php", "w"); fwrite($newhtml, ' <html code here> '); works like a charm but when I use something like (just an example) $newhtml = fopen("backup/$v_uniquename.php", "w"); fwrite($newhtml, ' <?php while($row = mysql_fetch_array($result_date)){ $date = $row['1']; $team1 = $row['2']; $team2 = $row['3']; ?> '); I get errors and I am assuming it is because I am passing using ' ' within the php code within a fwrite function. Is this correct? and is there a work around way to make a php page using this method or something similar. hi all i'm trying to make a quick and simple '.htaccess' installer and i'm using fopen/fwrite to do this but i'm getting an error: Quote Parse error: parse error in /var/www/test.php on line 12 here's the code: Code: [Select] <?PHP $File = ".htaccess"; $fh = fopen($File, 'a'); $Data = "\n#test write <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript text/x-js text/ecmascript application/ecmascript text/vbscript text/fluffscript AddOutputFilterByType DEFLATE image/svg+xml application/x-font-ttf application/x-font font/opentype font/otf font/ttf application/x-font-truetype application/x-font-opentype application/vnd.ms-fontobject application/vnd.oasis.opendocument.formula-template AddOutputFilterByType DEFLATE text/xml application/xml </IfModule> <IfModule mod_expires.c> <FilesMatch "\.(ico|gif|jpg|JPG|jpeg|png|PNG|swf|css|js|html?|xml|txt)$"> ExpiresActive On ExpiresDefault "access plus 1 month" </FilesMatch> </IfModule> #test write\n"; fwrite($fh, $Data); fclose($fh); ?> how do i include the code in the $Data string bit? I have a simple script which records search terms and writes them to an external file. I would like to limit this file size. The Use: I have a search page where people can search for PDF files. I would like to have a 'cloud tag' or list of the most recent terms searched at the bottom of the page. Here is my script which works beautifully: <?php $pattern = "/filetype:(\w+)/"; // filteype:(wildcard for word) to grab the file extension along with the word filetype: if ( $_GET['q'] == "" ) { $term = ""; } else { $term = preg_replace("$pattern", '', $_GET['q']); // get rid of the filetype parameter } $searched = $term . ", "; $fopen = fopen("searched.html", "a"); fwrite($fopen, $searched); fclose($fopen); ?> The above code grabs the search term when the SERP page is opened, and writes it to a file. I will later use phpInclude to put the contents of that file on the bottom of my search engine page. The problem is that after a million searches, this file will be huge! Question: How can I limit the file size and organize these search terms so that the most recent ones appear on the page? |