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

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' );

Related

reCaptcha V2 is now timing out during valication

I have been using reCaptcha V2 for awhile now and all of a sudden the validation is timing out on the file_get_contents line.
I can copy the URL from the error and paste it into a new window and the JSON object comes back immediately.
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='. urlencode($secret) .'&response='. urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
I fixed this timeout problem with the File_get_contents by changing to using $curl instead.
Like this:
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret) . '&response=' . urlencode($captcha);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// file get contents not used any more
//$response = file_get_contents($url,0,stream_context_create(["http"=>["timeout"=>120]]) );
$responseKeys = json_decode($response,true);
// should return JSON with success as true

Mock Curl response for testing in laravel

I am trying to unit test a function(updateMeeting) in laravel which uses a curl request inside it. I tried many google links but nothing worked. can you guys give me suggestions on this matter.
following are relevant methods. $this->meeting is a MeetingModel
public function updateMeeting($meetingId){
$meeting = $this->meeting->find($meetingId);
$endpoint = \Config::get('api_backend_endpoint');
$response = $this->curlPut($endpoint);
if ($response->http_status_code != 200) {
if(Input::get('source') == 'ajax') {
$apiResponse = app(ApiResponse::class);
$message = 'ERROR Updating Meeting ' . $meeting->name;
return $apiResponse->failed($message);
}
return Redirect::route('meetings.show', $meetingId)
->withInput()
->with('message', 'An error occurred hiding meeting with message: ' . $response->errors);
}
$meeting->save();
}
following is curlPut method
private function curlPut($url, $payload = array())
{
$data_string = json_encode($payload);
$ch = curl_init();
//send through our payload as post fields
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$buffer = json_decode(curl_exec($ch));
curl_close($ch);
return $buffer;
}
Use a webservice like https://www.mocky.io/. Instead of requesting the real API, you send your requests to their API. You can create mock endpoints which return a response you can define.

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

Refreshing an access token (offline access) for Google Drive API in PHP

I am writing an app that performs routine updates to a database with data gathered from a single account's Google Drive using the Google Drive API and Google Sheets API.
Using the answer found in this How do I authorise an app (web or installed) without user intervention? (canonical ?) question, I have been able to create my own PHP function to get the access token.
function get_access_token() {
$request_url = "https://www.googleapis.com/oauth2/v4/token";
$refresh_token = "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X";
$params = [
'client_id' => "1073411048819-vergewrgergergewrgerwgewr.apps.googleusercontent.com",
'client_secret' => "b8oPhmVrevervvreverviA37aipaB",
'refresh_token' => $refresh_token,
'grant_type' => "refresh_token"
];
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
$postData = "";
//This is needed to properly form post the credentials object
foreach($params as $k => $v) {
$postData .= $k . '='.urlencode($v).'&';
}
$postData = rtrim($postData, '&');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$json_response = curl_exec($curl);
$response = (array) json_decode( $json_response );
$response["refresh_token"] = $refresh_token;
$date = new DateTime();
$response["created"] = $date->getTimestamp();
return $response;
}
Which works and produces an access token that looks like this:
array(5) {
["access_token"]=>
string(129) "ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy"
["token_type"]=>
string(6) "Bearer"
["expires_in"]=>
int(3600)
["refresh_token"]=>
string(45) "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X"
["created"]=>
int(1510654966)
}
I can use this access_token to make requests such as...
GET https://www.googleapis.com/drive/v3/files
Authorization: Bearer ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy
... so the function definitely produces a valid token.
However, I cannot figure out how to use the Google Drive API Client library with this.
Here is the PHP Quickstart for the Google Drive API.
And here is my broken code:
define('APPLICATION_NAME', 'My Plugin');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$accessToken = get_access_token();
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode(get_access_token()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$driveService = new Google_Service_Drive($client);
That produces:
$client = NULL;
$driveService = NULL;
Is it possible to use this approach with the PHP library? If so, what is wrong with my example?
If not, how can I turn this:
$response = $driveService->changes->getStartPageToken();
Into a HTTP/REST call (similar to GET https://www.googleapis.com/drive/v3/files)?
$token='access_token_here';
$url="https://www.googleapis.com/upload/drive/v3/files?uploadType=media";
$method='POST';
$filepath='file_to_upload_path.pdf'
$data['name']='file_title_here.pdf';
$data['title']='file_title_here.pdf';
$p1=(object)[];
$p1->id='parent_folder_id_here';
$data['parents'][]=$p1;
$body=file_get_contents($filepath);
$timeout=30;
$verify_ssl = false;
$headers = array(
'Content-Type: application/pdf',
'Cache-Control: no-cache',
'Authorization: Bearer '.$token ,
'Content-Length: '.strlen($body)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
echo $result = curl_exec($ch);
//echo $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

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

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' );

Resources