CakePHP Multiple Named Parameters in Link - php

I'm using a link to name a parameter that I need in a form on the next page. Here is the link code:
echo $this->Html->link('Email', array('controller' => 'emails', 'action' => 'add', 'contact_email' => $model), array('class' => 'button add'));
The purpose of this is to save an email to the database, and then send the email (both of which work).
I want to return to the page that they were on when they clicked the link, but don't know how to access that model and id after they've gone through two more page...
Here's add.ctp
<div class="universities form">
<?php echo $this->Form->create('Email');?>
<fieldset>
<legend><?php __('Add Email'); ?></legend>
<?php
echo $this->Form->input('subject');
echo $this->Form->input('email_text');
echo $this->Form->hidden('email', array('value' => $this->params['named']['contact_email']));
echo $this->Form->hidden('user_from', array('value' => $this->Session->read('User.id')));
echo $this->Form->hidden('created', array('value' => date("Y-m-d")));
echo $this->Form->hidden('modified', array('value' => date("Y-m-d")));
echo $this->Form->hidden('model', array('value' => $this->params['named']['model']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
The real issue -- where to redirect?
$this->redirect(array('controller' => $this->data['Email']['model'], 'action' => 'view', $this->data['model']['id']));
After implementing answer one, I get these errors on redirect (email saves and sends successfully though, so its just redirect issue).
Notice (8): Undefined property: Email::$enabled [CORE/cake/libs/controller/component.php, line 142]
Code | Context
$component =& $this->_loaded[$name];
if ($component->enabled === true && method_exists($component, 'beforeRedirect')) {
Component::beforeRedirect() - CORE/cake/libs/controller/component.php, line 142
Controller::redirect() - CORE/cake/libs/controller/controller.php, line 678
EmailsController::add() - APP/controllers/emails_controller.php, line 54
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
Warning: mkdir() [http://php.net/function.mkdir]: Permission denied in /Users/jwg2s/Sites/fundvista/cake/libs/folder.php on line 498
Warning (2): Cannot modify header information - headers already sent by (output started at /Users/jwg2s/Sites/fundvista/cake/libs/debugger.php:673) [CORE/cake/libs/controller/controller.php, line 742]
Code | Context
header - [internal], line ??
Controller::header() - CORE/cake/libs/controller/controller.php, line 742
Controller::redirect() - CORE/cake/libs/controller/controller.php, line 721
EmailsController::add() - APP/controllers/emails_controller.php, line 54
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
Warning: mkdir() [http://php.net/function.mkdir]: Permission denied in /Users/jwg2s/Sites/fundvista/cake/libs/folder.php on line 498

What I would suggest, is to build a full return URI using:
$this->params['controller']
$this->params['action'];
$this->params['pass'];
So it would look something like this:
$returnUrl = $this->params['controller'] . '/' . $this->params['action'] . '/' . implode('/', $this->params['pass']);
// let's also replace the slashes with, say, underscores
$returnUrl = str_replace('/', '_', $returnUrl);
echo $this->Html->link('Email', array('controller' => 'emails', 'action' => 'add', 'contact_email' => $model, 'returnUrl' => $returnUrl), array('class' => 'button add'));
in add.ctp
echo $this->Form->hidden('returnUrl', array('value' => $this->params['named']['returnUrl']));
and in email's controller
$this->redirect('/' . str_replace('_', '/', $this->data['Email']['returnUrl']));

$this->redirect($this->referer(array('action' => 'index')));
where index is your default action if the referring link doesn't exist.
read up here
e.g your user is on content/view/my-content, he clicks emails/add, fills in his details, submits. the referring page is content/view/my-content, so he (should) be redirected back there.

I added this to app_controller.php:
public function sendEmail($to,$from,$subject,$body,$headers=array(),$save_to_db=true)
{
if($save_to_db == true)
{
//do model crap here
$this->Email->create();
$data = array(
'email' => $to,
'subject' => $subject,
'email_text' => $body,
'user_from' => $from,
// map fields here
);
if($this->Email->save($data) == false)
{
$this->log("Email to '$to' from '$from' with subject '$subject' failed to save into the database!");
}
} // end save to db
$email = new EmailComponent();
//$email->startup($this);
//reeset email component
$email->reset();
/* SMTP Options */
$email->smtpOptions = array(
'port'=>'25',
'timeout'=>'30',
'host' => 'smtp.gmail.com',
'username'=>'###########',
'password'=>'###########',
);
/* Set delivery method */
//$email->delivery = 'smtp';
$email->from = $from;
$email->to = $to;
$email->subject = $subject;
$email->replyTo = $from;
$email->from = '############ <' . $subject . '>';
$email->sendAs = 'html'; //Send as 'html', 'text' or 'both' (default is 'text')
$success = $email->send($this->data['Email']['email_text']);
if($success == false)
{
$this->log("Email to '$to' from '$from' with subject '$subject' failed to send!");
}
return true;
} // end sendEmail
And then called the function after setting variables in my emails controller. (e.g. the $to, $from, $subject, $body, $headers)

Related

PHP MAIL: one of my variables send a "false" value

I am sending an e-mail with different variables as an JSON encoded array from an online store. I get the mail just fine and all the data is in there except for one of the variables, which is a JSON encoded array by itself. this particular variable shows as "false" in the e-mail. I'm missing something?
I'm using PHP mail to do it.
<?php
require_once "Mail.php";
$link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM users WHERE user = '" . $_SESSION['logged'] . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$user = $_SESSION['logged'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$apt = $_POST['apt'];
$cep = $_POST['cep'];
$total = $_POST['total'];
$comment = $_POST['observacion'];
$from = $row['mail'];
$mailTo = "xxxxx#hotmail.com";
$subject = "compra online - no cep";
$compra = $_SESSION["shopping_cart"];
$compra2 = json_encode($compra);
$bod = array(
'user' => $user,
'rua' => $rua,
'cep' => $cep,
'compra' => $compra2,
'comment' => $comment,
'total' => $total,
);
$body = json_encode($bod);
$headers = array(
'From' => $from,
'To' => $mailTo,
'Subject' => $subject,
);
$smtp = Mail::factory('smtp', array(
'host' => 'smtp-mail.outlook.com',
'port' => '587',
'auth' => true,
'username' => 'xxxxxxx#hotmail.com',
'password' => 'xxxxxxx',
));
$mail = $smtp->send($mailTo, $headers, $body);
if (PEAR::isError($mail)) {
echo ("<p>" . $mail->getMessage() . "</p>");
} else {
header("Location: lojacart.php?mailok");
}
mysqli_close($link);
I'm getting the e-mail with all the data except for the $compra2 variable which is showing as 'compra'=false. now if I echo the variable $compra2 it actually have a large string of data on it.
I think it might have to do with the variable being a JSON encoded session, but I'm not sure.
After a lot of trying and getting frustrated I came with a solution, for those looking for a something like this:
I added a hidden input to the form on the previous page and assigned it a value as "print_r($SESSION['whatever you session is called'], TRUE)" ...
on the next page I took the $_POST[] form that input and added the variable to the $body array for the mail().
It will print some array garbage in the middle BUT it works like a charm! and I cleaned all the "extra" text form the array using preg_replace(). It may not be an elegant way of doing it but as I said... it worked

stream_socket_client - php_network_getaddresses: getaddrinfo failed: Name or service not known

function drupal_http_request($url, array $options = array()) {
// Allow an alternate HTTP client library to replace Drupal's default
// implementation.
$override_function = variable_get('drupal_http_request_function', FALSE);
if (!empty($override_function) && function_exists($override_function)) {
return $override_function($url, $options);
}
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
$uri = #parse_url($url);
if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}
if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}
timer_start(__FUNCTION__);
// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'Drupal (+http://drupal.org/)',
);
// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];
// Use a proxy if one is defined and the host is not on the excluded list.
$proxy_server = variable_get('proxy_server', '');
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
// Set the scheme so we open a socket to the proxy server.
$uri['scheme'] = 'proxy';
// Set the path to be the full URL.
$uri['path'] = $url;
// Since the URL is passed as the path, we won't use the parsed query.
unset($uri['query']);
// Add in username and password to Proxy-Authorization header if needed.
if ($proxy_username = variable_get('proxy_username', '')) {
$proxy_password = variable_get('proxy_password', '');
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
}
// Some proxies reject requests with any User-Agent headers, while others
// require a specific one.
$proxy_user_agent = variable_get('proxy_user_agent', '');
// The default value matches neither condition.
if ($proxy_user_agent === NULL) {
unset($options['headers']['User-Agent']);
}
elseif ($proxy_user_agent) {
$options['headers']['User-Agent'] = $proxy_user_agent;
}
}
switch ($uri['scheme']) {
case 'proxy':
// Make the socket connection to a proxy server.
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
// The Host header still needs to match the real request.
$options['headers']['Host'] = $uri['host'];
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
break;
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;
case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;
default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}
if (empty($options['context'])) {
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout']);
}
else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}
var_dump($fp);
// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket #socket', array('#socket' => $socket));
print_r($result);
exit();
// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// See system_requirements().
variable_set('drupal_http_request_fails', TRUE);
return $result;
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}
// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}
// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
}
// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';
while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);
if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);
// Parse the response status line.
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
$result->protocol = $response_status_array['http_version'];
$result->status_message = $response_status_array['reason_phrase'];
$code = $response_status_array['response_code'];
$result->headers = array();
// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
}
else {
$result->headers[$name] = trim($value);
}
}
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
}
elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects']--;
$result = drupal_http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $result->status_message;
}
return $result;
}
I'm getting the below mentioned message by doing var_dump of $fp as mentioned above on my VM machine hosted with Ubuntu 14.04
stdClass Object
(
[code] => 0
[error] => php_network_getaddresses: getaddrinfo failed: Name or service not known
)
When I'm implementing the same thing on my localhost which is XAMPP based in Windows 7 I'm getting this:
Resource id #8
Due to this I'm unable to use the drupal_http_request
As per your suggestion I've tried dns_get_record()
$dns_get_record = dns_get_record("www.google.com");
print_r($dns_get_record);
and got this as the output:
Array
(
[0] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 243
[type] => A
[ip] => 216.58.220.4
)
[1] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 257
[type] => AAAA
[ipv6] => 2404:6800:4009:805::2004
)
)
I've also checked the stream_socket_client()
var_dump(stream_socket_client());
and it returned me bool(false)
Since you've not put any proper error handling in the code, we can't tell which function is being executed. You haven't provided the parameters you are passing, so we can't tell what the cause is, but the most likely issue is that you are trying to establish a network connection and the host where the code is running is unable to resolve the hostname inside $socket.
You can very this with dns_get_record() or speak to your hosting provider.

