LinkedIn API - Setting user status saying unauthorised - json

So I've been following through various tutorials and documents to get this working and am really struggling. These are the files required for it to work:
Required Files
auth.php
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token.
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to.
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup:
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member.
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is linkedin library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The Problem
Trying to set the status
To set the status update I have tried using this in the demo.php file:
$setStatus = "Testing API";
$statusResponse = $linkedin->setStatus("~:($setStatus)");
echo '<pre>';
var_dump($statusResponse);
echo '</pre>';
But it is giving me this error:
Setting status... ~:(Testing API)
string(343) "
401
1407931633217
DW74ALZZVN
0
[unauthorized]. OAU:xxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxx|*01|*01:1407931633:eyA6PiJzKUJixQLLtaQL90wppHI=
"
P.S: I x'd out the key there, but they are correct and the rest of the script works with them.
How do I set the status of the authorised account? So I've been following through various tutorials and documents to get this working and am really struggling. These are the files required for it to work:
Required Files
auth.php
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token.
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to.
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup:
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member.
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is linkedin library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The Problem
Trying to set the staus
To set the status update I have tried using this in the demo.php:
$setStatus = "Testing API";
$statusResponse = $linkedin->setStatus("~:($setStatus)");
echo '<pre>';
var_dump($statusResponse);
echo '</pre>';
But it is giving me this error:
Setting status... ~:(Testing API)
string(343) "
401
1407931633217
DW74ALZZVN
0
[unauthorized]. OAU:xxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxx|*01|*01:1407931633:eyA6PiJzKUJixQLLtaQL90wppHI=
"
P.S: I x'd out the key there, but they are correct and the rest of the script works with them.
How do I set the status of the authorised account?

Not sure if it is still relevant, and the current-status API is deprecated, but the line:
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
needs to be changed to:
$xml = "" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "";

Related

How to Make Forgot Password in Codeigniter, Password send in email

