Sending SMS via PHP Codeigniter and email-to-SMS gateway - codeigniter

I am trying to send a text message via the following in PHP Codeigniter.
If I send an email to the same "###########vtext.com" from my gmail client, I receive the text message.
If I use the same code below but substitute my gmail account, I receive the message via email.
However, I cannot seem to trigger a text message sent to me via the code below.
I am thinking it may have something to do with a spam filter somewhere within the phone service.
Any suggestions, or else a free workaround for sending SMS via PHP/Codeigniter? Thanks!
public function textMe()
{
$this->load->library('email');
$this->email->to('###########vtext.com'); [number edited out]
$this->email->from('Notify#test.org','Test');
$this->email->subject("Test Subject");
$this->email->message('Test Message');
$this->email->send();
echo $this->email->print_debugger();
}

Codeigniter helper is useful in this case. Helper function will be available wherever needed. Save below file in Application/Heplers/sendsms_helper.php
/*Start sendsms_helper.php file */
function sendsms($number, $message_body, $return = '0'){
$sender = 'SEDEMO'; // Need to change
$smsGatewayUrl = 'http://springedge.com';
$apikey = '62q3z3hs49xxxxxx'; // Change
$textmessage = urlencode($textmessage);
$api_element = '/api/web/send/';
$api_params = $api_element.'?apikey='.$apikey.'&sender='.$sender.'&to='.$mobileno.
'&message='.$textmessage;
$smsgatewaydata = $smsGatewayUrl.$api_params;
$url = $smsgatewaydata;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
if(!$output){
$output = file_get_contents($smsgatewaydata);
}
if($return == '1'){
return $output;
}else{
echo "Sent";
}
}
/* * End sendsms_helper.php file */
** Use:**
Load sendsms helper as $this->load->helper('sendsms_helper');
Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message' );

Related

How to send data from controller to rest api in laravel?

How can I send data from controller to external api in Laravel?
public function syncData(Request $request)
{
$datas = Data::all();
$newDatas = NewData::all();
$url = 'mydomain.com/api/sync-data';
}
I want to send $datas and $newDatas to $url through Laravel controller and perform some actions on those data. How can I achieve that?
You could use the Laravel HTTP Client (which is a wrapper for Guzzle HTTP Client) to perform a request to that API.
use Illuminate\Support\Facades\Http;
$response = Http::post('mydomain.com/api/sync-data', [
'data' => Data::all(),
'newdata' => NewData::all(),
]);
public function syncData(Request $request)
{
$datas = Data::all();
$newDatas = NewData::all();
$url = 'mydomain.com/api/sync-data';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($datas));
$output = curl_exec($ch);
curl_close($ch);
}
let me know if it is helpful.
important things to notice here.
you have to know what your external API type is. is it POST or in GET method.
my example above is just a sample code to make you understand how you will use curl it is not tested in regard to your context

codeigniter: how do you declare sendsms( '919918xxxxxx', 'test message from spring edge' );

sendsms( '919918xxxxxx', 'test message from spring edge' ); how do you declare this function in codeigniter?
Codeigniter have a good functionality Helpers. Helper functions are available in all controllers(if auto-load). You can use codeigniter helper to declare this function.
Open a file in Application/Heplers/sendsms_helper.php
/*Start sendsms_helper.php file */
function sendsms($number, $message_body, $return = '0'){
$sender = 'SEDEMO'; //Use sender name here
$smsGatewayUrl = 'SMS_GATEWAY_URL_HERE';
$apikey = '62q3z3hs49xxxxxx'; // Use API key here
$textmessage = urlencode($textmessage);
$api_element = '/api/web/send/';
$api_params = $api_element.'?apikey='.$apikey.'&sender='.$sender.'&to='.$mobileno.
'&message='.$textmessage;
$smsgatewaydata = $smsGatewayUrl.$api_params;
$url = $smsgatewaydata;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
if($return == '1'){
return $output;
}
}
/* * End sendsms_helper.php file */
How to use in controller:
Load sendsms helper in controller using $this->load->helper('sendsms_helper');
Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message from spring edge' );

The resource doesn't support specified Http Verb

