Tableau get ticket with PHP - php

please can you assist. I'm trying to get a ticket from the tableau server via PHP. Currently my ISP and my Server IP address is listed as trusted IPs on the tableau servers. If I use javascript on my remote server then I get the ticket but for some reason I cannot get any result with PHP and have tried a range of php code snippets. If I can get any one of them to work I will do the splits with joy.
NB: In the javascript version I need to enter the target_site which is the same as the username otherwise I don't get a result. Also note the :8000 port on the end of the url.
This is the working html/javascript version (returns a valid ticket, eg 128018285):
<script type="text/javascript">
function submitForm(){document.getElementById('form1').action = document.getElementById('server').value + "/trusted";}
</script>
<form method="POST" id="form1" onSubmit="submitForm()">
<table class="style1">
<tr>
<td class="style2">
Username:</td>
<td>
<input type="text" name="username" value="" /></td>
</tr>
<tr>
<td class="style2">
Server: </td>
<td>
<input type="text" id="server" name="server" value="http://" /></td>
</tr>
<tr>
<td class="style2">
Client IP (optional):</td>
<td>
<input type="text" id="client_ip" name="client_ip" value="" /></td>
</tr>
<tr>
<td class="style2">
Site: (leave blank for Default site, else NameOfSite if using sites)</td>
<td>
<input type="text" id="target_site" name="target_site" value="" /></td>
</tr>
<tr>
<td class="style2">
<input type="submit" name="submittable" value="Go" /></td>
<td>
</td>
</tr>
</table>
</form>
Here is my code, snippet 1 using file_get_contents
$remote_addr = $_SERVER['REMOTE+ADDR'];
$params = array(
'username' => 'myusername',
'client_ip' => $remote_addr,
'target_site' => 'myusername'
);
$context = stream_context_create($params);
$ticket = file_get_contents('http://mysite.com:8000/trusted', false, $context);
if ($ticket > 0) {
return $ticket;
}
else
return 0;
Another code snippet using curl
$server = 'myserver.com:8000';
$url = 'http://'.$server.'/trusted';
$fields_string ='target_site=myusername&username=myusername';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip'));
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
return curl_exec($ch);
curl_close($ch);
Another code snippet using fopen
$url = 'http://myserver.com:8000/trusted';
$data = array ('username' => 'myusername','target_site' => 'myusername', 'format' => 'txt');
$data = http_build_query($data);
$params = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n"
.'Accept-Encoding:' . "\r\n"
));
if($optional_headers != null)
{
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $url, $php_errormsg");
}
$response='';
while (!feof($fp))
{
$response = $response.fgets($fp);
}
if ($response === false)
{
throw new Exception("Problem reading data from $url, $php_errormsg");
}
fclose($fp);
return $response;
Many Many Thanks in advance...

Tableau has sample PHP which works (it's running on my machine as I type). Have you tried it?
This post actually refers to the same sample code and extends it just a touch so it can be called by way of JS:
Generate tableau trusted ticket using AJAX
The sample code in question can be found in:
C:\Program Files (x86)\Tableau\Tableau Server\8.0\extras\embedding\php
It looks fairly similar to yours, but POSTs using http_post_fields()
<?php
// Returns a trusted URL for a view on a server for the
// given user. For example, if the URL of the view is:
// http://tabserver/views/MyWorkbook/MyView
//
// Then:
// $server = "tabserver";
// $view_url = "views/MyWorkbook/MyView";
//
function get_trusted_url($user,$server,$view_url) {
$params = ':embed=yes&:toolbar=yes';
$ticket = get_trusted_ticket($server, $user, $_SERVER['REMOTE_ADDR']);
if($ticket > 0) {
return "http://$server/trusted/$ticket/$view_url?$params";
}
else
return 0;
}
// Note that this function requires the pecl_http extension.
// See: http://pecl.php.net/package/pecl_http
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
Function get_trusted_ticket($wgserver, $user, $remote_addr) {
$params = array(
'username' => $user,
'client_ip' => $remote_addr
);
return http_parse_message(http_post_fields("http://$wgserver/trusted", $params))->body;
}
?>

Sorry, seems that my web host was blocking port 8000, which is why the code was not working.
For reference, this was the most concise piece of code that did the trick, change the variables for your own, myusername, mytargetsite, http://example.com/trusted
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => 'username=myusername&target_site=mytargetsite'
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/trusted', false, $context);
if ($result === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
else echo $result;

With your suggestion, I used cURL request and I have solved your problem with cURL request as following:
function get_trusted_ticket($wgserver, $user, $remote_addr) {
$server = $wgserver;
$url = 'http://'.$server.'/trusted';
$fields_string ='target_site=$remote_addr&username=$user';
$ch = curl_init($url);
$data = array('username' => $user, 'client_ip' => $remote_addr);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec($ch);
curl_close($ch);
}

Related

fetching imgur cURL to json_decode php upload form

i'm trying to use imgur as a uploading backend - i guess it secure my website if there's upload picture (is it right?) so
i went with this way :
<?php
$client_id = 'xxxxx';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
HTML form
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
when i click on submit the result is fine as i guess ^^
Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}
but my problem i want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.imgur.com/TvFtE29.png'; to added into my database -> user pic
i went with json_decode but it's not completed with me in the right way, if someone can help with this issue 🌹
thanks.
json_decode worked fine here:
$json_returned = json_decode($json_returned, true);
$uploaded = $json_returned['data']['link'];

How to send push notifications to android mobile from php in react-native?

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 !! "
}
}
}

Fix request failed using php

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

Why No response from Google Invisible recaptcha?

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.

Wistia upload using PHP cURL

Does anyone know how to upload a video to Wistia using PHP cURL from a file upload input specified within a form? This is my code but I cannot seem to get this to work with the current API. I’ve looked at a few similar posts on this subject but still no luck...
<?php
$pathToFile = $_FILES['fileName']['tmp_name']; /* /tmp/filename.mov */
$nameOfFile = $_FILES['fileName']['name']; /* filename.mov */
$data = array(
'api_password' => '********',
'file' => '#'.$pathToFile,
'project_id' => '********'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
?>
UPDATE - FULL CODE (still not working)
cURL returns false for both curl_exec and curl_error when using "'file' => '#'.$pathToFile" but works fine when using "'url' = 'http://example.com/file.mov'... Perhaps I'm not processing the form properly? Here's the full code:
<?php
if ($_POST['submit']) {
$filePath = $_FILES['fileUploaded']['tmp_name'];
$fileName = $_FILES['fileUploaded']['name'];
$fileSize = $_FILES['fileUploaded']['size'];
echo("File Path: ");
echo $filePath;
echo '<br>';
$data = array(
'api_password' => '******',
/* 'url' => 'http://example.com/file.mov', WORKS */
'file' => '#'.$filePath, /* DOES NOT WORK */
'project_id' => '******'
);
// WORKING CMD LINE
// curl -i -F api_password=****** -F file=#file.mov https://upload.wistia.com/
/* cURL */
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($data)
));
// Send the request
$KReresponse = curl_exec($chss);
$KError = curl_error($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo '<br>';
echo("Response:");
print_r($KReresponseData);
echo '<br>';
echo("Error:");
print_r($KError);
}
?>
<form name="upload-form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="file" name="fileUploaded">
<input type="submit" name="submit" value="Upload">
</form>
Any help would be much appreciated!
Try this:
$filePath = "#{$_FILES['fileUploaded']['tmp_name']};filename={$_FILES['fileUploaded']['name']};type={$_FILES['fileUploaded']['type']}";

Categories