PHP File Operation - php

I am trying to create a text file with PHP in fopen("test.txt","a"). I have also tried with fopen("test.txt","w+").
The text file is created but I want to check for some string in test.text, that it exist or in test.txt it will not create duplicate entry. Can someone help me out?

Use this code:
$content = file_get_contents('test.txt');
if (str_pos('YOUR KEYWORD', $content) !== false){
// your keyword exists in the file
}

if (!file_exists("test.txt"))
{
///file does not exist
}
else
{
$f = fopen("test.txt", "a");
fwrite($f, "appending text");
}
searching in file:
$arr = file_get_contents("test.txt");
if (preg_match("/your_rexexp/i", $arr))
{
echo "text found";
}

If I understand you correctly, you want to insert new values into a textfile, but first check if the value already exists in it.
You can use fread() to get the contents of the file, and then through preg_match() you can check for values in the file.

If you are using PHP5 then you can use some of the new easy functions.
file_exists(filename) returns boolean
sayin if the file exists.
file_put_contents(filename,data) returns boolean saying if the write was successful.
file_get_contents(filename) returns the contents of the file (string).

Related

How do I add content in a new row to a txt file

I would like to create a < input> where if someone enters text, a text file will add the content entered as a new row. I have tried highly modified the feature in this link: here
Just use the PHP_EOL (PHP end of line) constant that will create a new line.
This must be appended at the end of each line.
$file = fopen("myfile.txt", "a+");
fwrite($file, "hello".PHP_EOL);
// or...
fwrite($file, $myvar.PHP_EOL);
Alternatively, you could create your own, new, function:
function fwrite2($handle, string $string, $length = null, $newline = true) {
$string = $newline ? $string.PHP_EOL : $string;
if (isset($length)) {
fwrite($handle, $string, $length);
} else {
fwrite($handle, $string);
}
}
Call the above in the same manner, except the third argument will now create a new line automatically.
Edit following the comments:
The a+ means that the file is open and stored in $file and is available for reading and writing. The a stands for append; meaning the fwrite will append the file.
See more on the PHP documentation.
$file = fopen("myfile.txt", "a+");
fwrite2($file, "{$_GET['message']} | from {$_GET['sender']}");
Since you are using the URL to send data (ill-advised, but that is another point completely), you can access its contents through the superglobal variable - $_GET.
Notice that I have wrapped the values in curly braces. This is because $_GET is an array and if you want to interpolate arrays they must be wrapped, the same goes for class properties.

PHP Validate Value $_GET from url against lines of a txt file

