I have a two pages in my website, one is named "new_account.php" and the other is "visitor.php". The user can choose to create a new account for themselves or just go with a visitor account.
When the user picks "visitor" I make a request to "new_account.php" to create a temporary account with a random username and password, to be deleted later when the user is done. I'm using file_get_contents for the request, since the page returns the user hash which I use to automatically login the user.
This is "visitor.php":
$url = getBaseUrl().'new-account.php';
$data = array(
'name' => $tempName,
'character-name' => $tempCharacterName,
'gender' => $tempGender,
'age' => $tempAge,
'parent-email' => $tempParentEmail,
'password' => $tempPassword,
'password-confirmation' => $tempPassword,
'temporary' => TRUE
);
$options = array(
'http' => array(
'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);
var_dump($result);
if($result != "error") {
User::loginUser($result, TRUE, $conn);
User::ifUserLoggedRedirect('game.php',$conn);
}
My problem is that, while the request is successful and a new random user is inserted in the database, when User::loginUser tries to query the user data using the hash returned by file_get_contents (such as the user icon or user name) I'm getting an empty result set.
User::loginUser is this:
public static function loginUser($userHash, $temporary, $conn) {
if(User::isAnyLogged($conn))
User::logout($conn);
User::safeSessionStart();
$result = $conn->prepare('SELECT p.screen_name, pi.url, p.id FROM player as p, player_icon as pi WHERE p.user_hash=? AND pi.id = p.player_icon_id');
$result->bind_param('s',$userHash);
$result->execute();
$res = $result->get_result();
if($res->num_rows == 0) {
die("Invalid user with hash ".$userHash);
}
$user_info = $res->fetch_assoc();
$_SESSION['user'] = new User($userHash, $temporary, $user_info['screen_name'], $user_info['url'], $user_info['id']);
setcookie('userHash',$userHash);
setcookie('temporary',$temporary ? '1' : '0' );
return $_SESSION['user'];
}
And the call always dies with an invalid hash, but if I query the user from phpmyadmin using the hash the user is actually there. Going through the normal registration by accessing "new_account.php" also works.
The first thing I tried was closing and reopenning the connection after getting the result from file_get_contents but that didn't work. Using mysqli::refresh also didn't work. I tried moving the login part of the code to the "new_account.php" but apparently I also can't set the $_SESSION from a request using file_get_contents.
I also could solve this by copying the new account code to the visitor page, but I would rather keep the account creation in a single page. Is there anything else I can try?
You should use require_once to include the new-account.PHP
This way, you can use the code of the included file as if it were in the file from where you include it.
Related
We are using Woocommerce for our ecom website and in order to automatically generate government-approved invoices for customers we use a certified online invoicing software.
I am making an API request to this invoicing software in order to retrieve the generated invoice document from their database, this is the code:
// On Order complete > Get document ID from order > access Moloni invoicing API > get document link GETPDFLINK > Sanitize the string and get Hash > generate the final document link > access it and download the PDF
function download_moloni_document_id( $order_id, $order ) {
// Retreive from the Database table moloni_api the access token from column main_token
global $wpdb;
$table_name = "db_invoicing_api";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE id = 1" );
foreach ($retrieve_data as $retrieved_data) {
$maintoken = $retrieved_data->main_token;
}
// Get document ID from the order
$documentid = get_post_meta($order->id, '_moloni_sent', true);
// Connect to moloni API and getpdflink
$url = "https://api.moloni.pt/v1/documents/getPDFLink/?access_token=$maintoken";
$postData = array(
'company_id' => '12345',
'document_id' => $documentid );
$arguments = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'body' => $postData,
);
$response = wp_remote_post( $url, $arguments );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
return "Something went wrong: $error_message";
} else {
echo '<pre>';
var_dump( wp_remote_retrieve_body( $response ) );
echo '</pre>';
// jsondecode the string received by the API to remove backslashes, get and parse the URL and extract the HASH key
$response2 = wp_remote_retrieve_body($response);
parse_str(parse_url(json_decode($response2, true)['url'], PHP_URL_QUERY), $result);
$hash = $result['h'];
// Assemble the Invoice HTML download URL with the Hash and document ID
$fileUrlpdf = "https://www.moloni.pt/downloads/index.php?action=getDownload&h=$hash&d=$documentid&e=$loginmail&i=1&t=n";
$pdforderid = $order->id;
// Save the file with document id name to server location
$saveTopdf = "ftp://myserver/INVOICES/evo-$pdforderid.PDF";
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf)
);
} }
add_action( 'woocommerce_order_status_completed', 'download_moloni_document_id', 20, 2 );
In the end you can see I use
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf) );
in order to visit the link, retrieve the PDF and download it.
This works well then the link is generated successfully and sends to a direct download of the invoice PDF
The problem I have is is, sometimes there is an issue and the invoice PDF is not generated, this makes it so that the final link $fileUrlpdf does not lead to a download but instead to a web page with an error message saying something like "No Documents Found" which leads this code to download a PDF of dozens of pages containing the source code/HTML of that page. This is a problem because the PDFs (invoices) are later automatically printed by our system, so we sometimes end up with hundreds of pages of HTML code instead of the invoices.
I have tried to solve this in the following way through conditions:
to check if the download/PDF file exists
if (file_exists($fileUrlpdf)) {
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf)); }
one that would check the $response array for the error message and not proceed (because
$invalid = 'No Documents Found'; if (strpos($response, $valid) !== false) {echo 'No Documents found'; else { *download the PDF* } }
I have also considered the possibility of
checking if the page $fileUrlpdf would contain "No Documents Found", to not download it but I haven't been able to figure this one out either.
Bear with me as you can see my experience with PHP is limited so I would like to ask, what would be the best practice here? What approach would you suggest?
Thank you very much in advance for the attention and advice.
Either look at using the API to fetch the invoice/document and handle errors that way moloni.pt/dev
Or you could look at checking the Content-Type of the response headers as shown below
get_headers
$fileUrlpdf = "https://www.moloni.pt/downloads/index.php?action=getDownload&h=$hash&d=$documentid&e=$loginmail&i=1&t=n";
$fileHeaders = get_headers($fileUrlpdf, true)
if($fileHeaders['Content-Type'] === 'application/pdf') {
// PDF response
}
I have a work to do and I need to login to the webpage, and extract content from it.
The query has to be made of a username and an access key.
The problem is that I don't really know how to make a query with thos 2 elements, and in PHP.
So, I have found this code have this code :
$ak = "accesskey";
$username = 'admin';
$password = '123';
$remote_url = 'http://192.168.1.78/index.php';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Basic " . base64_encode("$username:$ak")
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);
print($file);
But the output is simply the Webpage code, from the <!DOCTYPE html><html> to </html>
According to the webpage REST API, the result that I need to get is this :
{
success: true,
result: json_result
}
Any idea why it doesn't work ?
PS : here is the API documentation : https://www.vtiger.com/docs/rest-api-for-vtiger#/Authentication
The vTiger API (in 7.2 at least) has an odd combination of parameter and form POST payloads. Here is the Python script I used to get started. Note that it uses param in the getchallenge hit but data in the login hit:
import requests
from hashlib import md5
import urllib3
urllib3.disable_warnings() # shut up whining about that security stuff
encoding = 'ascii'
userName = 'Michael'
userToken = (access key from my preferences page)
APIURL='https://our.crm.instance/webservice.php'
session = requests.Session()
def getSession(session, name, token):
response = session.get(APIURL, params={'operation':'getchallenge', 'username':userName}, verify=False)
token_key = response.json()['result']['token']
combined = token_key + userToken
accessKey = md5(combined.encode(encoding)).hexdigest()
response1 = session.post(APIURL,
data={'operation':'login', 'username':userName, 'accessKey':accessKey},
verify=False)
return response1.json()['result']['sessionName']
sessionToken = getSession(session, userName, userToken)
types = session.get(APIURL, params={'operation':'listtypes', 'sessionName':sessionToken})
print(types.json())
I can upload files from the PHP SDK, It is uploading and also getting the shared link back.
But my issue is, how I can make and empty folder with password protected shared link. I am researching on it, but I could not find a good way to do it.
Here is waht I researched.
$response = $dropbox->postToAPI("/sharing/create_shared_link_with_settings", ["path" => "/BABERZAMAN/hello-world.txt", "settings" => ['requested_visibility' => 'public']]);
$data = $response->getDecodedBody();
var_dump($data);
This is what I am using and Uploading files.
$db_path = "/".$db_folders."/".$file_renamed;
$file = $dropbox->upload($dropboxFile, $db_path , ['autorename' => true]);
$pathToFile = $db_path;
$response = $dropbox->postToAPI("/sharing/create_shared_link", [
"path" => $pathToFile,
"short_url" => false,
]);
$shared_link = $response->getDecodedBody();
$db_shared_link = $shared_link["url"];
So for now I have just 2 issues.
Make empty folder
Get that folder's shared link but password Protected
For Random Password I can use rand(0000000000,99999999);
I got the issue solved for Creating empty Folder
$MainDirectory = '/BABERTEST';
//Create empty folder
$MakeFolder = $dropbox->createFolder($MainDirectory);
$response = $dropbox->postToAPI("/sharing/create_shared_link", [
"path" => $MainDirectory,
]);
$shared_link = $response->getDecodedBody();
$BackupLink = $shared_link["url"];
echo $BackupLink;
But the other Part, Sharing Link with Password is still pending. Need help
I got it fixed by myself.
$response = $dropbox->postToAPI("/sharing/create_shared_link_with_settings", [
"path" => $MainDirectory,
"settings" => ['requested_visibility' => 'password', 'link_password' => '123456']
]);
I am trying to tweet an image using php. I have read the documentation and followed a some tutorials. I don't have any problem when sending a message; however, it does not work with images. I can not find where my mistake is, can anyone help?? I would deeply appreciate it.
<?php
$comments = $_POST['comment'];
if (isset($_POST['Twitter']))
{
require_once('twitter/codebird-php/src/codebird.php');
\Codebird\Codebird::setConsumerKey("xxxxxx","xxxxxx");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("xxxxxx", "xxxxxxxxxx");
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
$reply = $cb->statuses_update($params);
echo "You have posted your message succesfully";
}
else{
echo "You havent posted anythingh";
}
?>
You need to supply Twitter the fully qualified URI to your image.
You have the following code:
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
Unfortunately, that's not a complete URL to an image, it's a relative URL. Instead, you need to provide something along the lines of this:
$params = array(
'status' => $comments,
'media[]' => "http://www.example.com/images/image1.jpg"
);
In addition, according to the Twitter API v1 documentation, you need to use statuses/update_with_media instead of statuses/update.
If you are using Twitter API v1, Twitter also recommends using v1.1 instead.
hello i need somehow to get top Regional interest and interest over time from
http://www.google.com/trends?q=lingerie+&ctab=0&geo=id&date=all&sort=0
or better
http://www.google.com/insights/search/#q=lingerie&geo=ID&cmpt=q
so i found out that we have to login to export data can anybody give me an example doing this with our google username and password? maybe using curl to export the data? or something else
Thanks for looking in
Adam Ramadhan
Just to be quick about it, I used my xhttp class which is a curl wrapper, and I think the code is easy enough to follow.
<?php
header('content-type: text/plain');
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'trendspro', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
);
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Test if unsuccessful
if(!$response['successful']) {
echo 'response: '; print_r($response);
die();
}
// Extract SID
preg_match('/SID=(.+)/', $response['body'], $matches);
$sid = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the SID in cookies
$data['cookies'] = array(
'SID' => $sid
);
$response = xhttp::fetch('http://www.google.com/insights/search/overviewReport?q=lingerie&geo=ID&cmpt=q&content=1&export=1', $data);
// CSV data in the response body
echo $response['body'];
?>
The result is at: http://codecri.me/apps/test/test.google.trends.php
But I'm not sure if the result is what you are looking for.
Since April 2012 Google changed it's auth policy, edit the Arvin's code as follows:
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the Authorization header
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth='.$auth
);
The curl man page describes how to provide username and password. Have you tried the -u flag?
-u/--user
Specify the user name and password to use for server authentication. Overrides -n/--netrc and --netrc-optional.
If you just give the user name (without entering a colon) curl will prompt for a password.
If you use an SSPI-enabled curl binary and do NTLM authentication, you can force curl to pick up the user name and password from your environment by simply specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.