foreach ($delete_addresses[$key] value failure with imap_delete() - php

In below example there is an array $delete_addresses filled with email-addresses. The print_r() show all correct.
But within the foreach I do something wrong and do not get the $key number needed for the imap_delete).
I get this not saying a lot error message:
Warning: Invalid argument supplied for foreach() in /home/deb96951n2/domains/domain.nl/public_html/wp-admin/email_handlers/bouncehandler.php on line 75
Does someone of you with more experience then me can tell me what I do wrong and how to correct it? Imap is not my daily work.
$delete_addresses = array();
$bouncecounter = 0;
$deletecounter = 0;
for ($n=1;$n<=$num_msgs;$n++) {
$bounce = imap_fetchheader($conn, $n).imap_body($conn, $n); //entire message
$multiArray = $bouncehandler->get_the_facts($bounce);
if (!empty($multiArray[0]['action']) && !empty($multiArray[0]['status']) && !empty($multiArray[0]['recipient']) ) {
echo $multiArray[0]['action'].'= '.$multiArray[0]['status'].'::'.$multiArray[0]['recipient'].'<br>';
$delete_addresses[] = $multiArray[0]['recipient'];
if ($multiArray[0]['action'] == 'failed') {
$result = mysqli_query($db, "UPDATE wp_mm_external_emails set deleted = 1 WHERE email = '".$multiArray[0]['recipient']."' ");
} //if delivery failed
$deletecounter++;
} //if passed parsing as bounce
$bouncecounter++ ;
} //for loop
foreach ($delete_addresses as $key => $value) { //trim($key) is email address, $value is number of failures
if ($value>=$delete) {
/*
do whatever you need to do here, e.g. unsubscribe email address
*/
# mark for deletion
print_r($delete_addresses[$key]);
foreach ($delete_addresses[$key] as $delnum) imap_delete($conn, $delnum);
} //if failed more than $delete times
} //foreach

Related

Php: Delete string from text file [duplicate]

This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I need to delete a specific string set from a txt file. Currently, the code works in a similar manner to post the data directly to the file. However, trying to remove the same data, inputted in the same manner, will not allow it. In it's current state, the code looks like this for the string removal.
We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code.
Here is the current code for the string removal:
$blankReplace = "";
$found = false;
$fileData = file($fileInput,FILE_IGNORE_NEW_LINES);
for($i = 0; ($i < count($fileData)) && != $found; $i ++)
{
if($fullNameAndEmail == $fileData[$i])
{
$pos = $i;
$name = $fileData[$i];
$found = true;
}
}
if($found == true)
{
// Exit path. Go to for($j = 0) path
unset($fileData[$pos]);
shuffle($fileData);
}
else
{
//Error Msg
}
$writeToFile = fopen($inputFile,'w+');
for($j = 0;$j<count($fileData);$j++)
{
if(trim($fileData[$j]) != " ")
{
$rewrittenList = trim($fileData[$j])."\n";
fwrite($writeToFile, $rewrittenList);
}
}
The code outputs an error of T_IS_NOT_EQUAL in code upon researching the error. The data comes in as direct data from the file() read, so it should work. The error is pointing at for($i = 0; ($i < count($fileData)) && != $found; $i ++) line currently, but likely also references a similar occurrence in the code.
The data is inputted in the format:
firstname lastname emailaddress
I also need to be able to handle if multiple instances of the mentioned name occur so say we have:
Matt Person emailaddr#email.com
Matt Person emailaddr#email.com
That it will delete one instance, and not all, in cases similar to this.
Any help is appreciated, Thank you for your time in advance.
EDIT:
Example input:
Matthew person person#email.com
John holton person#email.com
Person Name person#gmail.com
The user will input a person's name (in format above) and it will result in removing a person. Say they input into the form:
$fullName = "Matthew person";
$emailAddr = "person#email.com";
The output will edit the data to put the data into a single line again
$fullNameAndEmail = $firstName." ".$lastName." ".$emailAddr;
The output of the code, in this example will remove "Matthew person person#email.com"
So the output in the text file will output:
John holton person#email.com
Person Name person#gmail.com
Edit 2: Code in it's current state
<!doctype HTML>
<html>
<meta charset="utf-8">
<head>
<title>Updating the guest book!</title>
</head>
<body>
<?php
$fileInput = "guestBook.txt";
$fileInputInData = file_get_contents($fileInput); // Gets data from file
$testBool = file_exists($fileInput);
$fullName = trim($_POST["fullName"]);
$emailAddr = trim($_POST["emailAddr"]);
$fileSize = filesize($fileInput);
if(!empty($fullName) and !empty($emailAddr))
{
if($testBool == 0)
{
echo "There was an issue with the file. Please have it checked.</br>";
}
else
{
echo "Made it into else path for testBool </br>";
if($fileSize > 0)
{ #code for truth
echo "Made it into filesize check. Filesize: $fileSize </br>";
$fullNameLen = strlen($fullName);
$emailAddrLen = strlen($emailAddr);
$fullNameArr = explode(" ", $fullName);
$firstName = trim($fullNameArr[0]);
$lastName = trim($fullNameArr[1]);
$fullNameToWrite =$firstName." ".$lastName;
$emailAddrCheck=substr_count($emailAddr, "#");
if ($emailAddrCheck == 1)
{
echo "Email address check passed</br>";
#email addr entered right path
$fullNameAndEmail =$fullNameToWrite." ".$emailAddr." has signed in.\n";
$inputFile = "guestBook.txt";
//$pos = strpos($writeToFile, $fullNameAndEmail);
//$writeToFileEx = explode("\n", $fileInputInData);
$blankReplace = "";
$str = $fileInputInData;
$find = $fullNameAndEmail;
$arr=explode("\n", $str);
Foreach($arr as $key => &$line)
{
If($line == $find)
{
Unset($arr[$key]);
shuffle($arr);
}
}
$writeToFile = fopen($inputFile,'w+');
$rewrittenList = trim($arr)."\n";
fwrite($writeToFile, $rewrittenList);
fclose($inputFile);
}
else {
echo "Email address check failed. Invalid email address entered. </br>
Line 55 occured.</br>";
#email addr entered wrong message
}
//asort(array) sorts array low to high (ascending)
//arsort(array) sorts array high to low (descending)
}
else
{
echo "Did not make it into filesize check. Filesize: $fileSize. Line 63 occured </br>";
}
}
}
else if (empty($fullName) or empty($emailAddr))
{
echo "Error! Line 23: One of the inputs was left empty. Line 69 occured </br>";
}
else
{
echo "Error! Line 23: Did not detect any values in either data area,</br>and program
did not go into first error. Line 73 occured </br>";
}
?>
<br>
</body>
</html>
I think you have overcomplicated it.
I foreach each line and check if it matches.
If it does I unset the line.
After the loop I implode on new line and the string is back to normal but without the $find's.
$str = "Matt Person emailaddr#email.com
John doe doesoe#gmail
Matt Person emailaddr#email.com
Trump donald#whitehouse";
$find = "Matt Person emailaddr#email.com";
$arr=explode("\n", $str);
Foreach($arr as $key => &$line){
If($line == $find){
Unset($arr[$key]);
}
}
Echo implode("\n", $arr);
https://3v4l.org/hmSr7