i have a problem i couldn't figure out since im self-taught and still exploring the php world
so i have a text file that looks like this:
951753159
456787541
123156488
748651651
and i got an url with a variable
http://example.com/mypage.php?variable=951753159
what i want is to check if the url variable matches one of the txt file lines in order to execute a code
i already tried this
$search = $_GET["variable"];
$file = "variables.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
THE CODE THAT I WANT TO EXECUTE
}
but for some reason it matches the whole content of the file
any help is highly appreciated
Thanks in advance :)
Try with an array from file():
$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);
if(in_array($_GET["variable"], $lines)) {
// YES FOUND
} else {
// NOT FOUND
}
From the documentation on `file_get_contents', the entire contents of the file are read as a string. So that is why it is matching against the entire file.
The command that you want to use is file, this reads the file into an array of each line.
I would
Use file to read the file into an array.
Then array_flip the array so that it's values are now the keys
Which allows me to isset($array[$key])
You can do this.
<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
if (trim($search) == trim($value)) {
print "DO something! " . $value;
}
}?>
Regards.
Nelson.

Writing some data to a specific area within a file in PHP

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?
Ideally, I'd like to:
Use fopen to get the file
Search for a comment called <!-- test -->
Replace that comment with new data.
This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).
Thanks!
<?php
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
}
?>
From: http://www.php.net/manual/en/function.fopen.php#81325
EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
?>
If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

inserting csv file data into an array (PHP)

I am attempting to insert the data from an uploaded file into a single dimension array.
The file is as such that there is one student number to a line like so:
392232,392231,etc
this is the most common way I've found online:
while (($line = fgetcsv($file, 25, ',')) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
However form what I understand this will create an array ($line) for each row. Which is not what I want.
that aside I tried this to see if it is working and my code is not printing out the array after using ftgetcsv(). The file is successfully uploading.
here is my code:
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//create file name
$file_path = "csv_files/" . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving uploaded file";
}
print_r($_FILES['csv_file']);
$file = fopen('$file_path', 'r');
while (($line = fgetcsv($file, 25, ',')) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
//delete csv file
unlink($file_path);
}
First off, can anyone obviously see why it wouldnt work to at least print them as seperate arrays of data (each row).
Second, is it possible to set it so that it creates a 1d array of all rows in the file?
Many thanks,
Question 1 is because of
print_r($_FILES['csv_file']);
$file = fopen('$file_path', 'r');
should be:
$file = fopen($file_path, 'r');
and for Question 2, check out the array_push
1st Question:
This line will actually try to open a file called '$file_path' because you're using single quotes (so it doesn't expand to the value of the variable). You can just remove the quotes.
$file = fopen('$file_path', 'r');
$file is null after this.
2nd Question:
If all you want to do is convert a file into an array by lines you can use one of these instead:
file() - get whole file into a 1D array of lines of the file (closest to what you want)
fgets() - get a string per line per call; keep calling this until it returns false to get each line one at a time
file_get_contents() - get the whole file into a string and process as you like
According to PHP.net $line has to return as array.
"returns an array containing the fields read."
But if you are sure it's contains only one student number you can use $line[0] to get the first line value (Ignoring the ",")
Here are some general comments on your code:
You are passing the file path into the fopen() function incorrectly. The variable should not be surrounded with single quotes.
Since you are deleting the CSV file after processing it, moving it is unnecessary. Simply use $_FILES['csv_file']['tmp_name'] as the path to the file.
Since there is only one entry per row in your CSV file, simply access the first element of the array that is returned from fgetcsv(): $numbers[] = $line[0];

Contingency plan for fopen error in php

I'm writing a PHP app that has a 'control panel' that writes a prefs file with certain variables. On every POST, if the file doesn't exist, it is created. If it does exist, it is unlinked and a new file is touched with the same filename and new variables. This file is then included on another page with displays content based on the variables inside it.
$file = "phpsettings.php";
if (!file_exists($file)) {
touch($file);
$handle = fopen ($file, 'r+');
$str = "<?php \$pref1 = \"$mypref\"; ?>";
} else {
unlink($file);
touch($file);
$handle = fopen ($file, 'r+');
$str = "<?php \$pref1 = \"$mypref\"; ?>";
}
fwrite ($handle, $str);
fclose ($handle);
Is this a safe way of writing preferences, provided this file will be overwritten many times per day? What is a good way of both alerting the user of this control panel if the file wasn't saved correctly, and in that case, what would be a good contingency plan to avoid breaking the page this prefs file is included on short of defining a default set of variables to fill if !(file_exists)?
If you store your settings in an array, you can serialize() them and write to a text file, rather than writing raw php to a php file and including it.
If you're not sanitising your input for those preferences, and say $mypref1 represents someone's name, there's nothing stopping them from filling this out in the form field:
\"; echo \"PWNED
and your resulting PHP will become
<?php \$pref1 = \"$mypref\"; echo \"PWNED\"; ?>
So firstly, storing your preferences in an array and using serialize() is much safer:
$prefs = array('mypref1' => 'somethingorother');
$handle = fopen ($file, 'w');
fwrite($handle, serialize($prefs));
fclose($h);
// example code demonstrating unserialization
$prefs2 = unserialize(file_get_contents($file));
var_dump($prefs == $prefs2); // should output "(bool) true"
In your question, you also mention that if the file does exist, it is unlinked. You can simply truncate it to zero length by passing "w" as the second argument to fopen - you don't need to manually delete it. This should set the mtime anyway, negating the need for the call to touch().
If the values being written to the file are preferences, surely each preference could have a default, unless there are hundreds? array_merge will allow you to overwrite on a per-key basis, so if you do something like this:
// array of defaults
$prefs = array(
'mypref1' => 'pants',
'mypref2' => 'socks',
);
if (file_exists($file)) {
// if this fails, an E_NOTICE is raised. are you checking your server error
// logs regularly?
if ($userprefs = unserialize(file_get_contents($file))) {
$prefs = array_merge($prefs, $userprefs);
}
}
If the issue is that there are heaps, and you don't want to have to initialise them all, you could have a get_preference method which just wraps an isset call to the prefs array.
function get_preference($name, &$prefs) {
if (isset($pref[$name]))
return $pref[$name];
return null;
}
var_dump(get_preference('mypref1', $prefs));
Beyond all of the questions this raises though, the reality is that with your app, in the unlikely event that something does go wrong with the fopen, it should be regarded as a serious failure anyway, and the handful of users you're likely to have making use of this feature are going to be contacting you pretty darn quick if something goes wrong.
It is always better to store your users state in a session and only persist that state when needed.
Why not just use the truncation capabilities of fopen()? I believe instead of "r+", you'll need to pass "w+"... Then if the file exists, it will be truncated, if it doesn't you'll just create a new file. So the code becomes:
$file = "phpsettings.php";
$handle = fopen( $file, 'w+' );
$str = "<?php \$pref1 = \"$mypref\"; ?>";
fwrite ($handle, $str);
fclose ($handle);

Categories