I have seen many answer in stack overflow about this. But Nothing is working. I am trying to send a mail using SMTP server. But the server is dynamic. For me this is not a problem, but for sending mail I am try to make an api. For call the API I did the below code.
function curl_get_contents($url)
{
//echo $url; die;
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data_ar = array(
"email_ip" => $SmtpServer,
"username" =>$SmtpUser,
"password" => $SmtpPass,
"port" => $SmtpPort,
"email_id" => 'admin#owntheblog.com',
"email_to" => $_POST['to'],
"email_subject" => $_POST['sub'],
"email_content" => $_POST['message']
);
$data_js = json_encode($data_ar);
$url='http://setup.spotrix.com/app/webroot/mail/mail.php?smtp='.$data_js;
$response = curl_get_contents($url);
or replace the last line with $response = file_get_contents($url);
I found the above code in the stackoverflow. But in the both the case (as in the CURL or file_get_contents) the API calling is not working. But if you directly hit the URL in the browser then the mail is working. Like the URL is,
http://setup.spotrix.com/app/webroot/mail/mail.php?smtp={%22email_ip%22:%22IP%22,%22username%22:%22username%22,%22password%22:%22password%22,%22port%22:port,%22email_id%22:%22form_email%22,%22email_to%22:%22to_email%22,%22email_subject%22:%22Test%20Subject%22,%22email_content%22:%22Test%20Message%22}
Then the mail is working. But not working in the code. I am using cakephp 2.X. I think I made a mistake here. Please help me to solve this problem.
I made a form in php for test the mail portion. I am sharing the code also.
<?php
//Server Address
$SmtpServer= 'Your SMTP IP';
$SmtpPort= YOUR SMTP PORT; //default
$SmtpUser='YOUR SMTP USER NAME';
$SmtpPass='YOUR SMTP PASSWORD';
function curl_get_contents($url)
{
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$data_ar = array(
"email_ip" => $SmtpServer,
"username" =>$SmtpUser,
"password" => $SmtpPass,
"port" => $SmtpPort,
"email_id" => $_POST['from'],
"email_to" => $_POST['to'],
"email_subject" => $_POST['sub'],
"email_content" => $_POST['message']
);
$data_js = json_encode($data_ar);
$url='http://setup.spotrix.com/app/webroot/mail/mail.php?smtp='.$data_js;
$response = curl_get_contents($url);
//$response = file_get_contents($url);
echo $response;
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test Mail</title>
</head>
<body>
<form method="post" action="">
<table width="500px">
<tr><td width="20%">To : </td>
<td ><input type="text" name="to" /></td></tr>
<tr><td>From :</td><td><input type='text' name="from" /></td></tr>
<tr><td>Subject :</td><td><input type='text' name="sub" /></td></tr>
<tr><td>Message :</td><td><textarea name="message"></textarea></td></tr>
<tr><td></td><td><input type="submit" value=" Send " /></td></tr>
</table>
</form>
</body>
</html>
You can copy paste the above code and change to your SMTP details and use the mail system. You can echo the $url to see the requested url. Try to copy paste the url in the browser see the mail is working but not from the code. If the mail send successfully then it will reture 1 else 0. Please make me correct id I make any mistake.
Thanks in advance for help.
Related
I am able to send push notifications from the firebase console to mobile in react-native, but when I send from php file the success message is shown but no notification in a mobile. The message in php is :
{"multicast_id":8573*********,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:156161518380026**************"}]}
The user token and server key are correct.In previous projects, I used the similar php file to send notifications developed in android studio which worked perfect.
My php code for sending notification:
<html>
<head>
<title>ControlPlus Notification Center</title>
</head>
<body>
<center>
<br>
<font size="10" style="bold">ControlPlus Notification Center</font>
<br> <br> <br> <br> <br>
<Table class= "b">
<tr>
<td>
<form method = 'POST' action = '?notifyHealth=1'>
<div>
<input class ='main_button' type = 'submit' value = 'Send Notification'>
</div>
</form>
</td>
</tr>
</Table>
</center>
</body>
</html>
<?php
function sendPushNotification() {
$url = "https://fcm.googleapis.com/fcm/send";
$serverKey = 'AAAA25************************************Xw';
$title = "ControlPlus App";
$body = "New Workorder has been added !! ";
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => 'fL8aUT2un*******************************B2bzLa', 'data' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
if(!empty($_GET['notifyHealth'])) {
sendPushNotification();
}
?>
There may be an issue in the structure of the JSON payload you are sending. According to the documentation here: https://firebase.google.com/docs/cloud-messaging/concept-options, it should be structured as follows:
{
"message":{
"token":"fL8aUT2un*******************************B2bzLa",
"notification":{
"title":"ControlPlus App",
"body":"New Workorder has been added !! "
}
}
}
I make an api using Linkedin for website. After created all files, my application run fine but the only that has problem is when I try to allow the website, gives me this errors:
my purpose is to access in this page:
My code has error in this line:
init.php
<?php
SESSION_start();
$client_id="xxxxxxxxxxxxxx";
$client_secret="xxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token = "random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$header =[];
$header[] = "Content-type:applicationx-www-form-urlencoded";
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id="xxxxxxxxxxxxxx";
$client_secret="jxxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token ="random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
}
if(isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url, http_build_query($params));
$accessToken = json_decode($accessToken)->access_Token;
$URL="https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token=" .$accessToken;
$user = file_get_contents($url, false);
return(json_decode($user));
}
?>
Callback.php:
<?php
require_once "init.php";
$user = getCallback();
$_SESSION['user'] = $user;
header("location: landing.php");
?>
And this is the landing page:
<?php
require "init.php";
if(!isset($_SESSION['user'])) {
$user = 0;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
<body style="margin-top:200px; text-align:center;">
<div>
<h1>successful</h1>
<h1>here is describing your details info</h1>
<label style="font-weight:600">First Name</label><br>
<label><?php echo $user['firstName'] ?></label><br><br>
<label style="font-weight:600">Last Name</label><br>
<label><?php echo $user['lastName'] ?></label><br><br>
<label style="font-weight:600">Email address</label><br>
<label><?php echo $user['emailaddress'] ?></label><br><br>
<label style="font-weight:600">Headline</label><br>
<label><?php echo $user['headline'] ?></label><br><br>
<label style="font-weight:600">Industry</label><br>
<label><?php echo $user['industry'] ?></label><br><br>
<button>Log out</button>
</div>
</body>
</html>
the x it is for secure reason, I have put $client_secret="", $client_id="".
In this project I want to see my profile completed with details on landing page and not empty as it's show here for example in first name to be writen a name and ect.
how to fix those errors,thanks
The first error (Undefined property) is because the HTTP request didn't get a valid response ($accessToken) in:
$accessToken = curl();
This could be because the URL requested is invalid. You can:
Check if $params array is correctly set. Call print_r($params) or print_r(http_build_query($params)) before calling curl to check it.
Check if the curl() call has the right parameters (url and parameters) it could be better to use only a full url ($url . "?" . http_build_query($params)) if the request is using GET, but
The accessToken API must be requested as POST request (not GET), so make sure your cUrl call sends a POST request (See: https://developer.linkedin.com/docs/oauth2#)
The second error is related to the first one, because the access token is empty, you get a HTTP 400 error (bad request). So if you fix the first step the second could be fine.
try this code before $accessToken :
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
return true;
this make solute the error message
Trying to achieve Google invisible recaptcha, but I am not getting any response after verification.
Here is my code:
invisible_recaptcha.php (form)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recaptcha Demo</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
</head>
<body>
<!-- FORM GOES HERE -->
<form id='i-recaptcha' action="process_recaptcha.php" method="post">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>
<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>
<label for="email">Email Address*</label><br>
<input type="email" name="email" id="email" required><br><br>
<button class="g-recaptcha" data-sitekey="XXXXXXmy_site_keyXXXXXXXXX" data-size="invisible" data-callback="onSubmit">
Submit
</button>
</form>
</body>
</html>
process_recaptcha.php (verify the recaptcha)
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'XXXXXX_my_secret_key_XXXXXXXXX',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
//echo $user_response."<br><br><br><br>". $fields_string;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
// Paste mail function or whatever else you want to happen here!
echo '<br><p>CAPTCHA was completed successfully!</p><br>';
}
} ?>
It always gives me this message:
reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.
Please try this One
try {
//Get google capcha details
if ($site_details['google_captcha_secret_key'] != '') {
$site_key = $site_details['google_captcha_secret_key'];
} else {
$site_key = GOOGLE_CAPTCHA_SECRET_KEY;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $site_key,
'response' => $captcha,
'remoteip' => $this->userIpAddress];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
} catch (Exception $e) {
return null;
}
Make sure you double-check your code over for syntax errors. You are missing the left quote around your site key. You also have an extra parenthesis where it says json_decode.
Finally, you don't need to separate it into two PHP files if you are going to use this condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
So the php code in process_recaptcha.php can be embedded in invisible_recaptcha.php. You would then have to change the form's action attribute to itself (invisible_recaptcha.php). The condition will check if the form has been submitted yet. If is has, it will process your recaptcha code, if not, it will skip it.
I have to create an simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
<input type="text" name="firstname" placeholder="rahul_sharma">
<button type="submit">send</button>
</form>
</body>
</html>
From my process.php file, I have to hit an url like below:
https://stackoverflow.com/api?rahul_sharma
which will give back an json response
{"status":"Success","username":"your username is RAHULSHARMA"}
If status is success, have to display the username value.
New to php.Any help is appreciated.
you can call API using curl.
$url='https://stackoverflow.com/api?';
$call_url = $url . $_POST['first_name'] ;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call_url,
CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;//{"status":"Success","username":"your username is RAHULSHARMA"}
In your process.php file, you can use the $_POST superglobal to fetch the form data.
$firstname = $_POST['firstname'];
After that you can concatenate it using the . operator to form the url.
$url = "https://your-api-site.com/api?" . $firstname;
Next you can fetch the content from the url using a curl request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
The result from fetching the url will be obtained in the $output variable. Suppose the result from your API is a JSON string like the one you provided, you can use json_decode PHP function to convert it to an associative array.
$result = json_decode($output);
Now you can use if conditions to check if status is Success and display the username.
if ($result['status'] == "Success") {
echo $result['username'];
}
I am trying learn PHP by actually doing something I may find useful for myself. There is a betting agency in my country which has a website where I can check if I won or not by entering a ticket number. I am trying to write a PHP script to check if range of tickets are worth anything so I don't have to enter every ticket manually on their website.
I managed to do that. But now I want to save the response I get from their server in a file. I run into serious problems with this. I managed to save the verbose into a file but I am unable to make the script save to a file what I see on the screen inside my browser after running the script.
Here is the code:
<?php
function check($week, $base, $startcheck, $endcheck, $verbose = "true"){
// Set file path
$verbosePath = 'publicbet.txt';
echo "Saving the tickets to: <b>$verbosePath</b>\n";
// Initiate numbering
$i = 0;
// Initiate publicbet.ro IP
$ip = "80.86.107.93";
// Loop
while ($startcheck <= $endcheck){
// Generate tickkey
$tickkey = $week.$base.$startcheck;
// get the current server time
$time = date('d-m-Y H:i:s');
// Open a new cURL resource
$ch = curl_init();
// Stuff
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_STDERR,$f = fopen($verbosePath, "a"));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
// publicbet.ro may be checking the IP adress
// from where the $tickkey is sent in order to
// check for abnormalities; we will send the
// IP adress of the website:)
$headerarray = array(
"X-Forwarded-For: $ip");
// Set the URL and other options
curl_setopt($ch, CURLOPT_URL, 'http://publicbet.ro/gettickinfo2.php?lang=ro&tickkey='.$tickkey);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.publicbet.ro/');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
// Executing cURL
curl_exec($ch);
// Close cURL resource, free up system resources
curl_close($ch);
fclose($f);
// Showing informtion
$v .= "<br />$i. At <b>$time</b> the server checked the tickkey: <b>$tickkey</b> and returned the tickket: ";
if ($verbose == "true"){
echo $v;
$v = '';
}
// Modifying values
$startcheck++;
$i++;
}
}
if ($_POST[week] && $_POST[base] && $_POST[startcheck] && $_POST[endcheck]){
check($_POST[week], $_POST[base], $_POST[startcheck], $_POST[endcheck]);
}
else {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>publicbet.ro</title>
</head>
<body>
<h1>Check your tickets here</h1>
<form action="<?php echo $_SERVER[PHP_SELF];?>" method="post">
<table>
<tbody>
<tr>
<td>week:</td>
<td>base:</td>
<td>start check:</td>
<td>end check:</td>
</tr>
<tr>
<td><input type="number" name="week" min="00" max="54" maxlength="2" size="2" value=""/></td>
<td><input type="number" name="base" maxlength="11" size="11" value=""/></td>
<td><input type="number" name="startcheck" maxlength="6" size="6" value=""/></td>
<td><input type="number" name="endcheck" maxlength="6" size="6" value=""/></td>
</tr>
</tbody>
</table>
<br /><input type="submit" value="Check!" />
</form>
</body>
</html>
<?php } ?>
So please tell me if there is any method of doing what I am willing to. I would be really pleased.
If you want to test the script use these values:
week: 05
base: 16010234203
start check: 350900
end check: 350920 .
It will return 19 false tickets and 1 true. I want all this text which is showing up to be exported to a text file rather than showing on my screen.
Is there a way to do this?
Thank you in advance.
Set CURLOPT_RETURNTRANSFER to true, and then where you do curl_exec(), assign it to a variable like this:
$data = curl_exec($ch)
Then you can save it like this:
file_put_contents('my_file.txt', $data);
Use constants instead of string literals for things like true and false etc.. I see in your function arguments you do $verbose = "true", this could be replaced with $verbose = true.
You also are using constants where you should actually be using string literals, for example $_POST[base] should be $_POST['base'] or $_POST["base"]
Please don't use $_SERVER['PHP_SELF'] like that, it leaves you very open to XSS attacks, etc. You can do action="" and it will post to the page in question, like PHP_SELF
Where you are doing
if($_POST[base] .....)
I recommend doing this instead:
if(isset($_POST['base'], $_POST['somethingElse'], $_POST['anotherField'])) {
// yay
}