First time doing this. I am having a tough time trying to complete this. Three days on this now. I transitioned the php Twilio/sdk over to Laravel and have successfully sent a text with Twilio's api to my phone. I am now figuring out how to receive the reply text.
(I tried the laravel packages for this and they only send the text, not receive the reply)
I am getting an error on my code.
Undefined index: From
If I move the header to my view I get a whoops error.
I also tried replacing the REQUEST with
$name = in_array(Input::get('name'), $people) ? Input::get('name') : 'default';
Here is my receiving function
public function getReceiveSMS() {
// make an associative array of senders we know, indexed by phone number
$people = array(
"1111111111"=>"Curious George",
"1111111111"=>"Boots",
"1111111111"=>"Virgil",
"1111111111"=>"Stephen",
);
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!$name = $people[$_REQUEST['From']]) {
$name = "Monkey";
}
// now greet the sender
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
return View::make('account.sms.receive-sms');
}
}
Here is my view
#extends('layout.main')
#section('content')
<Response>
<Message><?php echo $name ?>, thanks for the message!</Message>
</Response>
#stop
I don't know about Twilio's API, but it seems the error is just basic PHP, and you're being held back by the fact that Laravel is far less lenient than regular PHP, meaning undefined variables and indexes will halt processing just like a fatal error would.
If in fact the sender can be unknown, and when that does happen the From index won't ever be set, the following should prevent your code from triggering a Notice:
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!isset($_REQUEST['From']) || !$name = $people[$_REQUEST['From']]) {
$name = "Monkey";
}
As for your malformed XML, try this instead of a simple View::make():
return Response::view('account.sms.receive-sms', compact('name'))->header('Content-Type', 'text/xml');
Related
I want to have a variable that contain url address such as this example
when I open http://localhost/test?alfa=b&bravo=c#question=Z
I want to print on my web the "question=Z"
I try to get by using REQUEST_URI
$url=$_SERVER['REQUEST_URI'];
The browser just show "/test?alfa=b&bravo=c" without "question=Z"
Could somebody helped me with this issue?
Thanks Before
After research on php and java, I can get the #hashtag by combine php n java
here put javascript :
<script type="text/javascript">
var test = window.location.hash.replace("#","$");
document.cookie = 'tag=' + test;
</script>
And last, put this php to take the variable
<?php
$hashtag = $_COOKIE["tag"]; $hashtag = substr($hashtag,11,1000);
?>
I put 1000 because I limit the input question max 1000 character
Maybe you just made an error and what you actually mean is:
http://localhost/test?alfa=b&bravo=c&question=Z
Then your error would just be a typo.
Otherwise, there is no solution to that. Everything including and bafter the # is never actually transmitted to the server. It is evaluated locally on the browser.
The Server only sees the Domain, the URI and teh query string.
Regards,
Stefan
use this kind of URL
http://localhost/test?alfa=b&bravo=c&question=Z
then in php you can catch them by
$alfa = $_GET['alfa'];
$bravo = $_GET['bravo'];
$question = $_GET['question'];
to catch
<?php
if( $_GET["alfa"] || $_GET["bravo"] )
{
echo "I'm ". $_GET['alfa']. "<br />";
echo "I'm ". $_GET['bravo'];
exit();
}
?>
or
<?php
if( !empty($alfa) || !empty($bravo) )
{
echo "I'm ". $alfa. "<br />";
echo "I'm ". $bravo;
exit();
}
?>
About GET
The GET method produces a long string that appears in your server
logs, in the browser's Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive
information to be sent to the server.
GET can't be used to send binary data, like images or word
documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING
environment variable.
The PHP provides $_GET associative array to access all the sent
information using GET method.
PHP - GET & POST Methods
HTTP Methods: GET vs. POST
What else is needed to:
make this php script send an auto-response back?
sanitize and check the phone number and email that is not junk as my current formmail from dbmasters I get junk like dasawewdjz89)$%&*_sasa779%7fmsdls in almost every field including the input areas.
It is mentioned to take out the bcc and cc code, yet, I had code to sent to a different recipient based on the state, so is there a way to keep the bcc and cc fields too without compromising security?
Maybe this is 3 questions in 1, but this is essentially building upon the answer here
Replacing deprecated eregi() with stristr(). Is this php mail script secure from header injections? since it is a deprecated form and I get error logs each day now.
I believe I only need validation on input fields NOT select or radio fields, right?
I am an html/css guy so would this actual code go into the php page or as a separate contact.php page.
EDIT: The script I cannot post for some reason here with the code given (like in other forums). so I made a link to it in BOLD
..Validate without Javascript
To answer your questions:
Question 1: Don't quite understand what you mean here. Once you are in your script you can send output to the screen, generate and email, etc. This question is very vague.
Question 2: You can use regular expressions to validate various pieces of information. For example this will check a phone number in the format of XXX-XXX-XXXX and tell you if it is valid.
function validatePhone($number)
{
$test = "/^\d{3}-\d{3}-\d{4}$/";
return (preg_match($test, $number) != 0) ? true : false;
}
var_dump(validatePhone("815-555-1234"));
var_dump(validatePhone("8158791359"));
var_dump(validatePhone("blah blah 209#&$#)(##1;llkajsdf"));
This will produce:
bool(true)
bool(false)
bool(false)
Keep in mind this function is far from robust. Valid phone numbers in different formats will fail (e.g. 815 555-8846), so you will need to adjust the regexp or craft multiple regexps to meet your needs. But that should be enough to illustrate the process.
Question 3: For email, I don't really see how the BCC and CC fields are going to compromise security. What you need to focus on in that area is preventing email header injections.
Spammers have recently been using mail header injection to send spam e-mail from contact forms that have in the past viewed as secure.
If you are a webmaster you can edit your forums to ensure they are secure and safe from spammers
Anyway, I have several websites that all use a common contact form. Every contact form posts to the same script.
This is how I defend against header injections. (I typically use this script as an include file)
This script requires your html form to use action="post". Make sure this is only used on the script that the html form will be posted to. If you use this script on a regular page request, it will die().
More error checking should be done when testing posted values for bad strings. Possibly a regular expression.
<?php
// First, make sure the form was posted from a browser.
// For basic web-forms, we don't care about anything
// other than requests from a browser:
if(!isset($_SERVER['HTTP_USER_AGENT'])){
die("Forbidden - You are not authorized to view this page");
exit;
}
// Make sure the form was indeed POST'ed:
// (requires your html form to use: action="post")
if(!$_SERVER['REQUEST_METHOD'] == "POST"){
die("Forbidden - You are not authorized to view this page");
exit;
}
// Host names from where the form is authorized
// to be posted from:
$authHosts = array("domain.com", "domain2.com", "domain3.com");
// Where have we been posted from?
$fromArray = parse_url(strtolower($_SERVER['HTTP_REFERER']));
// Test to see if the $fromArray used www to get here.
$wwwUsed = strpos($fromArray['host'], "www.");
// Make sure the form was posted from an approved host name.
if(!in_array(($wwwUsed === false ? $fromArray['host'] : substr(stristr($fromArray['host'], '.'), 1)), $authHosts)){
logBadRequest();
header("HTTP/1.0 403 Forbidden");
exit;
}
// Attempt to defend against header injections:
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
// Loop through each POST'ed value and test if it contains
// one of the $badStrings:
foreach($_POST as $k => $v){
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
logBadRequest();
header("HTTP/1.0 403 Forbidden");
exit;
}
}
}
// Made it past spammer test, free up some memory
// and continue rest of script:
unset($k, $v, $v2, $badStrings, $authHosts, $fromArray, $wwwUsed);
?>
Scenario: I have a number of Codeigniter applications that I am improving the email delivery system to use a database queue. So my application logs all emails that need to be sent into the database. I run a cron job every minute to check this database queue and send out any pending emails (throttled to my server limits as needed).
It is all working fantastically and has dramatically improved our applications.
Part of the feature is it will record when emails are not sent, and will retry again later. As part of the process I update the database to include any error messages during the send attempts, for debugging later. I do this with $this->email->print_debugger().
Once again all working ok (normally).
The problem is if an attachment was included in the email, the attachment 'data' is dumped as part of the print_debugger() - so my database gets smashed with large text dumps of attachment data.
What I tried: So I went looking in the Email.php class of codeigniter, thinking I could extend the library to just not include the attachment data in the print_debugger() function - but it seems that the error that is returned from the function is actually from the SMTP server itself in another function. I cant see a way to stop the attachment data coming through on the error.
Question/Challenge: Can anyone see a way where I can capture an SMTP error, and the email headers - but not the attachment data? I'm happy to settle for not capturing any of the email body either (since I know what that is anyway in my database queue).
I believe that you can just extend the library. This is the current function:
public function print_debugger()
{
$msg = '';
if (count($this->_debug_msg) > 0)
{
foreach ($this->_debug_msg as $val)
{
$msg .= $val;
}
}
$msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
return $msg;
}
There are four main parts to what is returned:
_debug_msg - The debug messages
_header_str - The email's headers
_subject - The email's subject
_finalbody - The body of the message and the attachment data
Implementing a similar function, without _finalbody should give you the desired output but without the body and attachment data.
Here's an example solution, (with the class 'MY_Email' located here at: application/libraries/MY_Email.php):
class MY_Email extends CI_Email
{
public function my_print_debugger()
{
$msg = '';
if (count($this->_debug_msg) > 0)
{
foreach ($this->_debug_msg as $val)
{
$msg .= $val;
}
}
$msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".'</pre>';
return $msg;
}
}
Looking through the code for the class, I think that $_body may contain the body data without the attachment data, so it could be worth trying to append $this->_body, rather than $this->_finalbody to the function. I've haven't tested this, so I'm not certain.
Hopefully this helps!
I'm using the Zend_Mail_Message class to display emails inside of my PHP app, and am able to output the subject, content, date and even the NAME of the sender (using $message->from) but I can't figure out how to get the email address of the person who sent the message. The documentation is no help and googling finds a million results for how to send messages with Zend, but nothing about getting the address that sent the message.
EDIT:
This is how I ended up doing it. After some more digging, I found the sender's email in a field called 'return-path'. Unfortunately, this field has a dash in the name (WTF??) so to access it, I had to do this:
$return_path = 'return-path';
$message->reply_to = $zendMessage->$return_path;
Using the return-path caused some problems with some emails, specifically messages from no-reply accounts (mail-noreply#gmail.com, member#linkedin.com etc). These addresses would end up looking something like this:
m-9xpfkzulthmad8z9lls0s6ehupvordjdcor30geppm12kbvyropj1zs5#bounce.linkedin.com
...which obviously doesn't work for display in a 'from' field on the front-end. Email clients like Apple Mail and Gmail show mail-noreply#gmail.com or member#linkedin.com, so that's what I was going for too.
Anyways, after some more research, I discovered that the 'from' field in a Zend Mail Message object always looks something like this:
"user account name" <user#email.com>
The part in < > is what I was after, but simply doing $from = $zend_message->from only gave me the user's account name (hence my original question). After some more playing around, this is how I finally got it working:
$from = $zendMessage->from;
$start = strpos($from, '<');
$email = substr($from, $start, -1);
$result = str_replace('<', '', $email);
Hopefully this will save someone some frustration. If anyone knows of a simpler way of doing this, please let me know.
This works well..
$senderMailAddress = null;
foreach ( $message->getHeader('from')->getAddressList() as $address ) {
if ( $senderMailAddress === null) {
$senderMailAddress = $address->getEmail();
}
}
The main problem here is that many email programs, relay agents and virus scanner along the way do funny stuff to an actually simple and well defined email standard.
Zend_Mail_Message extends to Zend_Mail_Part which has a method called getHeaders(). This will have all the data from an email stored in the head versus the body which is accessed with getContent() and the actual email message.
With this method you'll get an array of all the key/value pairs in the header and while developing you should be able to determine which header field you will actually want. Once you know that you can then get the actual field with getHeader('field_name') or with its actual name directly.
However, if you have to many different email senders you may want to stick with the complete header array though and evaluate multiple fields for the best result like if there's an "reply-to" address. Again there are many uncertainties because the standard isn't always obeyed.
I am using zend. I have the following piece of code,
....
$cust = 'test#test.com';
$list.='Also Sent Mail to following members';
foreach($m_list as $value)
{
$mail_to_manu = new Zend_Mail('utf-8');
$mail_to_manu->clearFrom();
$mail_to_manu->setBodyHtml('Text')
->setFrom('noreply#test.com', 'test admin')
->addTo($value['email'])
->setSubject('Test');
$mail_to_manu->send();
$list.=$value['manufacturers_email'].'<br/>';
}
$this->_helper->flashMessenger->addMessage('Mail send to '. $cust. ' Successfully'.$list);
$this->_redirector->gotoUrl('/index');
.....
I got message with out any break.my message looks like,
Mail send to test#test.com Successfully Also Sent Mail to following members some1#example.com some2#example.com...
I need to my message will be like,
Mail send to test#test.com Successfully
Also Sent Mail to following members,
some1#example.com
some2#example.com
...
So i need some break one after another.Is it possible to do that in Flash messenger. If yes,Kindly Advice.
Are you using strip_tags or something similar in the view script? It could cause the <br /> tags to get stripped out.
It's also possible to add multiple messages by calling flashMessenger->addMessage() once for every address:
$cust = 'test#test.com';
$this->_helper->flashMessenger->addMessage('Mail send to '. $cust. ' Successfully');
if(count($m_list)>0 )
$this->_helper->flashMessenger->addMessage('Also Sent Mail to following members');
foreach($m_list as $value)
{
$mail_to_manu = new Zend_Mail('utf-8');
$mail_to_manu->clearFrom();
$mail_to_manu->setBodyHtml('Text')
->setFrom('noreply#test.com', 'test admin')
->addTo($value['email'])
->setSubject('Test');
$mail_to_manu->send();
$this->_helper->flashMessenger->addMessage($value['manufacturers_email']);
}
$this->_redirector->gotoUrl('/index');
Your question
The reason why it's all bunched up together is that you're echoing it all out in a loop without additional markup.
What about something like:
foreach ($this->messages as $message)
{
echo '<p class="message">' . $this->escape($message) . '</p>';
}
But, in fact, there is a much better way of handling the flashMessenger in views. As you know the Zend FlashMessenger is an action helper. But there is also a great view helper avaiable which helps you output your messages nicely. The best thing about it is, that you can pass an array('warning' => 'This is a warning') and the array key (warning) will be used as class for the <p> tag. You can find information about this helper on Carlton Gibson's blog and additional explanations in this SO question.
Your variable naming needs improvement
Write readable variable names like $customer instead of just $cust. Nobody ever said shortening variable names is a means of writing lean code ;). Shortening variable names is bad (code smell) because it make code less readable for others and for yourself in the future.
Use casing like this $mailToManufacturer instead of using underscores. It's a general agreement (standard) and therefore good for readability and understanding of code too.