I have a PHP code for sending OTP, When i execute it in my local server its works well. But when i run this code after changing it from my local to server by changing host name etc, i am getting 500 internal server error. I don't know where i am going wrong. Any solution will be apreciated. Thank you
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.
Related
I need your help with this:
I try to create a shot in Dribbly but get the error message.
I did it like described in the documentation(http://developer.dribbble.com/v1/shots/#create-a-shot). This is my code:
$url = "http://www.rodos-palace.gr/uploads/images/509.jpg";
print_r($drib->create_shot('shottitle', $url));
public function create_shot($title, $image, $description = false)
{
$query = array(
'title' => $title,
'image' => $image
);
if ($description) {
$query['description'] = $description;
}
// print_r("<br>crearing_shot-> ".__LINE__);
$query['access_token'] = $this->access_token;
return $this->curl_post_shot($this->short_api, $query);
// return $this->curl_post_shot($this->short_api . "?" . 'access_token=' . $this->access_token, http_build_query($query));
}
public function curl_post_shot($url, $post)
{
$headers = array("Content-Type: multipart/form-data");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => $headers,
/*, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false*/
));
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$information = curl_getinfo($curl);
if( ($resp = curl_exec($curl)) === false )
{
echo 'Curl error: ' . curl_error($curl);
}
else
{
// echo 'Operation completed without any errors';
}
//echo "Check HTTP status code >>>>";
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($information = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
{ /*echo 'Unexpected HTTP code: ', $http_code, "\n";*/}
}
}
curl_close($curl);
print_r("<br>crearing_shot-> ".__LINE__);
echo "<pre>";
var_dump($information);
print_r("<br>----------------------------<br>");
print_r($headers);
return $resp;
}
and this is the error:
{ "message": "Validation failed.", "errors": [
{
"attribute": "image",
"message": "file is required"
} ] }
beside this, I try to do it with the image real path and with the PHP $_FILES and the result is the same.
please help me to solve this problem.
Thanks a lot.
Since I cannot verify, because I do not have an uploader account, I recommend using the cURL file class to upload a file. There are multiple ways to to this, but since you use OOP you should try this:
public function create_shot($title, $image, $description = false)
{
$query = array(
'title' => $title,
'image' => new CURLFile($image), // $image is the absolute path to the image file
);
if ($description) {
$query['description'] = $description;
}
$query['access_token'] = $this->access_token;
return $this->curl_post_shot($this->short_api, $query);
}
You will find details in the manual about the file upload.
I want to use mediawiki api to retrieve some informations with a symfony project, i want tu use curl to fo api calls,
I tried with
$ch=curl_init();
$postfield = "action=query&titles=Watch&prop=langlinks&lllimit=20";
$url = "https://en.wikipedia.org/w/api.php"; //url to wiki's api
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
but it does not work, it gives me boolean false as result
Here's a good example of using the PHP API using cURL from WikiMedia itself.
First, logging in:
/**
* Configuration
* -------------------------------------------------
*/
// Start session
session_start();
// Login
$app['username'] = "Example";
$app['password'] = "mypassword";
// Version
$app["version"] = "0.0.1-dev";
// Last modified
date_default_timezone_set("UTC");
$app["lastmod"] = date("Y-m-d H:i", getlastmod()) . " UTC"; // Example: 2010-04-15 18:09 UTC
// User-Agent used for loading external resources
$app["useragent"] = "My First Tool " . $app["version"] . " (LastModified: " . $app["lastmod"] . ") Contact: myfirsttool (at) example (.) com";
// Cookie file for the session
$app["cookiefile"] = tempnam("/tmp", "CURLCOOKIE");
// cURL to avoid repeating ourselfs
$app["curloptions"] =
array(
CURLOPT_COOKIEFILE => $app["cookiefile"],
CURLOPT_COOKIEJAR => $app["cookiefile"],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $app["useragent"],
CURLOPT_POST => true
);
$app["apiURL"] = "http://www.mediawiki.org/w/api.php";
Then to do the login using cookies:
/**
* Login
* -------------------------------------------------
*/
// Info: http://www.mediawiki.org/wiki/API:Login
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 003: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Basic error check + Confirm token
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "NeedToken") {
if (!empty($result["login"]["token"])) {
$_SESSION["logintoken"] = $result["login"]["token"];
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
"lgtoken" => $_SESSION["logintoken"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 004: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
} else {
$other_error = "Error 006: Token error.";
}
}
// Check for all documented errors
// Source: http://www.mediawiki.org/wiki/API:Login#Errors
// Date: 2010-04-17
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "Success") {
$_SESSION["login_result"] = $result["login"]["result"];
$_SESSION["login_lguserid"] = $result["login"]["lguserid"];
$_SESSION["login_lgusername"] = $result["login"]["lgusername"];
} else if ($result["login"]["result"] == "NeedToken") {
$other_error = "Error 005: Token error.";
} else if ($result["login"]["result"] == "NoName") {
$username_error = "The username can not be blank";
} else if ($result["login"]["result"] == "Illegal") {
$username_error = "You provided an illegal username";
} else if ($result["login"]["result"] == "NotExists") {
$username_error = "The username you provided doesn't exist";
} else if ($result["login"]["result"] == "EmptyPass") {
$password_error = "The password can not be blank";
} else if ($result["login"]["result"] == "WrongPass" || $result["login"]["result"] == "WrongPluginPass") {
$password_error = "The password you provided is incorrect";
} else if ($result["login"]["result"] == "CreateBlocked") {
$username_error = "Autocreation was blocked from this IP address";
} else if ($result["login"]["result"] == "Throttled") {
$other_error = "You've logged in too many times in a short time. Try again later.";
} else if ($result["login"]["result"] == "mustbeposted") {
$other_error = "Error 004: Logindata was not send correctly";
} else if ($result["login"]["result"] == "Blocked") {
$username_error = "This account is blocked.";
} else if ($result["login"]["result"]){
$other_error = "Error 001: An unknown event occurred.";
} else {
$other_error = "Error 002: An unknown event occurred.";
}
// The tool you use may log or display the variables:
// $other_error, $username_error and $password_error in the appropiate place
// Such as near a login form, or in a specific debug/logfile
// by default the errors are not outputted
if($_SESSION["login_result"] !== "Success"){
die("Login error. Have you defined app[username] and app[password] ?");
}
Example of building a query:
/**
* Get userinfo
* -------------------------------------------------
*/
$postdata = http_build_query([
"action" => "query",
"format" => "php",
"meta" => "userinfo",
"uiprop" => "rights|hasmsg",
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
Death("Error 003: " . curl_error($ch),"API connection failed.");
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Check for usermessages
if (isset($result['query']['userinfo']['messages'])) {
$api['hasmsg'] = true;
$api['hasmsghtml'] = '<div class="usermessage">You have new messages !</div>';
} else {
// User does not have new messages
}
And finally, how to clean up the session:
// Delete the cookie file
unlink($app["cookiefile"]);
// Destroy the session
session_destroy();
// End this file
die($output);
I tried that, and it works either
public function callWiki($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function getAllCategories()
{
$api = 'https://en.wikipedia.org/w/api.php? action=query&titles=watch&prop=categories&format=json';
//get query result
$api_response = $this->callWiki($api);
$results = json_decode($api_response, true);
}
i am able to send sms via php but in that i have to mention mobile number everytime i want that with the same script i can send sms to the entries stored in my database .
here is my code:
<?php
//Your authentication key`enter code here`
$authKey = "API key";
//Multiple mobiles numbers separated by comma
$mobileNumber = "+919425386214";
//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "Social";
//Your message to send, Add URL encoding here.
$message = urlencode("Test message");
//Define route
$route = "04";
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
if (isset($_POST['submit']))
{
//API URL
$url="https://control.msg91.com/api/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo $output;
}
?>
please help so that i can send sms to my clients whom contact no. are stored in my database
You need to do some query code to do it , for your help a sample code:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$mobileNumber = '';
$conn = mysqli_connect('localhost','root','','database name') or die (mysqli_error()); // give connection credentials here
if($conn){
$query = "Select mobile_number From User"; // change table name and column name accordingly.
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$mobileNumber .= $row['mobile_number'].',';
}
}
}
$mobileNumber = substr($mobileNumber,0,strlen($mobileNumber)-1); // now you have all mobile numbers in , seperated form in this variable
Note:- You can add this code in your current php code and do changes accordingly and you will get the output what you want.
When I call the function below, the field in my database gets the responses as send (only one time), but when I check the mobile it has sent two equal messages at a time.
public function sendverifymsg($phone, $verifycode) {
$user = "xx";
$password = "xx";
$api_id = "xx";
$baseurl = "http://promo.blastsms.in/sendsms.jsp?";
$text = urlencode("Thank you for registering with CARE MY KIDEE.. VERIFY CODE =" . $verifycode . "Please verify your mobile number immedi`enter code here`ately for our value added services.... ");
$version = "3";
//Define header array for cURL requestes
$header = array('Contect-Type:application/xml', 'Accept:application/xml');
// auth call
$url = "$baseurl/&user=$user&password=$password&mobiles=$phone&sms=$text&senderid=$api_id&version=$version";
//Define http request nouns
$ls = $url . "landscapes";
//Initialise cURL object
$ch = curl_init();
//Set cURL options
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => $header, //Set http header options
CURLOPT_URL => $ls, //URL sent as part of the request
CURLOPT_NOBODY => 1,
CURLOPT_FAILONERROR => TRUE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, //Set Authentication to BASIC
CURLOPT_USERPWD => $user . ":" . $password, //Set username and password options
CURLOPT_HTTPGET => TRUE //Set cURL to GET method
));
//Define variable to hold the returned data from the cURL request
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
if ($errorDescription) {
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
} else {
$errorDescription = 'verify';
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
}
return true;
} else {
$matches = array();
// we use ? because we want to stop at first </error-description>
// we use preg_match because we want only one error-description text
preg_match('/<error-description>(.+?)<\/error-description>/', $data, $matches);
$errorDescription = isset($matches[1]) ? $matches[1] : '';
// $errorDescription = "failed";
$sess_id = $this->session->userdata('id');
$this->generatedate_model->sendsmsdetails($errorDescription, $phone, $sess_id);
return false;
}
//Close cURL connection
curl_close($ch);
}
Try it
$data = curl_exec($ch);
if (curl_exec($ch) !== FALSE) {
Modify It
$data = curl_exec($ch);
if ($data !== FALSE) {
You are execute tow time CURL
I have already tried below code,
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
You need to use the proper Tumblr endpoint:
http://www.tumblr.com/api/write
I'm pretty sure the others won't work.
Obviously make sure that your user and pass are correct, other than that, this looks fine - it's pretty much exactly what I'd write.