I am trying to make a contact form for a static website hosted in an Azure blob.
When I click submit I can see the following error in the Console.
Failed to load resource: the server responded with a status of 405
(The resource doesn't support specified Http Verb.)
I think the issue may be that I need to set up CORS for mailgun.
However I don't know what values to put
Here is send.php code
<?php
if( isset($_POST) ){
$postData = $_POST;
$mailgun = sendMailgun($postData);
if($mailgun) {
echo "Great success.";
} else {
echo "Mailgun did not connect properly.";
}
}
function sendMailgun($data) {
$api_key = 'INSERT_API_KEY_HERE';
$api_domain = 'INSERT_DOMAIN_HERE';
$send_to = 'YOUR_EMAIL';
// sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
// form data
$postcontent = $data['data'];
$reply = $data['senderAddress'];
$messageBody = "<p>You have received a new message from the contact form on your website.</p>
{$postcontent}
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
$config = array();
$config['api_key'] = $api_key;
$config['api_url'] = 'https://api.mailgun.net/v3/'.$api_domain.'/messages';
$message = array();
$message['from'] = $reply;
$message['to'] = $send_to;
$message['h:Reply-To'] = $reply;
$message['subject'] = "New Message from your Mailgun Contact Form";
$message['html'] = $messageBody;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config['api_url']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:{$config['api_key']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$message);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
This question is a follow up from this question
I have tried including the subdomain www in the api_domain.
PHP does not run client side which means it is not suitable for a static website. As mentioned in this question
Alternatives are mentioned here

OAuth 2.0 create single event with Google Calendar PHP API - Login Required error with cURL

I need a PHP script which has to create an event on google calendar.
I've already read google API documentation and I've understood that I have to use an offline access to API because I'd like that my script would create the calendar event itself, without asking for user auth every time.
I've also read here in stackoverflow that some ppl had problems resfreshing the token and have fixed the problem using cURL; I've tried to do that but I got an error: Uncaught exception 'Google_ServiceException' with message 'Error calling POST and 401 Login Required; now in $json_response var, there is the access_token; I've not understood how to use it to renew my connection. Thanks in advance for your help!
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_CalendarService.php';
session_start();
// I need that my script refresh the token itself, starting from a token that I've generated one time with user interaction
$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"client_id" => '...',
"client_secret" => '...');
$clienttoken_post["refresh_token"] = "1/vIQ......";
$clienttoken_post["grant_type"] = "refresh_token";
$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
print_r($authObj);
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('....');
$client->setClientSecret('....'); $client->setRedirectUri('...');
$client->setDeveloperKey('....');
$client->setAccessType('offline');
//$client-> setApprovalPrompt("auto");
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if(isset($_SESSION['token'])) {
// echo $_SESSION['token'];
$client->setAccessToken($_SESSION['token']);
}
$event = new Google_Event();
$event->setSummary($event_name);
$event->setLocation('');
$start = new Google_EventDateTime();
$start->setDate($scadenza);
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDate($scadenza);
$event->setEnd($end);
$createdEvent = $cal->events->insert('cal_id_xyz', $event);
?>
Thanks in advance!
(Disclaimer: I'm not a PHP expert (or even novice) - but I do know Google's OAuth flows)
A few things to note:
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); - if that is disabling certificate validation, then I strongly suggest not doing that - you should want to verify that you are sending the refresh token to accounts.google.com and no-one else.
Make sure you set the content-type to "application/x-www-form-urlencoded" on the POST - it's not clear to me whether setting CURLOPT_POSTFIELDS does this or something else for you.
I don't know why you are setting CURLOPT_HTTPAUTH - I wouldn't expect that to make any positive effect on the request.
That all said, my suggestion would be to take advantage of the Google provided client library - which it looks like you are already using.
After looking at the src for Google_Client.php, I believe that adding a:
$client->refreshToken("1/xxxxxx....");
after all of the other ->setXXXs will have it go ahead and get a new access token for you that it should then automatically add to subsequent APIs calls. I suggest trying that and removing the manual calls to curl.
I've finally solved my problem this way:
First of all I've obtained an access token and a refresh token with a human interaction using the PHP sample script found at this URL: https://code.google.com/p/google-api-php-client/
So I've put the access token in actok.txt and then I've run the following script.
Hope that could help beginners (and I am one of them :-) ), to better understand how OAuth works with offline access.
<?php
// I've put the last valid access token in a txt file
$my_file = 'actok.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
fclose($handle);
$first_answer = "{\"access_token\":\"" . $data . "\",\"expires_in\":3920,\"token_type\":\"Bearer\",\"refresh_token\":\"1/xxxxx\"}"; // the refresh_token is always the same and it's the one obtained at the beginning.
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_CalendarService.php';
session_start();
$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"client_id" => '....',
"client_secret" => '....');
$clienttoken_post["refresh_token"] = "...."; // the same as before
$clienttoken_post["grant_type"] = "refresh_token";
$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt ($curl, CURLOPT_HTTPHEADER, Array("application/x-www-form-urlencoded"));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('xyz'); // ClientID
$client->setClientSecret('xyz'); // ClientSecret
$client->setRedirectUri('http://www.xyz/zzz.php'); // RedirectUri
$client->setDeveloperKey('ffffff'); // DeveloperKey
$client->setAccessType('offline');
$cal = new Google_CalendarService($client);
$client->setAccessToken($first_answer); // here I set the last valid access_token, taken from the txt file
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if(isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if(isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if($client->isAccessTokenExpired()) { // if the token is expired, I have to refresh it
echo 'Access Token Expired'; // debug
$json_response = curl_exec($curl); // JSON value returned
curl_close($curl);
$authObj = json_decode($json_response);
$sec_answer = "{\"access_token\":\"" . $authObj->access_token . "\",\"expires_in\":3920,\"token_type\":\"Bearer\",\"refresh_token\":\"1/xxxxxx\"}"; // same refresh_token as always
$client->setAccessToken($sec_answer);
$handle2 = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$new_accesstk = $authObj->access_token;
fwrite($handle2, $new_accesstk);
fclose($handle2);
}
// Event Creation
$event = new Google_Event();
$event->setSummary('xyz'); // Event name
$event->setLocation(''); // Event location
$start = new Google_EventDateTime();
$start->setDate('2013-xx-xx');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDate('2013-xx-xx');
$event->setEnd($end);
$createdEvent = $cal->events->insert('xyz', $event); // insert(calendar_id, event)
?>

CodeIgniter redirect to another function when request is made by cURL

I've got a function, "Function A", in a CodeIgniter controller that includes a redirect to another function, "Function B" to send an email when it's done gathering data. My problem is that when I enter Function A's url into the browser, the function works as expected and the redirect to Function B also works... but Function A is called by a cURL script, and when this happens Function A is performed but the redirected Function B does not work. Is it possible to have a redirected function in this scenario (when the request is made via cURL)?
Can you show your CURL code? I think you use something like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close( $ch );
Check this string (it should set to true):
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And you can use next thing (in stormdrain's example):
function first_function(){
ob_start();
//do stuff
$this->second_function();
ob_end_flush();
}
function second_function(){
//send email
}
It's hard to say without seeing any code. But, if these functions are in the same controller, you can call the other function when the first completes
function first_function(){
//do stuff
$this->second_function();
}
function second_function(){
//send email
}

Resources