imap_search() with for() will not search for sender - php

The loop ($zeile[$i]) will not be executed, when it is in the imap_search() function.
The syntax ($inbox, 'FROM " ' . $zeile[$i] . ' " ') is like a lot of examples I have found.
Outside of this codeblock it works well.
But inside even the line on the bottom (echo "#" .$zeile[$i]."<br>";) will not show anything.
With a single var ($test = "domain.de";) it works though.
$test = "domain.de";
$zeile = file("blacklist.txt");
for ($i=0;$i < count($zeile); $i++) {
$emails = imap_search($inbox, 'FROM " ' . $zeile[$i] . ' " ');
if ($emails) {
foreach ($emails as $email_number) {
imap_setflag_full($inbox, $uid, "\\Seen", ST_UID);
echo "#" .$zeile[$i]."<br>";
}
} // if emils
} //Dateischleife
imap_close($inbox, CL_EXPUNGE);

okay, I found the problem.
The first email address from the text file determines the number of $ mails and thus the number of loops of if ($ mails). After that, there is no turning back to the line above.

Related

Handling empty lists in PHP SOAP

Initially if there was one item in the list it would return an object rather than an array of one object. I fixed that using:
https://eirikhoem.wordpress.com/2008/03/13/array-problems-with-soap-and-php-updated/
$x = new SoapClient($wsdl, array('features' => SOAP_SINGLE_ELEMENT_ARRAYS));
But I'm having problems when there is no items in the list.
The best I've come up with so far is:
$occulist = $result->GetWebOccurrencesResult->OccuList;
if (!empty((array)($occulist))) {
foreach($occulist->TOccu as $occurrence) {
echo $occurrence->Prog_Name . ' running from ' . $occurrence->StartDate . ' to ' . $occurrence->EndDate . '<br/>';
}
}
Originally it was
foreach($result->GetWebOccurrencesResult->OccuList->TOccu as $occurrence) {
I don't understand exactly what you're trying to achieve here, so if you can clarify in the comments, that'd be great.
What I'm taking from your question is that you want to handle when the array is empty, but want a clean method to do so? The loop you have there would do what you require, but here is another alternative:
do {
foreach($occulist->TOccu as $occurrence) {
echo $occurrence->Prog_Name . ' running from ' . $occurrence->StartDate . ' to ' . $occurrence->EndDate . '<br/>';
}
} while(empty((array)($occulist)) !== FALSE);
So you're looping through the foreach while the $occulist array isn't empty.
You could even do:
while((array)$occulist !== FALSE) {
foreach(....) {
...
}
}
On my server with Windows and PHP 5.4.23 this:
if (!empty((array)($occulist))) {
gives the following error:
Parse error: syntax error, unexpected '(array)' (array) (T_ARRAY_CAST)
I fixed it using:
if (get_object_vars($occulist)) {
I think that is a more elegant alternative to the original...

adding a line feed when building a string php

i have been looking all over and i cant find the answer. i am sure this is easy
i am sending an email, and in the body are names of clients
the code looks for clients that fit the search conditions and as each one is found it goes into a loop
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . ???
}
the result should be
Client1
Client2
Client3
but what i keep getting is:
Client1Client2Client3
I have tried
$clients = $clients . $first_name . lf;
$clients = $clients . $first_name . cr;
$clients = $clients . $first_name . '\n';
but always the same result
TIA
If your output will be the command line, file, etc. Use PHP_EOL. If it will be a web browser use <br>:
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . PHP_EOL;
}
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . "<br/>";
}
For text e-mails, the simplest case would be:
$clients = $clients . $first_name . "\n";
Note that you need to enclose \n in double (") instead of single (`) quotes, so that it gets treated as a new line character.
If you are sending HTML e-mails, then you'll need the appropriate HTML tag, i.e. <br>
You can use "\n" or PHP_EOL (single quoted strings like '\n' are not interpolated)
$clients = $clients . $first_name . PHP_EOL;
If you're outputting this to the browser, newline characters are not displayed in html, so you can do something like this:
print nl2br($clients);
Or this:
header('Content-type: text/plain');
print $clients;`
Or this:
printf('<pre>%s</pre>', $clients);

PHP : Second Function not being called

I am using PHP and want to run 2 functions, one after the other.
These functions are getallmydata() and createCSV()
The code below runs the first function fine but the second function createCSV() is not working. It seems like it is not being called properly.
Is there anything wrong with the structure of my code as both functions work correctly independently? I cannot work this out!
<?php
//run this function//
getallmydata();
//then run this function//
createCSV();
function getallmydata(){
require_once dirname(__FILE__).'/cm/csrest_general.php';
require_once dirname(__FILE__).'/cm/csrest_clients.php';
require_once dirname(__FILE__).'/cm/csrest_campaigns.php';
$api_key = 'MY API KEY';
$wrap = new CS_REST_General($api_key);
$result = $wrap->get_clients();
$Content = "";
if ($result->was_successful()) {
foreach ($result->response as $client) {
$client_wrapper = new CS_REST_Clients($client->ClientID, $api_key);
$client_details_result = $client_wrapper->get();
$campaigns_result = $client_wrapper->get_campaigns();
if ($client_details_result->was_successful()) {
/* This is where the client details will be */
$client_details = $client_details_result->response;
echo ('<pre>');
/*print out the company name*/
echo "Company Name = " . $client_details->BasicDetails->CompanyName . "<br/>";
/*print out the company markup*/
echo "Markup On Delivery = " . $client_details->BillingDetails->MarkupOnDelivery . "<br/>";
$count = 0;
if ($campaigns_result->was_successful()) {
/*print out the latest campaign name of the current campaign*/
foreach ($campaigns_result->response as $campaign_ob) {
echo 'Latest Campaign Name = ' . $campaign_ob->Name . '<br/>';
//echo 'Latest Subject = ' . $campaign_ob->Subject . '<br/>';
//echo 'Total Recipients = ' . $campaign_ob->TotalRecipients . '<br/>';
//echo 'Sent Date = ' . $campaign_ob->SentDate . '<br/>';
/*Set content for CSV File*/
//$Content .= "This is within the loop \n";
$count++;
if($count > 0) break;
}/*end loop*/
}/*end campaigns if statement*/
echo ('</pre>');
} else {
echo 'Failed with code '.$client_details_result->http_status_code."\n<br /><pre>";
var_dump($client_details_result->response);
}
}
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo ('</pre>');
}
} //end main function
/*create the downloadable csv file*/
function createCSV(){
$FileName = date("d-m-y") . '.csv';
# Titlte of the CSV
//$Content = "Company_Name Markup Campaign_Name Subject Recipients Date \n";
# fill data in the CSV
//$Content .= "\"John Doe\",\"New York, USA\",15,65465464 \n";
$Content .= "Testing The Function Works OK \n";
//$Content .= "This should be another line";
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}//end csv download function
/*end create downloadable .csv file */
?>
I think you should get the error: headers already sent. (you checked that the second function is called right? You can find it out by placing a echo on the first line of the function.)
You are trying to create a CSV page but you are parsing HTML in the first function, so the header is already sent to the client saying that it is a normal HTML page. Remove these echo's in the first function and it should work.
Quote of the PHP manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
More info about headers: PHP header
First think I would tell you is
1 you should first write function definition and then you should call a function
i.e
function getallmydata(){
// function code
}
function createCSV(){
// function code
}
getallmydata();
createCSV();
2 . The second thing is that check that is there any white space left in the code out side php code or any o/p that is sent as resonse as because when ever you user header() at that if any kind of content other than header() is sent as response then header() function fails. Try this things and check again.

New line does not display when getting jira issue using php soap

I am trying to get issue details from JIRA 3.13 using PHP SOAP. I was able to login and get the issues; however, on one of my field, I could not get the new line formatting. So, all I got is the text for that particular field without new line character (everything just append into a single line of text). As of now, I am guessing php also did some re-formatting of the string from SOAP. The reason I am saying this is because I did some testing with SOAP UI and was able to get the text out with the formatting. Can anyone help me out with a way to displaying the text with the formatting? Thanks in advance.
This is my php code:
try {
$soap = new SoapClient("<<JIRA URL>>");
$auth = $soap->login($formUsername, $formPassword);
if ($auth)
{
$result0 = $soap->getIssue($auth,'<<JIRA ISSUE ID>>');
$result = (array) $result0;
foreach ($result as $key => $a)
{
$z = $z . '<br/>' . $key . ' = ' . $a;
}
echo $z;
}
}
catch(Exception $e){
$string = urlencode($e->getMessage());
header("Location: login.php?message=".$string);
die();
}
I just realize that I do not need to convert it into array.
Simply do the following:
foreach ($result0 as $key => $a)
{
$z = $z . '<br/>' . $key . ' = ' . $a;
}
This, however, still does not solve my problem with the new line.
Isn't it just because you don't change the linefeeds into <br/> before outputting it?
Should be easy to find out if that's the case just by looking at the source in the browser.
You need nl2br() to convert newline characters (\n et. al) into HTML <br> tags:
foreach ($result0 as $key => $a)
{
$z = $z . '<br/>' . $key . ' = ' . nl2br($a);
}
Could be that the text is stored with Unix line endings and you're displaying on a Windows machine? Which field is having the problem?

php imap get from email address

How do I retrieve the email address from an email with imap_open?
If the sender name is known I get the sender name instead of the email address if I use the 'from' parameter.
Code: http://gist.github.com/514207
$header = imap_headerinfo($imap_conn, $msgnum);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
I battled with this as well but the following works:
// Get email address
$header = imap_header($imap, $result); // get first mails header
echo '<p>Name: ' . $header->fromaddress . '<p>';
echo '<p>Email: ' . $header->senderaddress . '<p>';
I had used imap_fetch_overview() but the imap_header() gave me all the information I needed.
Worst case, you can parse the headers yourself with something like:
<?php
$headers=imap_fetchheader($imap, $msgid);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $headers, $matches);
?>
$matches will contain 3 arrays:
$matches[0] are the full-lines (such as "To: user#user.com\r\n")
$matches[1] will be the header (such as "To")
$matches[2] will be the value (user#user.com)
Got this from: http://www.php.net/manual/en/function.imap-fetchheader.php#82339
Had same issue as you....had to piece it together, don't know why it's such gonzoware.
Untested example here:
$mbox = imap_open(....)
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$header = imap_headerinfo ( $mbox, $msg);
echo '<p>Name / Email Address: ' . $header->from[0]->personal ." ".
$header->from[0]->mailbox ."#". $header->from[0]->host. '<p></br>';
}
imap_close($mbox);
imap_fetch_overview could be what you're looking for: http://www.php.net/manual/en/function.imap-fetch-overview.php
An example of use can be found here: http://davidwalsh.name/gmail-php-imap, specifically
echo $overview[0]->from;
This function is simple, but has limitations. A more exhaustive version is in imap_headerinfo ( http://www.php.net/manual/en/function.imap-headerinfo.php ) which can return detailed arrays of all header data.
Had trouble until I spotted that the $header is an array of stdClass Objects. The following 2 lines worked:
$header=imap_fetch_overview($imap,$countClients,FT_UID);
$strAddress_Sender=$header[0]->from;
Full working code with an online example
Extract email addresses list from inbox using PHP and IMAP
inbox-using-php-and-imap
I think all you need is just to copy the script.
I am publishing two core functions of the code here as well (thanks to Eineki's comment)
function getAddressText(&$emailList, &$nameList, $addressObject) {
$emailList = '';
$nameList = '';
foreach ($addressObject as $object) {
$emailList .= ';';
if (isset($object->personal)) {
$emailList .= $object->personal;
}
$nameList .= ';';
if (isset($object->mailbox) && isset($object->host)) {
$nameList .= $object->mailbox . "#" . $object->host;
}
}
$emailList = ltrim($emailList, ';');
$nameList = ltrim($nameList, ';');
}
function processMessage($mbox, $messageNumber) {
echo $messageNumber;
// get imap_fetch header and put single lines into array
$header = imap_rfc822_parse_headers(imap_fetchheader($mbox, $messageNumber));
$fromEmailList = '';
$fromNameList = '';
if (isset($header->from)) {
getAddressText($fromEmailList, $fromNameList, $header->from);
}
$toEmailList = '';
$toNameList = '';
if (isset($header->to)) {
getAddressText($toEmailList, $toNameList, $header->to);
}
$body = imap_fetchbody($mbox, $messageNumber, 1);
$bodyEmailList = implode(';', extractEmail($body));
print_r(
',' . $fromEmailList . ',' . $fromNameList
. ',' . $toEmailList . ',' . $toNameList
. ',' . $bodyEmailList . "\n"
);
}

Categories