Hello guyz i have create small kind of application in codeigniter,in this application i am doing forgot password module, i have created a function but dont know why its not working, i need random password have to been send in mail which will be autogenerated , but email method does not work, so give me some suggestion.
Here is My view:
<form action="<?php echo base_url() . "welcome/forgotpassword" ?>" method="POST">
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" name="user_email" />
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="Send">
</div>
</div>
</form>
Here is my Controller:
public function forgotpassword(){
$email = $this->input->post('user_email');
$findemail = $this->main_model->ForgotPassword($email);
$this->load->view('forgotpassword');
if ($findemail) {
$this->main_model->sendpassword($findemail);
} else {
$this->session->set_flashdata('msg', 'Email not found!');
}
}
Here is My model:
public function sendpassword($data) {
$email = $data['user_email'];
print_r($data);
$query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
$row = $query1->result_array();
if ($query1->num_rows() > 0) {
$passwordplain = "";
$passwordplain = rand(999999999, 9999999999);
$newpass['user_password'] = md5($passwordplain);
$this->db->where('user_email', $email);
$this->db->update('user_registration', $newpass);
$mail_message = 'Dear ' . $row[0]['full_name'] . ',' . "\r\n";
$mail_message .= 'Thanks for contacting regarding to forgot password,<br> Your <b>Password</b> is <b>' . $passwordplain . '</b>' . "\r\n";
$mail_message .= '<br>Please Update your password.';
$mail_message .= '<br>Thanks & Regards';
$mail_message .= '<br>Your company name';
require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPSecure = "tls";
$mail->Debugoutput = 'html';
$mail->Host = "ssl://smtp.googlemail.com";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = "xxxxxxxxx#gmail.com";
$mail->Password = "xxxxxxxx";
$mail->setFrom('xxxxxxx#gmail.com', 'admin');
$mail->IsHTML(true);
$mail->addAddress('user_email', $email);
$mail->Subject = 'OTP from company';
$mail->Body = $mail_message;
$mail->AltBody = $mail_message;
if (!$mail->send()) {
$this->session->set_flashdata('msg', 'Failed to send password, please try again!');
} else {
echo $this->email->print_debugger();
$this->session->set_flashdata('msg', 'Password sent to your email!');
}
}
}
This function may have something to do with it... can you show us that?
$findemail = $this->main_model->ForgotPassword($email);
When you use print_r($data) is anything returned?
If not, $query1 will be 0 or null and everything will break.
// core function
public function sendpassword($data) {
// include your libary at the top
require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
// email retrieved from the ForgotPassword() method.
$email = $data['user_email'];
// get the user_info array row
$query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
$row = $query1->result_array();
if ($query1->num_rows() > 0) {
// assign users name to a variable
$full_name = $row['full_name'];
// generate password from a random integer
$passwordplain = rand(999999999, 9999999999);
// encrypt password
$encrypted_pass = $this->pass_gen($passwordplain);
$newpass['user_password'] = $encrypted_pass;
// update password in db
$this->db->where('user_email', $email);
$this->db->update('user_registration', $newpass);
// begin email functions
$result = $this->email_user($full_name, $email, $passwordplain);
echo $result;
}
}
// email sending
public function email_user($full_name, $email, $passwordplain) {
// compose message
$mail_message = 'Dear ' . $full_name. ',' . "\r\n";
$mail_message .= 'Thanks for contacting regarding to forgot password,<br> Your <b>Password</b> is <b>' . $passwordplain . '</b>' . "\r\n";
$mail_message .= '<br>Please Update your password.';
$mail_message .= '<br>Thanks & Regards';
$mail_message .= '<br>Your company name';
// email config
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPSecure = "tls";
$mail->Debugoutput = 'html';
$mail->Host = "ssl://smtp.googlemail.com";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = "xxxxxxxxx#gmail.com";
$mail->Password = "xxxxxxxx";
$mail->setFrom('xxxxxxx#gmail.com', 'admin');
$mail->IsHTML(true);
$mail->addAddress('user_email', $email);
$mail->Subject = 'OTP from company';
$mail->Body = $mail_message;
$mail->AltBody = $mail_message;
// send the mail
if (!$mail->send()) {
return $this->email->print_debugger();
$this->session->set_flashdata('msg', 'Failed to send password, please try again!');
} else {
return $this->email->print_debugger();
$this->session->set_flashdata('msg', 'Password sent to your email!');
}
}
// Password encryption
public function pass_gen($password) {
$encrypted_pass = md5($password);
return $encrypted_pass;
}
$query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
it is has sql injection!

phpmail gmail Could not connect to SMTP

Tried using the code below which has been working for years until last week. Some change on Gmail side perhaps. But its just not working even if various combinations are tried.
Allow unsafe apps is ON still unable to connect SMTP
<?php
sendMail("tosomeid#gmail.com", "fromsomeid#gmail.com", "test", "test msg<br>hello!");
function sendMail($to, $from, $subject, $message) {
try {
//$to='tosomeid#gmail.com';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From:' . $from . ' <fromsomeid#gmail.com>' . "\r\n";
ini_set("sendmail_from", "fromsomeid#gmail.com");
require_once("class.phpmailer.php");
require_once("class.smtp.php");
set_time_limit(240);
$mail = new PHPMailer(true);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAutoTLS = false;
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 4;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 587; // or 587 // set the SMTP port for the GMAIL server
$mail->Username = "fromsomeid#gmail.com"; // SMTP account username
$mail->Password = "password123"; // SMTP account password
$mail->From = "fromsomeid#gmail.com";
$mail->SMTPSecure = 'tls';
$mail->AddAddress("tosomeid#gmail.com");
$mail->SetFrom('fromsomeid#gmail.com', $from);
$mail->AddReplyTo("fromsomeid#gmail.com", $from);
$mail->AddBCC("tosomeid#gmail.com");
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->WordWrap = 50;
echo 'sendMail to=>' . $to;
if (!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo '<br>Message was sent successfully to selected recipients.';
}
} catch (Exception $ex) {
echo'EXCEPTION <br>';
echo '<br>Caught exception: ' . $ex->getMessage() . "\n".$ex->getTraceAsString();
}
}
?>
You add SMTPOption to config Phpmailer
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

