This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
I've got this PHP script:
<?php
if ('POST' === $_SERVER['REQUEST_METHOD'] && ($_POST['title'] != 'Title') && ($_POST['date'] != 'Date'))
{
$fileName = 'blog.txt';
$fp = fopen('blog.txt', 'a');
$savestring = PHP_EOL . "<h2><center><span>" . $_POST['title'] . "</span></center></h2>" . "<div class=fright><p><em>|<br><strong>| Posted:</strong><br>| " . $_POST['date'] . "<br>|</p></em></div></p></em>" . "<p><em>" . $_POST['paragraph'] . "</em></p>" . PHP_EOL . "<hr>";
fwrite($fp, $savestring);
fclose($fp);
header('Location: http://cod5showtime.url.ph/acp.html');
}
?>
It works perfectly but it has a slight problem. The text is added at the end of the file. Is there a way to make it add the $savestring at the beginning of the text file ? I'm using this for my blog and I just noticed this slight problem.
You need to use the correct writing mode:
$fp = fopen('blog.txt' 'c');
http://us1.php.net/manual/en/function.fopen.php
You can you use
$current = file_get_contents($file);
// Append a data to the file
$current .= "John Smith\n";
file_put_contents($file, $current, FILE_APPEND | LOCK_EX);
Related
My code:
function log_message($user = "", $message = "") {
$log_file = LOG_PATH;
// if we can open the file
if($handle = fopen($log_file, "a")) {
$timestamp = strftime("%Y-%m-%d:%H %H:%M:%S", time());
$content = $timestamp . " | [{$user}] | " . $message . "\n";
fwrite($handle, $content);
fclose($handle);
} else {
die("error opening log file: {$log_file}");
}
}
Problem:
The first time I can write to the file no problem but any subsequent writes don't get make it through and falls into the else statement?
Other info:
The site is hosted on godaddy and i have set the privacy permissions on the folder to be writable.
What I tried:
I used the function
file_put_contents($log_file, $content . PHP_EOL, FILE_APPEND | LOCK_EX);
but same result.
I also tried the solution mentioned in this question: How to make sure a file handle has been closed before next operation?
This question already has answers here:
Turn off warnings and errors on PHP and MySQL
(6 answers)
Closed 5 years ago.
It prints on the screen when it is correctly entered, but I do not want to do anything when it is entered incorrectly
How can I do that?
<?php
header('Content-type: text/html; charset=utf8');
$api_key = 'local';
$keyword = 'test';
$url = 'test.json' . $api_key . '&' .'keyword' .'=' . $GLOBALS['q'] ;
$open = file_get_contents($url);
$data = json_decode($open, true);
$istatistikler = $data['data'];
if ($data) {
foreach ( $istatistikler as $istatistik ){
echo '<div class="right">';
echo 'Oyun modu: ' . $istatistik['title'] . '<br />' .
'Kazanma: ' . $istatistik['content'] . '<br />' .
'Kazanma: ' . $istatistik['image'] . '<br />' .
'Kazanma: ' . $istatistik['category'] . '<br />' .
'<br />' .
'<hr/>';
$karakter_simge = 'http://google.com' . $istatistik['image'] . '';
echo "<img src=".$karakter_simge." >" ;
echo '</div>';
}
}
?>
Successful output
Failed output
Warning:
file_get_contents(http://localhost/api/detail?X-Api-Key=local&keyword=a):
failed to open stream: HTTP request failed! HTTP/1.1 406 Not
Acceptable in /opt/lampp/htdocs/weather-master/php/php-api.php on line
10
"I do not want to print unsuccessfully"
thank you for your help!
This may be helpful:
$open = #file_get_contents($url);
# sign before a function name (in a call) prevents from showing any warnings (It's a bad practice though).
Good luck!
Change
$open = file_get_contents($url);
into
$open = #file_get_contents($url);
if ($open === false)
die("wrong");
The # suppresses the error message. Using die() will abort the script completely with the given message.
Alternatively, change the condition to !== false and wrap the rest of your "successful" code in its body:
$open = #file_get_contents($url);
if ($open !== false)
{
$data = json_decode...
...
...
}
I guess I overshot the goal here a little, but not even running into code that won't work properly without its data isn't a bad idea at all.
I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)
Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180
I've got a form that writes its input to a textfile.
Would it be possible to lock a text file for editing, and perhaps give a friendly message "the file is edited by another user, please try again later."
I'd like to avoid conflicts if the file has multiple editors at the same time.
Here's how the entry is currently added.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
Any thoughts?
You can use flock() function to lock the file. For more see this
Something like:
<?php
$content = file_get_contents("./file.csv");
$fp = fopen("./file.csv", "w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX))
{
// do your file writes here
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
flock($fh, LOCK_UN); // unlock the file
}
?>
In order of desirability:
Use a database.
Use more than one text file.
Use locks:
eg:
$lockwait = 2; // seconds to wait for lock
$waittime = 250000; // microseconds to wait between lock attempts
// 2s / 250000us = 8 attempts.
$myfile = '/path/to/file.txt';
if( $fh = fopen($myfile, 'a') ) {
$waitsum = 0;
// attempt to get exclusive, non-blocking lock
$locked = flock($fh, LOCK_EX | LOCK_NB);
while( !$locked && ($waitsum <= $lockwait) ) {
$waitsum += $waittime/1000000; // microseconds to seconds
usleep($waittime);
$locked = flock($fh, LOCK_EX | LOCK_NB);
}
if( !$locked ) {
echo "Could not lock $myfile for write within $lockwait seconds.";
} else {
// write out your data here
flock($fh, LOCK_UN); // ALWAYS unlock
}
fclose($fh); // ALWAYS close your file handle
} else {
echo "Could not open $myfile";
exit 1;
}
You can use PHP's flock function to lock a file for writing, but that lock won't persist across web requests and doesn't work on NFS mounts (at least in my experience).
Your best be may be to create a token file in the same directory, check for its existence and report an error if it exists.
As with any locking scheme, you're going to have race conditions and locks that remain after the operation has completed, so you'll need a way to mitigate those.
I would recommend creating a hash of the file before editing and storing that value in the lock file. Also send that hash to the client as part of the edit form (so it comes back as data on the commit request). Before writing, compare the passed hash value to the value in the file. If they are the same, commit the data and remove the lock.
If they are different, show an error.
You could try flock — Portable advisory file locking ?
http://php.net/manual/en/function.flock.php
I would just use a simple integer or something like that.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
$status = 1;
...
if($status == 1){
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
$status = 0;
}
else
echo "the file is edited by another user, please try again later.";
Is that what you mean?
Ok sorry if its a stupid question im a begginer.
Im making a small shoutbox just for practise.
It inserts the shout infos in a txt file.
My problem is that, it lists the text from top to bottom, and i would like to do this reversed.
if(isset($_POST['submit'])) {
$text = $_POST['text'];
if(!empty($text)) {
$text = $_POST['text'];
$name = $_POST['name'];
$time = date("H:i");
$content =
"<div class='text'><em>" . $time . "</em>
<span class='c11'><b>" . "<a href='userinfo_php_willbe_here.php' target='_blank'>" . htmlspecialchars($name) . "</a>" . ":</span></b>
" . htmlspecialchars($text) . "
</div>\n";
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
}
}
here is my code.
i was googleing around with not much luck maybe i wasnt looking hard enough.
could please someone give me a hint?
thank you
No way to do so with one function call. You need to read the content from your target file, prepend the data in php and rewrite the whole file (see file_get_contents).
$fileContent = file_get_contents($file);
$fileContent = $content . $fileContent;
file_put_contents($file, $fileContent, LOCK_EX);
You can also use the array_reverse like so:
// Data in file separated by new-line
$data = explode("\n",file_get_contents("filename.txt"));
foreach(array_reverse($data) as $value) {
echo $value."\n";
}
You can only prepend to a file by means of reading it and writing afterwards.
file_put_contents($file, $content . file_get_contents($file), LOCK_EX);