generirajSkripte() is my function, but its not important for detecting problem.
So, next code work good:
generirajSkripte('pages/','developingStyles/','develop');
generirajSkripte('pages/','developingStyles/fonts/','fonts');
This code work good too:
//All these variable matching strings above!
generirajSkripte('pages/',$Pages[0].'/',$ScriptNames[0]);
generirajSkripte('pages/',$Pages[0].'/fonts/',$ScriptNames[1]);
And this code doesnt work:
generirajSkripte('pages/',$Pages[0].'/',$ScriptNames[0]);
generirajSkripte('pages/',$Pages[0].'/'.$Pages[1].'/',$ScriptNames[1]);
Variable $Pages[1]=='fonts' 101% , I have spent 8 hours for check it and much more...no anything is no-sense!
So, lets inside generirajSkripte():
function generirajSkripte($pageFolderName,$path,$scriptName)
{
if(!file_exists(noSlashRight($pageFolderName.$path)))
{
echo '(test echo) dont exist: '.$pageFolderName.$path;br();
//die('miki');
if (!mkdir(noSlashRight($pageFolderName.$path), 0777, true)) {die('Failed to create folders...');};
//model.php
$file=fopen($pageFolderName.$path.$scriptName."_m.php", "w");
fwrite($file, "<?php nnnnn?>"); fclose($file);
//wiev php (content)
$file=fopen($pageFolderName.$path.$scriptName."_w.php", "w");
$fileTxt="";
fwrite($file, $fileTxt );
fclose($file);
//file.js
$file=fopen($pageFolderName.$path.$scriptName.".js", "w");
fwrite($file, "/*\n onload(function()\n\t{\n\t});\n*/");
fclose($file);
//file.css
$file=fopen($pageFolderName.$path.$scriptName.".css", "w");
fclose($file);
echo 'There is new script for path: '.$pageFolderName.$path;br();
}
}
In situation when code doesn't work, there is generate a bunch of strange folders, but test echo line is not triggered. So wierd!!
Error? There is not error, only I get extra no-sense and unexpected hierarchy of folders. The names of these folders are getting like all around my main folder. Some names of folders are like my images in my img folder which is on top level of structure.
When I did print variables...what I got in function generirajSkripte(), all variables was exactly like expected...and same in both case!
I was looking for some extra characters in $Pages, so I did test:
echo '<pre>';
print_r($Pages);
print_r($ScriptNames);
echo '</pre>';
and got:
Array
(
[0] => developingStyles
[1] => fonts
[2] =>
[3] =>
[4] =>
)
Array
(
[0] => develop
[1] => fonts
[2] =>
[3] =>
[4] =>
)
..emtpy position are expected too!
And, one more thing.
When I getting unexpected behavior....I run code while my target file is exist! So main condition should be false ...and there is supposed nothing to happen. But, I get all new folder structere with strange names...and cant trigger anything else in same block of code, like my echo test funcion in first line of this block.
This was definitly the most confused bug I have ever seen. After 10+ hours of debuging, i found that PHP was confused with HTML script which is included in proceeding code.
Not necessarily plain HTML, also if I used echo function for generate some HTML parts, it has cause the same confusion.
This part of code was the key:
echo "
<div id='userBox' class='valign_inline'>
<div id='avatar_and_name_box' class='valign_inline'>
<div id='avatarBox' class='krug24 p'><img src='img/profile-photo.png'/></div>
</div>
</div>";
So, lets focus the img tag. If I change this tag name, there is no bug any more!
If I changes src attribute of this tag, it will directly causes diferent name of unexpected folders (while generating folders)
This is obviously unexpected behavior of PHP? ...I dont know what would be my mistake? :/
Related
I am having problems reading a CSV file where the values are encapsulated in quotes.
The first line of my CSV file are headers and they look like the following:
"Header 1","Header 2","Header 3","Header 4","Header 5"
When using fgetcsv, the first header retains the surrounding quotes.
while (($row = fgetcsv($file, 6000, ',')) !== false)
{
echo '<pre>';
print_r($row);
echo '</pre>';
exit;
}
This outputs the following to the page
Array
(
[0] => "Header 1"
[1] => Header 2
[2] => Header 3
[3] => Header 4
[4] => Header 5
)
Does anyone have any advice on how to make sure the quotes are not included in the first array item?
Thanks
As Karsten Koop as a comment stated, it's probably due to a utf8 BOM character. And since php is not solving this behaviour, you'll need to get rid of that char before opening the csv-file for reading.
i.e. using a function like this (more info):
public static function removeUtf8Bom($fileUri){
$content = file_get_contents($fileUri);
$content = str_replace("\xEF\xBB\xBF",'',$content);
file_put_contents($fileUri,$content);
}
It drives me crazy ... I try to parse a csv file and there is a very strange behavior.
Here is the csv
action;id;nom;sites;heures;jours
i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1
Now the php code
$required_fields = array('id','nom','sites','heures','jours');
if (($handle = fopen($filename, "r")) !== FALSE)
{
$cols = 0;
while (($row = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$row = array_map('trim',$row);
// Identify headers
if(!isset($headers))
{
$cols = count($row);
for($i=0;$i<$cols;$i++) $headers[strtolower($row[$i])] = $i;
foreach($required_fields as $val) if(!isset($headers[$val])) break 2;
$headers = array_flip($headers);
print_r($headers);
}
elseif(count($row) >= 4)
{
$temp = array();
for($i=0;$i<$cols;$i++)
{
if(isset($headers[$i]))
{
$temp[$headers[$i]] = $row[$i];
}
}
print_r($temp);
print_r($temp['action']);
var_dump(array_key_exists('action',$temp));
die();
}
}
}
And the output
Array
(
[0] => action
[1] => id
[2] => nom
[3] => sites
[4] => heures
[5] => jours
)
Array
(
[action] => i
[id] =>
[nom] => un nom a la con
[sites] => 1200|128
[heures] =>
[jours] => 1|1|1|1|1|1|1
)
<b>Notice</b>: Undefined index: action in <b>index.php</b> on line <b>110</b>
bool(false)
The key "action" exists in $temp but $temp['action'] returns Undefined and array_key_exists returns false. I've tried with a different key name, but still the same. And absolutely no problem with the others keys.
What's wrong with this ?
PS: line 110 is the print_r($temp['action']);
EDIT 1
If i add another empty field in the csv at the begining of each line, action display correctly
;action;id;nom;sites;heures;jours
;i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1
Probably there is some special character at the beginning of the first line and trim isn't removing it.
Try to remove every non-word character this way:
// Identify headers
if(!isset($headers))
{
for($i=0;$i<$cols;$i++)
{
$headers[preg_replace("/[^\w\d]/","",strtolower($row[$i]))] = $i;
....
If your CSV file is in UTF-8 encoding,
make sure that it's UTF-8 and not UTF-8-BOM.
(you can check that in Notepad++, Encoding menu)
I had the same problem with CSV files generated in MS Excel using UTF-8 encoding. Adding the following code to where you read the CSV solves the issue:
$handle = fopen($file, 'r');
// ...
$bom = pack('CCC', 0xef, 0xbb, 0xbf);
if (0 !== strcmp(fread($handle, 3), $bom)) {
fseek($handle, 0);
}
// ...
What it does, is checking for the presence of UTF-8 byte order mark. If there is one, we move the pointer past BOM. This is not a generic solution since there are other types BOMs, but you can adjust it as needed.
Sorry I am posting on an old thread, but thought my answer could add to ones already provided here...
I'm working with a Vagrant guest VM (Ubuntu 16.04) from a Windows 10 host. When I first came across this bug (in my case, seeding a database table using Laravel and a csv file), #ojovirtual's answer immediately made sense, since there can be formatting issues between Windows and Linux.
#ojovirtual's answer didn't quite work for me, so I ended up doing touch new_csv_file.csv through Bash, and pasting contents from the 'problematic' CSV file (which was originally created on my Windows 10 host) into this newly-created one. This definitely fixed my issues - it would have been good to learn and debug some more, but I just wanted to get my particular task completed.
I struggled with this issue for a few hours only to realize that the issue was being caused by a null key in the array. Please ensure that none of the keys has a null value.
I struggled with this issue until I realised that my chunk of code has been run twice.
First run when index was present and my array was printed out properly, and the second run when index was not present and the notice error is triggered. That left me wondering "why my obviously existing and properly printed out array is triggering an 'Undefined index' notice". :)
Maybe this will help somebody.
I am new to the world of coding and learning PHP these days. For almost one week of research on this issue , I have almost given up on this issue. Hope to get some good insight on it from the experts.
Problem :- I have a CSV file which has information about servers. for Example :
ClientId,ProductName,Server,ServerRole,Webserver,DatabaseName
001,abc,Server1,Web,Webserver1,,
001,abc,Server2,Dabatase,,Database1
001,abc,Server3,Application,,,
002,abc,Server4,Web,Webserver2,,
002,abc,Server5,Database,,Database2,
I created a HTML page which has a simple html form which takes a server name as an input and invokes the commands written in a page called "search.php". I am able to save the user input from index form to a variable fine . But here is the real problem. I want to search that variable against this CSV file , find the client name ( column 1) related to that server ( which should be matched from column 3 ) and then , print all the lines for that client. For e.g. if I input "Server3" , I should get the first three lines as output in a table form.
I have used fgetcsv() , fgets() etc. but I dont seem to crack this. So far , the closest I have reached is printing all the lines which contain the input text (and that too not in a table form). Any help to resolve my problem would be much appreciated.
Here is my code so far:
<?php
$name = $_POST["search"];
echo "You have searched for the server <b>$name</b>";
$output = "";
$fp = fopen("D:\VMware\DSRM\Servers\Servers.csv", "r");
// Read file
$txt = fgets($fp);
while ( !feof( $fp ) ) {
// Search for keyword
if ( stripos( $txt, $name ) !== false ) {
$output .= $txt.'<br />';
}
$txt = fgets($fp);
}
echo $output;
?>
What about regex?
$input_lines = file_get_contents("theCSV");
$server = "Server3";
preg_match_all("/(\d+).*(".$server.")(.*)/", $input_lines, $clientid);
preg_match_all("/(". $clientid[1] .".*)/", $input_lines, $output_array);
Var_dump(output_array[1]);
In theory this should work :-)
It drives me crazy ... I try to parse a csv file and there is a very strange behavior.
Here is the csv
action;id;nom;sites;heures;jours
i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1
Now the php code
$required_fields = array('id','nom','sites','heures','jours');
if (($handle = fopen($filename, "r")) !== FALSE)
{
$cols = 0;
while (($row = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$row = array_map('trim',$row);
// Identify headers
if(!isset($headers))
{
$cols = count($row);
for($i=0;$i<$cols;$i++) $headers[strtolower($row[$i])] = $i;
foreach($required_fields as $val) if(!isset($headers[$val])) break 2;
$headers = array_flip($headers);
print_r($headers);
}
elseif(count($row) >= 4)
{
$temp = array();
for($i=0;$i<$cols;$i++)
{
if(isset($headers[$i]))
{
$temp[$headers[$i]] = $row[$i];
}
}
print_r($temp);
print_r($temp['action']);
var_dump(array_key_exists('action',$temp));
die();
}
}
}
And the output
Array
(
[0] => action
[1] => id
[2] => nom
[3] => sites
[4] => heures
[5] => jours
)
Array
(
[action] => i
[id] =>
[nom] => un nom a la con
[sites] => 1200|128
[heures] =>
[jours] => 1|1|1|1|1|1|1
)
<b>Notice</b>: Undefined index: action in <b>index.php</b> on line <b>110</b>
bool(false)
The key "action" exists in $temp but $temp['action'] returns Undefined and array_key_exists returns false. I've tried with a different key name, but still the same. And absolutely no problem with the others keys.
What's wrong with this ?
PS: line 110 is the print_r($temp['action']);
EDIT 1
If i add another empty field in the csv at the begining of each line, action display correctly
;action;id;nom;sites;heures;jours
;i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1
Probably there is some special character at the beginning of the first line and trim isn't removing it.
Try to remove every non-word character this way:
// Identify headers
if(!isset($headers))
{
for($i=0;$i<$cols;$i++)
{
$headers[preg_replace("/[^\w\d]/","",strtolower($row[$i]))] = $i;
....
If your CSV file is in UTF-8 encoding,
make sure that it's UTF-8 and not UTF-8-BOM.
(you can check that in Notepad++, Encoding menu)
I had the same problem with CSV files generated in MS Excel using UTF-8 encoding. Adding the following code to where you read the CSV solves the issue:
$handle = fopen($file, 'r');
// ...
$bom = pack('CCC', 0xef, 0xbb, 0xbf);
if (0 !== strcmp(fread($handle, 3), $bom)) {
fseek($handle, 0);
}
// ...
What it does, is checking for the presence of UTF-8 byte order mark. If there is one, we move the pointer past BOM. This is not a generic solution since there are other types BOMs, but you can adjust it as needed.
Sorry I am posting on an old thread, but thought my answer could add to ones already provided here...
I'm working with a Vagrant guest VM (Ubuntu 16.04) from a Windows 10 host. When I first came across this bug (in my case, seeding a database table using Laravel and a csv file), #ojovirtual's answer immediately made sense, since there can be formatting issues between Windows and Linux.
#ojovirtual's answer didn't quite work for me, so I ended up doing touch new_csv_file.csv through Bash, and pasting contents from the 'problematic' CSV file (which was originally created on my Windows 10 host) into this newly-created one. This definitely fixed my issues - it would have been good to learn and debug some more, but I just wanted to get my particular task completed.
I struggled with this issue for a few hours only to realize that the issue was being caused by a null key in the array. Please ensure that none of the keys has a null value.
I struggled with this issue until I realised that my chunk of code has been run twice.
First run when index was present and my array was printed out properly, and the second run when index was not present and the notice error is triggered. That left me wondering "why my obviously existing and properly printed out array is triggering an 'Undefined index' notice". :)
Maybe this will help somebody.
So I have my navigation based on directory files here, however it outputs the first page twice.
I currently have 6 files in my directory: index.php, 2.php, 3.php, 4.php, 5.php and 6.php
My navigation displays the page links as [1] [2] [3] [4] [5] [6] [1]
How do i prevent the index.php [1] from printing again at the end?
<?php
$pathfiles = "../directory/";
$files = glob("../directory/*.php");
$key = array_search('index.php', $files);
unset($files[$key]);
natsort($files);
array_unshift($files, 'index.php');
foreach( $files as $file ) {
echo '[<a href="'.($pathfiles).''
.basename($file).'">'.str_replace('index', '1', basename($file,".php")).'</a>] ';
}
?>
Any solutions or leads would be appreciated. Thanks in advance.
You could change the array_unshift to this:
array_unshift($files, array_pop($files));
This will basically move the last entry to the first position, see the PHP documentation for array_pop.
I'am affraid that array_search() can't find the result . Check var_dump($files) and var_dump($key).