converting single PHP mySQL update into mass MySQL update

Ok so thank you for the feedback until now, with it I have got to the following point:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "madtags";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = mysqli_query($conn, "SELECT id from users");
$userinfo = array();
while ($row_user = $sql->fetch_assoc())
$userinfo[] = $row_user;
foreach ($userinfo as $user) {
$url = "http://www.pdga.com/player/".$user['id'];
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
#$dom->loadHTML($html);
$xpath = new DomXPath($dom);
$class = 'current-rating';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' $class ')]");
foreach($divs as $div) {
preg_match('/Current Rating:\s+(\d+)/', $div->nodeValue, $results);
}
$sql = "UPDATE users SET rating=$results[1] WHERE id=id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully <br>";
} else {
echo "Error updating record <br> " . $conn->error;
}
$conn->close();
}
?>
By changing the "where" command on row 45 "$sql = "UPDATE users SET rating=$results[1] WHERE id=id";", i can get it to run properly (this is a test array of 6 rows)
Record updated successfully
Error updating record
Error updating record
Error updating record
Error updating record
Error updating record
But I guess I am defining something wrong as it is not able to update the record after the first run.
Ideas?
original post
I am creating a competition website, parallel to a rating system used by a worldwide website. So basically I have created the code below to call for a rating from the website.
Since creating this, the member base has ballooned greatly. So creating this code individually for each member is not useful anymore. So I would need to develop this to basically run for each row in my MySQL table (this code is run every 2 weeks approx.)
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "madtags";
$url = "http://www.pdga.com/player/***ID***";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
#$dom->loadHTML($html);
$xpath = new DomXPath($dom);
$class = 'current-rating';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' $class ')]");
foreach($divs as $div) {
preg_match('/Current Rating:\s+(\d+)/', $div->nodeValue, $results);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET rating=$results[1] WHERE id=***ID***";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
So basically variable for each individual line are the parts marked ID ($url and $sql update).
Further, the table currently has 4 columns >> id, name, tag, rating
Thanks a bunch ahead of time.

quickbooks online interaction

I have a web app that I need to communicate with quickbooks online edition. I am able connect and receive data. The problem is is that the responce back that i get is not in a xml format or even better would be in json formate. How can I get it to respond back in one of those formats? Here is my code:
function request($xml, $certificate = null, $debug = false){
$ch = curl_init();
$header[] = 'Content-Type: application/x-qbxml';
$header[] = 'Content-Length: ' . strlen($xml);
$params = array();
$params[CURLOPT_HTTPHEADER] = $header;
$params[CURLOPT_POST] = true;
$params[CURLOPT_RETURNTRANSFER] = true;
$params[CURLOPT_URL] = $this->gateway;
$params[CURLOPT_TIMEOUT] = 30;
$params[CURLOPT_POSTFIELDS] = $xml;
$params[CURLOPT_VERBOSE] = $debug;
$params[CURLOPT_HEADER] = true;
// This is only for the HOSTED security model
if (file_exists($certificate))
{
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSLCERT] = $certificate;
}
// Some Windows servers will fail with SSL errors unless we turn this off
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSL_VERIFYHOST] = 0;
// Diagnostic information: https://merchantaccount.quickbooks.com/j/diag/http
// curl_setopt($ch, CURLOPT_INTERFACE, '<myipaddress>');
$ch = curl_init();
curl_setopt_array($ch, $params);
$response = curl_exec($ch);
if (curl_errno($ch))
{
$errnum = curl_errno($ch);
$errmsg = curl_error($ch);
_log('CURL error: ' . $errnum . ': ' . $errmsg, $debug);
return false;
}
// Close the connection
#curl_close($ch);
// Remove the HTTP headers from the response
$pos = strpos($response, "\r\n\r\n");
$response = ltrim(substr($response, $pos));
return $response;
}
function item_list(){
$xml =
'<?xml version="1.0"?>
<?qbxml version="6.0"?>
<QBXML>
<SignonMsgsRq>
<SignonTicketRq>
<ClientDateTime>' . date('Y-m-d') . 'T' . date('H:i:s') . '</ClientDateTime>
<SessionTicket>' . $this->session . '</SessionTicket>
<Language>English</Language>
<AppID>' . $this->application_id . '</AppID>
<AppVer>1</AppVer>
</SignonTicketRq>
</SignonMsgsRq>
<QBXMLMsgsRq onError="stopOnError">
<ItemQueryRq>
<OwnerID>0</OwnerID>
</ItemQueryRq>
</QBXMLMsgsRq>
</QBXML>';
$response = $this->request($xml, null, true);
echo $response;
}
Thanks
Here my xml request:
$xml =
'
' . date('Y-m-d') . 'T' . date('H:i:s') . '
' . $this->session . '
English
' . $this->application_id . '
1
0
</QBXMLMsgsRq>
</QBXML>';
Here is my responce:
2013-04-12T12:28:11 V1-115-Q03kydq32h22tnfqnd5izf:689712285 1 2013-04-10T06:02:40 2013-04-10T06:02:40 0 Sales Sales 0 0 1 Sales 2 2013-04-10T21:20:43 2013-04-10T21:20:43 0 test product test product 0 0 1 Sales
My stupid mistake. I was echoing my result to browser which interpreted xml tags as html tags. I used $xml = simplexml_load_string($response); print_r($xml); to view response in browser.