Verifying multiple emails from array

I have a query that I am not too sure how I can make it work
I have a form where the end users can add multiple email fields using jquery and it places each text input into an array
I have created some code that verifies each array key and fills an array with a number for verification purposes
Here is the code for verifying the POST:
// Collect and verify attached email
if(isset($_POST["email"])){
// set var for collecting email and store as null
$emailfields ="";
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
}
// Create a string for later
$emailfields .= $email .",";
}
// Verify Array contains value
if (!in_array('1', $emailcheckarray, true))
{
$emailverification = 1;
} else {
$emailverification = 0;
}
}
echo $emailfields;
echo $emailverification;
Now this works it fills the array $emailcheckarray with 1 1 1 1 1 if the emails are valid depending on how many inputs the user uses.
Is there a way that I can get the in_array to only work with all keys being the same as currently if one of the keys are 0 it still outputs $emailverification as 1 if the user enters 1 valid email and the rest invalid when I want it to be 0.
You can just omit the in_array if you set the verification to 0 during the loop when any of the checks fails. So start with a value of 1 as you have no failures yet:
$emailverification = 1; // added
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
$emailverification = 0; // added
}
// Create a string for later
$emailfields .= $email .",";
}
... and then at the end of the loop you have the correct value.
You can use functions such as array_map and array_filter to get an array of all the valid emails.
if (isset($_POST['email'])) {
$sanitized_emails = array_map(function ($email) {
return filter_var($email, FILTER_SANITIZE_EMAIL);
}, $_POST['email']);
$valid_emails = array_filter($sanitized_emails, function($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
$emailfields = implode(',', $sanitized_emails);
}
Then you just have to compare the size of the two tabs.
$emailverification = 0;
if (count($emails) == count($valid_emails)) {
$emailverification = 1;
}
Check the affirmative for zero:
if (in_array('0', $emailcheckarray, true)) {
$emailverification = 0;
} else {
$emailverification = 1;
}
If you don't have any zeros, that means they're all ones.

PHP ForEach loop doesn't iterate / count

I'm trying to return a value to an android application in JSON format using a web service. For some reason, my code is only returning "Invalid login, please try again". I'm positive that the username is being entered, and I'm positive the tasks are returning properly. Using test code, which I've included as commented lines, I verify that the service will return one set of data to the application. It appears that the problem is with my foreach loop, but I don't see how. It's pretty simple stuff. Obviously it isn't iterating, or my count would be increasing and I wouldn't receive the Invalid Login error. The only thing I can figure is that I would need to use a nest foreach loop, but I haven't had much success with that, either.
Thanks in advance for the help, guys!
Here is the foreach loop...
//for reach task returned, add to array for later output
foreach ($row2['Description'] as $t)
{
$taskDisplay = array('task' => $t);
$taskCount++;
}
and the count...
if ($taskCount > 0)
{
echo json_encode($taskDisplay);
}
else
{
echo "Invalid login, please try again";
}
here is the code in full
$taskDisplay = array();
$taskCount = 0;
//do this portion if app gives key value "PART_ONE"
if ($result['part'] == "PART_ONE")
{
//if username was entered, check user credentials
if(array_key_exists('user', $result)) {
$usercheck = $con->prepare("Select * from Employee
Where usr = ?
and pass = ?");
$usercheck -> execute(array($result['user'], $result['password']));
$row = $usercheck -> fetch();
//if username was verified, select tasks from database
if($row['usr'])
{
$task = $con->prepare("Select * from Tasks
where Assigned_Employee = ?");
$task -> execute(array($result['user']));
$row2 = $task -> fetch();
$statusCode = "Success";
//$taskDisplay = $row2['Description'];
//for reach task returned, add to array for later output
foreach ($row2['Description'] as $t)
{
$taskDisplay = array('task' => $t);
$taskCount++;
}
}
else
{
$statusCode = "Fail";
//bail if invalid username entered
exit;
}
//$arr = array('task' => $taskDisplay, 'status_code' => $statusCode);
//echo json_encode($arr);
if ($taskCount > 0)
{
echo json_encode($taskDisplay);
}
else
{
echo "Invalid login, please try again";
}
}
}
To foreach over all rows you'll want fetchAll(). Then you want to access the Description column in each row:
$row2 = $task->fetchAll();
// etc...
foreach ($row2 as $t)
{
$taskDisplay[] = array('task' => $t['Description']);
$taskCount++;
}

PHP foreach invalid argument supplied

I'm trying display error messages on a form but only one is displayed (the last one always). I tried using a foreach loop but I keep getting the invalid argument error. The following displays errors one by one. Code is inside a class...
public $errorContainer = '';
// ------------------------------------------------------------
// ERROR MESSAGE PROCESSING
// ------------------------------------------------------------
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
$this->errorContainer = $respMessage;
}
}
The following always gives me the invalid for each argument error.
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
foreach ($respMessage as $value) {
$this->errorContainer = $value;
}
}
}
Thank you!
replace your foreach() with this:
private function responseMessage($respBool, $respMessage) {
// ...code...
foreach ((array) $respMessage as $value) {
$this->errorContainer .= $value;
}
// ...code---
}
Using type casting (array) above will make it works for both array and string type.
Edit:
Use this solution (type casting) only in your last effort. But your real problem is you're not passing an array to the function. See this code:
// incorrect
$msg = 'This is a message';
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message');
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message', 'And another message');
$this->responseMessage($some_bool, $msg);
If you pass the argument correctly like above, you don't need to cast $respMessage to array.

Troubleshooting "Undefined offset" error

It's show following error:
Notice: Undefined offset: 1 in C:\xampp\htdocs\evantechbd\secure\content\feature_link_process.php on line 28.
Why it's show the error...? Can anyone tell me... Here is the code:
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if(isset($coun)){
$errors = array();
if(empty($coun))
$errors[] = 'Country Name require<br>';
}
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if $_POST['coun_name] has no | than $row[1] is not defined.
You will probably want to do something like this, instead:
$errors = array();
if( empty($_POST['coun_name']) )
{
$errors[] = 'Country Name required.';
}
elseif( strpos($_POST['coun_name'], '|') === false )
{
$errors[] = 'Country Name invalid.';
}
else
{
list($coun_name, $coun_id) = explode("|", $_POST['coun_name'], 2);
}
The first condition checks to make sure the user submitted a value for $_POST['coun_name']. The second condition checks to make sure that the value contains a '|' character.
If both conditions are met, $coun_name and $coun_id are populated by explode()'ing $_POST['coun_name'] as normal (I dropped in a call to list() for brevity).

Categories