I have form where I have three inputs for files. With code below, I try to move files from TMP localisation to ./uploads with some random hash and name of file.
I have issue with foreach because it is stopping, after first iteration and saving file to uploads directory. I do not know why it is not happening for other two elements in table. Whole function below, it is a little mess, but I hope it is understandable.
function saveFile(){
global $patchFile;
$fileArray = [ $_FILES['file_one']['name'], $_FILES['file_two']['name'], $_FILES['file_three']['name'] ];
$tmpArray = [ $_FILES['file_one']['tmp_name'], $_FILES['file_two']['tmp_name'], $_FILES['file_three']['tmp_name'] ];
$multiArray =
[
[$_FILES['file_one']['name'], $_FILES['file_one']['tmp_name']],
[$_FILES['file_two']['name'], $_FILES['file_two']['tmp_name']],
[$_FILES['file_three']['name'], $_FILES['file_three']['tmp_name']]
];
foreach ($multiArray as $key)
{
echo "<br />Key: ".$key[0]."\n";
echo "Key_tmp: ".$key[1]."\n";
$randomString = generateRandomString();
$patchFile = './uploads/'.$randomString.$key[0];
echo "<br />Check patchFile: $patchFile";
if(is_uploaded_file($key[1]))
{
echo "<br />Begin uploading to directory...<br />";
if(!move_uploaded_file($key[1], $patchFile))
{
echo 'Problem: Nie udało się skopiować pliku do katalogu.';
return false;
}
else {
echo "File was saved in uploads directory";
return true;
}
}
else
{
echo "Uploading to directory... FAILED!";
}
}
}
When you return something from a loop, the loop is always broken.
As per PHP manual:
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Related
I have written a small script which upload two csv files and compare them.
//set files upload directory
$target_dir1 = "uploads/old/";
$target_file1 = $target_dir1 . basename($_FILES["fileToUpload1"]["name"]);
$target_dir2 = "uploads/new/";
$target_file2 = $target_dir2 . basename($_FILES["fileToUpload2"]["name"]);
$uploadOk = 1;
//Upload files
if ($uploadOk == 0) {
echo "<BR> Sorry, your files were not uploaded. <BR>";
} else {
if (move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"], $target_file1)) {
echo "<BR> The 1st file ". basename( $_FILES["fileToUpload1"]["name"]). " has been uploaded. <BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 1st file. <BR>";
}
if (move_uploaded_file($_FILES["fileToUpload2"]["tmp_name"], $target_file2)) {
echo "<BR> The 2nd file ". basename( $_FILES["fileToUpload2"]["name"]). " has been uploaded.<BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 2nd file. <BR>";
}
}
//Get contetnt 1st file
$table1 = Array();
$filehandle1 = fopen($target_file1, "r") ;
if($filehandle1 !== FALSE) {
while(! feof($filehandle1)) { // feof end of file
$data1 = fgetcsv($filehandle1, 1000, ",");
array_push($table1, $data1);
}
}
fclose($filehandle1);
//Get content 2nd file
$table2 = Array();
$filehandle2 = fopen($target_file2, "r") ;
if($filehandle2 !== FALSE) {
while(! feof($filehandle2)) {
$data2 = fgetcsv($filehandle2, 1000, ",");
array_push($table2, $data2);
}
}
fclose($filehandle2);
//Find difference between these two files
$headers= array();
$headers = $table1[0];
$i= 0;
foreach ($table1 as $table) {
echo '<BR>';
$diff = array_diff($table2[$i], $table);
if(!empty($diff)) {
print_r($diff);
$chiave= key($diff);
echo $headers[$chiave];
};
echo '<BR>';
$i++;
}
And this is the error I get, however difference between the two files are dispalyed correctly:
Warning: array_diff(): Argument #1 is not an array in /var/www/csv_files/upload.php on line 67 Call Stack: 0.0053 337384 1. {main}() /var/www/csv_files/upload.php:0 0.0064 367220 2. array_diff() /var/www/csv_files/upload.php:67
You get this error because the first argument is not a array where one is expected. You are now checking a table with the nth element of a array but not the whole array. I think you are making a mistake in thinking table2 is a 2 dimensional array, and it's not. It is used a one dimensional array with nth data2 elements.
Hope this helps!
Seems yes, sometimes table2 is empty or those CSV files have different amount of rows - as result that warning.
So - you need add extra checks if $table2[$i] is not null.
Just a bit another variant from me - how to read file faster (Get content 1st and second file):
$table1 = file($target_file1);
$table2 = file($target_file2);
And then you can do same things as before, with extra tests:
if (count($table1)) {
$headers = str_getcsv($table1[0]);
foreach ($table1 as $key => $table) {
if (!isset($table2[$key])) {
echo 'Row ' . ($key+1) . ' is not exists in second CSV file.';
} else {
$diff = array_diff(str_getcsv($table2[$key]), str_getcsv($table));
// Here is code as in your example
print_r($diff);
$chiave = key($diff);
echo $headers[$chiave];
}
}
}
Good luck! :)
Trying to execute file upload through external function. It gives "Missing argument..." error but also returns the result correctly. What might be wrong?
This is form page:
<?php include '--formprocess.php'; ?>
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$upload = $_FILES['upload'];
if(formprocess($upload)) {
echo formprocess();
} else {
echo 'ERROR!';
}
}
?>
and process file:
<?php
function formprocess($upload) {
$name = $_FILES['upload']['tmp_name'];
return $name;
}
echo formprocess();
^---your missing argument
formprocess takes one argument, the first time you call it you passed an argument, the second time you did not.
$value = formprocess($upload);
if($value) {
echo $value;
}
I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}
so I am struggling with this bit of code for a project that I am working on. I do not understand why I am getting an array to string conversion error for my use of the Move_uploaded_file function below, since I implemented a foreach loop to work only with each individual element in the array. Also note that the issue- according to php's error handling- is specifically with the move_uploaded_file function, not with the other methods that get called.
Here's the relevant code. (Thanks all for the help).
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $this->getFilename())) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
you should replace $this->getFilename() with $name, $this->getFilename() returns an array if I got it right...
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
It should be
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
You're passing in $this->getFileName() to move_uploaded_file(), when you should be passing in $name, as you're already iterating over the array that $this->getFileName() is returning
my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}