integrating a function

this is the follow-up to my question about getting a div's content. the second function is the one im having a hard time with. im pretty sure i can call a function from another one, but im not sure about placing them into oneanother like i did here. its obviously a silly attempt to make the code work, since it gives me an error:
Blackline Frostbyte : in stock. : $139.99
Fatal error: Cannot redeclare get_string_between() (previously declared in /home/rambazar/public_html/cron.php:69) in /home/rambazar/public_html/cron.php on line 69
as i see this, the code is partially ok, because it gets a products stock info and the price tag, but the code stops and i cant figure out where get_string_between is redeclared, as it is only called. please help me sorting this out, thanks!
<?php
set_time_limit(1800);
include("admin/include/db.php");
error_reporting(E_ALL);
$res=mysql_query("select * from products");
while($row=mysql_fetch_array($res))
{
$availability=getavailability($row['newegg_productid']);
$price=getprice($row['newegg_productid']);
echo $row['productname']." : ".$availability." : ".$price."<br />";
}
function getavailability($itemId)
{
$url=trim("http://www.newegg.com/Product/Product.aspx?Item=".$itemId);
$ch = curl_init();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$content = curl_exec ($ch);
curl_close ($ch);
$content=strtolower($content);
$buff=$content;
$isAvailable=false;
$pos1=strpos($content,'<p class="note">')+16;
if($pos1==16)return "";
$pos2=strpos($content,'</p>',$pos1);
$availability= trim(substr($content,$pos1,($pos2-$pos1)));
return strip_tags($availability);
}
function getprice($itemId)
{
function get_string_between($string, $start, $end)
{
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0)
return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$data = file_get_contents("http://www.newegg.com/Product/Product.aspx?Item=".$itemId);
$pricediv = get_string_between($data, '<div class="current" id="singleFinalPrice"><span class="label">Now:', '</div');
$price = strip_tags($pricediv);
return $price;
}
?>
Take out the get_string_between() out of the getprice() function and you should be good to go:
function get_string_between($string, $start, $end)
{
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0)
return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
function getprice($itemId)
{
$data = file_get_contents("http://www.newegg.com/Product/Product.aspx?Item=".$itemId);
$pricediv = get_string_between($data, '<div class="current" id="singleFinalPrice"><span class="label">Now:', '</div');
$price = strip_tags($pricediv);
return $price;
}