cant make array to function - php

first sorry for my english
I have array will used by function
Upload text file and every line will be element in array
$fh = fopen("upload/".'1.txt','r');
$conn = array();
while ($line = fgets($fh)) {
$conn[] = $line;
}
fclose($fh);
$wbs->SendBulk($conn, "hello world");
Go To Function
public function SendBulk($targets, $message)
{
echo "Sending " . count($targets) . " bulk messages...<br />";
foreach($targets as $target)
{
$this->wa->sendPresenceSubscription($target);
$this->wa->pollMessages();
$this->wa->sendMessageComposing($target);
sleep(55);
$this->wa->pollMessages();
$this->wa->sendMessagePaused($target);
static::$sendLock = true;
echo "Sending message from " . $this->username . " to $target... ";
$this->wa->sendMessage($target, $message); // Orginal
while(static::$sendLock)
{
//wait for server receipt
sleep(55);
}
}
My Problem If I have in text file 2 or more element in array
will send for the last element a message
but If i make array like this
$conn= array("565684898", "484849815", "484897987", "515498798");
It work for all elements
Please Help

The string returned by fgets() includes the newline that ends each line. Use rtrim() to remove it:
$conn[] = rtrim($line);
You can also replace your entire code that reads the file with:
$conn = file('upload/1.txt', FILE_IGNORE_NEW_LINES)

Related

Validate Form Against a Text File

I have a simple form input box on my site that the user enters a 4 digit code into & submits. I need that code to match a list of codes in a text file. If not, it just returns an error. If so, it would execute another function. Using PHP.
I'm struggling on how to compare against that text file, seems simple to me...
I appreciate all of your help, learned SOOO much from SO.
Ian
Since you haven't provided a sample of your file or PHP code, am submitting the following:
Considering data.txt contains and with no commas from a .csv file, this will work.
1111
1112
1113
PHP
<?php
$search = "1111";
$file = "data.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
echo "$file DOES contains $search\n";
} else {
echo "$file does NOT contain $search\n";
}
This is another method which will work with or without a comma-seperated file:
1111,
1112,
1113,
PHP
<?php
$search = "1111";
$file = fopen("data.txt", "r") or die("Cannot open file!\n");
while ($line = fgets($file, 1024)) {
//if (preg_match("/\b1111\b/i", $line)) {
if (preg_match("/\b$search\b/i", $line)) {
echo "<b>Found match: " . $line . "</b>";
} else {
echo "No match: " . $line;
}
}
fclose($file);

fgets() returns false even though file is not empty

I have a form from which I save the given input into a textfile,
but I have trouble reading from the saved file:
while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
echo "An error occured while reading the file";
}
$rawLine seems to be always false, even though I use this function before, to fill the textfile:
function addToTable($notizFile) {
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
$date = date(DATE_RFC850);
fwrite($notizFile, $date."#");
fwrite($notizFile, $_POST["notiz"].PHP_EOL);
}
And after I submit the form and get the error message, if I check the textfile, everything is there, so the function works correctly.
If it is of value, I open the file with this command:
$fileNotizen = fopen("notizen.txt", "a+");
Could the problem be that the pointer is already at the end of the file and thus returns false?
$fileNotizen = fopen("notizen.txt", "a+");
a+ opens for read/write but places file pointer AT THE END. So you must fseek() to the beginning first or look into fopen() flags and choose more wisely based on your needs.
Use fseek($fileNotizen, 0, SEEK_SET); to rewind the file.
To read/get content of the file try this function:
function read_file($file_name) {
if (is_readable($file_name)) {
$handle = fopen($file_name, "r");
while (!feof($handle)) {
$content .= fgets($handle);
}
return !empty($content) ? $content : "Empty file..";
} else {
return "This file is not readable.";
}
}
and if you want to see content of the file displayed on separate lines then use <pre></pre> tag like this:
echo "<pre>" . read_file("notizen.txt") . "</pre>";
and if you want to write/add content to the file then try this function:
function write_file($file_name, $content) {
if (file_exists($file_name) && is_writable($file_name)) {
$handle = fopen($file_name, "a");
fwrite($handle, $content . "\n");
fclose($handle);
}
}
and you can use it like this:
$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
write_file("notizen.txt", $content);

php fgets function stuck the server

I have function build_additional_docs which calls another function that do few actions, but first it's call to function read_all_file, which extract the file to string variable and return it.
It's worked perfect when the function create_file_node has been called from another function.
but when it's called from build_additional_docs, the client wait to server untill time out...
I think that the function fail on fgets().
Additional comment: When I call function create_file_node whith with the same files, and the different is that file name is static string, and I have no foreach loop, the code works again...
here is my code:
function build_additional_docs($dir_name, $addDocsArr){
foreach ($addDocsArr as $doc) {
if($summery != ''){
$fileName = $dir_name . '\\' . $doc;
create_file_node($fileName);
}
}
function create_file_node($fileName){ global $base_url;
try{
$text = read_all_file($fileName);
}
catch (Exception $ex){
// some message here
}
return 0;
}
function read_all_file($file_name){
$file_handle = fopen($file_name, "r");
while (!feof($file_handle)) {
$line[] = fgets($file_handle);
}
fclose($file_handle);
return implode('',$line);
}
Found the mistake!
$addDocsArr variable is return value from explode() function for split string to seperated files names. The returned array include strings of file name with spacial characters that cannot be seen...
so when i add the code:
$fileName = $dir_name . '\\' . substr($doc, 0,strlen($doc) - 1);
the code worked.

fGetCsv only reading first line?

I'm trying to use fgetCsv but for some reason it is only reading the first line. Here is the code:
$fieldseparator = ",";
$lineseparator = "\r";
if(!file_exists($csvFile)) {
echo "<div id='error'>Cannot find uploaded file. Please try again</div>";
exit;
}
$file = fopen($csvFile,"r");
if(!$file) {
echo "<div id='error'>Error loading CSV file</div>";
exit;
}
$size = filesize($csvFile);
if(!$size) {
echo "<div id='warning'>File is empty</div>";
exit;
}
$query = "";
$content = fgetcsv($file,$size,$lineseparator);
fclose($file);
foreach($content as $data) {
$values = explode($fieldseparator,$data);
$query[$i] = "('".implode("','",$values)."')";
}
This just outputs one line. Here is the CSV file:
TSE-P01,1,WO47653897,RM,EcoQuiet,1
TSE-P02,1,WO47653898,RM,EcoQuiet,1
TSE-P03,1,WO47653899,RM,EcoQuiet,1
TSE-P04,1,WO47653900,RM,EcoQuiet,1
TSE-P05,1,WO47653901,RM,EcoQuiet,1
TSE-P06,1,WO47653902,RM,EcoQuiet,1
TSE-P07,1,WO47653903,RM,EcoQuiet,1
TSE-P08,1,WO47653904,RM,EcoQuiet,1
Any ideas why this might be happening?
From the docs:
fgetcsv — Gets line from file pointer and parse for CSV fields
If you want more than one line then you need to call it more than once.
This example is the "Example 2" from w3schools http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
$file = fopen("contacts.csv","r");
while(!feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
Using the while loop the code iterates through the whole file/all the lines..
Alternatively.. if you do something like that..
print_r(fgetcsv($file));
print_r(fgetcsv($file));
print_r(fgetcsv($file));
It will print only the first 3 lines..

Parsing file in PHP; how to detect newlines?

I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);

Categories