I get an error when sending this sms

I'm using the clockwork api. The error code is: Message failed - Error: Invalid 'To' Parameter
I think it's beacause in the $message line. I've not set the variables correctly.
<?php
require 'class-Clockwork.php';
try
{
// Create a Clockwork object using your API key
$API_KEY = "API_KEY";
$clockwork = new Clockwork( $API_KEY );
$phonenumber = $_POST['phonenumber'];
$message = $_POST['sendmessage'];
// Setup and send a message
$message = array( 'to' => '$phonenumber', 'message' => '$sendmessage' );
$result = $clockwork->send( $message );
// Check if the send was successful
if($result['success']) {
echo 'Message sent - ID: ' . $result['id'];
} else {
echo 'Message failed - Error: ' . $result['error_message'];
}
}
catch (ClockworkException $e)
{
echo 'Exception sending SMS: ' . $e->getMessage();
}
?>
$message = array( 'to' => '$phonenumber', 'message' => '$sendmessage' );
This should be
$message = array( 'to' => $phonenumber, 'message' => $sendmessage );
Otherwise you get the literal text "$phonenumber", not the contents of the variable.

Sending email using mailgun PHP API

I am trying to send an email with mailguns PHP api:
define('MAILGUN_KEY', 'key-ExamPle3xAMPle');
define('MAILGUN_DOMAIN', 'example.com');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#signstoptt.com',
'to' => $email,
'subject' => 'Sign Stop mailing list confirmation.',
'html' => "
Hello{$name},</br></br>
This is a test."
]);
I have even tried to use array() instead of [ ].
I receive the following error in my php error log:
MissingRequiredParameters
It implies that what I am passing to the post function is incomplete or incorrect. upon inspecting the post function in the RestClient, I see that the function requires 2 arrays and not 1, so I tried adding a 2nd array with message attachments and it just got more errors, this time with guzzle (a dependency for mailgun)
[26-Jan-2015 14:32:50 UTC] PHP Fatal error: Uncaught exception 'Mailgun\Connection\Exceptions\MissingRequiredParameters' with message 'The parameters passed to the API were invalid. Check your inputs!' in C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php:187
Stack trace:
#0 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php(116): Mailgun\Connection\RestClient->responseHandler(Object(Guzzle\Http\Message\Response))
#1 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Mailgun.php(106): Mailgun\Connection\RestClient->post('signstoptt.com/...', Array, Array)
#2 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Mailgun.php(53): Mailgun\Mailgun->post('signstoptt.com/...', Array, Array)
#3 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\subscribe.php(26): Mailgun\Mailgun->sendMessage('signstoptt.com', Array)
#4 in C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php on line 187
Has anyone else had this problem. I am running the site on a glassfish server setup by netbeans. I also used composer to install mailgun and its dependencies.
EDIT: Added more information.
init.php
<?php
require_once 'vendor/autoload.php';
define('MAILGUN_KEY', 'key-854743a7e');
define('MAILGUN_PUBKEY', 'pubkey-b00e47d7');
define('MAILGUN_DOMAIN', 'example.com');
define('MAILGUN_LIST', 'customers#example.com');
define('MAILGUN_SECRET','xjhbJH7');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgunValidate = new Mailgun\Mailgun(MAILGUN_PUBKEY);
$mailgunOptIn = $mailgun->OptInHandler();
subscribe.php
<?php
require_once 'init.php';
if(isset($_POST['name'], $_POST['email']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if($validate->is_valid)
{
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$result = $mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#example.com',
'to' => $email,
'subject' => 'example mailing list confirmation.',
'html' => "
Hello{$name},</br></br>
You submitted a request to join our mailing list, to confirm this subscription please click on the link provided below.</br></br>
http://localhost:8000/confirm.php?hash={$hash}"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
header('Location: ./');
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Subscribe | Mailing list</title>
</head>
<body>
<div class="container">
<form action="subscribe.php" method="post">
<div class="field">
<label>
Name
<input type="text" name="name" autocomplete="off">
</label>
</div>
<div class="field">
<label>
Email
<input type="text" name="email" autocomplete="off">
</label>
</div>
<input type="submit" value="Subscribe" class="button">
</form>
</div>
</body>
</html>
You forgot the text key which is used when html isn't available by the mail client.
Your code will look like
define('MAILGUN_KEY', 'key-ExamPle3xAMPle');
define('MAILGUN_DOMAIN', 'example.com');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#signstoptt.com',
'to' => $email,
'subject' => 'Sign Stop mailing list confirmation.',
'text' => 'Hello ' . $name . ', this is a test.',
'html' => '
Hello ' . $name . ',</br></br>
This is a test.'
]);
By the way; I recommend always using single quotes or double quotes for readability.

PHP: where to put the Restful service code at right position?

I am new to PHP and was trying to build RestFull service in PHP for my Mobile App. I googled and found Create a REST API with PHP Article best as per recommendations by many people on Stackoverflow and other places.
But while reading this article I arranged this code like below and was unable to figure out that the given last two functions, where to place them?
PHP is new language for me .. so please help me.
class RestUtils
{
public static function processRequest()
{
// get our verb
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method)
{
// gets are easy...
case 'get':
$data = $_GET;
break;
// so are posts
case 'post':
$data = $_POST;
break;
// here's the tricky bit...
case 'put':
// basically, we read a string from PHP's special input location,
// and then parse it out into an array via parse_str... per the PHP docs:
// Parses str as if it were the query string passed via a URL and sets
// variables in the current scope.
parse_str(file_get_contents('php://input'), $put_vars);
$data = $put_vars;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if(isset($data['data']))
{
// translate the JSON to an Object for use however you want
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
// set the status
header($status_header);
// set the content type
header('Content-type: ' . $content_type);
// pages with body are easy
if($body != '')
{
// send the body
echo $body;
exit;
}
// we need to create the body if none is passed
else
{
// create some body messages
$message = '';
// this is purely optional, but makes the pages a little nicer to read
// for your users. Since you won't likely send a lot of different status codes,
// this also shouldn't be too ponderous to maintain
switch($status)
{
case 401:
$message = 'You must be authorized to view this page.';
break;
case 404:
$message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
break;
case 500:
$message = 'The server encountered an error processing your request.';
break;
case 501:
$message = 'The requested method is not implemented.';
break;
}
// servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
// this should be templatized in a real-world solution
$body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>
</head>
<body>
<h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>
<p>' . $message . '</p>
<hr />
<address>' . $signature . '</address>
</body>
</html>';
echo $body;
exit;
}
}
public static function getStatusCodeMessage($status)
{
// these could be stored in a .ini file and loaded
// via parse_ini_file()... however, this will suffice
// for an example
$codes = Array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
return (isset($codes[$status])) ? $codes[$status] : '';
}
}
class RestRequest
{
private $request_vars;
private $data;
private $http_accept;
private $method;
public function __construct()
{
$this->request_vars = array();
$this->data = '';
$this->http_accept = (strpos($_SERVER['HTTP_ACCEPT'], 'json')) ? 'json' : 'xml';
$this->method = 'get';
}
public function setData($data)
{
$this->data = $data;
}
public function setMethod($method)
{
$this->method = $method;
}
public function setRequestVars($request_vars)
{
$this->request_vars = $request_vars;
}
public function getData()
{
return $this->data;
}
public function getMethod()
{
return $this->method;
}
public function getHttpAccept()
{
return $this->http_accept;
}
public function getRequestVars()
{
return $this->request_vars;
}
}
///// Code srgments Which I am unable to put at right position///////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
$data = RestUtils::processRequest();
switch($data->getMethod)
{
case 'get':
// retrieve a list of users
break;
case 'post':
$user = new User();
$user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
// and so on...
$user->save();
break;
// etc, etc, etc...
}
/////////////////////////////////
switch($data->getMethod)
{
// this is a request for all users, not one in particular
case 'get':
$user_list = getUserList(); // assume this returns an array
if($data->getHttpAccept == 'json')
{
RestUtils::sendResponse(200, json_encode($user_list), 'application/json');
}
else if ($data->getHttpAccept == 'xml')
{
// using the XML_SERIALIZER Pear Package
$options = array
(
'indent' => ' ',
'addDecl' => false,
'rootName' => $fc->getAction(),
XML_SERIALIZER_OPTION_RETURN_RESULT => true
);
$serializer = new XML_Serializer($options);
RestUtils::sendResponse(200, $serializer->serialize($user_list), 'application/xml');
}
break;
// new user create
case 'post':
$user = new User();
$user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
// and so on...
$user->save();
// just send the new ID as the body
RestUtils::sendResponse(201, $user->getId());
break;
}
/////////////////////////////////////////////////////////////////////////////////////
Check out this link,
we can use CodeIgniter to create a RESTful API for your existing web applications, and demonstrate how to interact with your own API or other RESTful web-services, such as Facebook and Twitter.
Working with Restful Services in CodeIgniter
May this helpful you.

Categories