How to decode a base64 email with php? - php

I'm trying to decode my message with base 64 decode method. Does anybody know how to do this, or maybe via a php function?
<?php
class Gmail
{
public function __construct($client)
{
$this->client = $client;
}
public function readLabels()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
$the_html = "";
if (count($results->getLabels()) == 0) {
// print "No labels found.\n";
$the_html .= "<p>No labels found</p>";
} else {
// print "Labels:\n";
$the_html .= "<p>labels</p>";
foreach ($results->getLabels() as $label) {
// printf("- %s\n", $label->getName());
$the_html .= "<p>" . $label->getName() . "</p>";
}
return $the_html;
}
}
/**
* Get list of Messages in user's mailbox.
*
* #param Google_Service_Gmail $service Authorized Gmail API instance.
* #param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #return array Array of Messages.
*/
public function listMessages()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$userId = 'me';
$pageToken = null;
$messages = array();
$opt_param = array();
$messagesResponse = array();
$i = 0;
do {
if ($i == 5) break;
$i++;
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
$msg = $service->users_messages->get($userId, $message->getId());
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
}
return $messages;
}
}

As mentioned on the comment above by #Marvin, try to use base64_decode function.
Here is an example:
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str); // This is an encoded string
So in your case, instead of using
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
try
echo "<pre>" . var_export(base64_decode($msg->payload->parts[1]->body->data), true) . "</pre>";
Reference
base64_decode

Related

Updating price and stock of thousands of entries in DB

I'm working on a project to update a daatabase of products (price and stock) in prestashop based on data from a vending program. I'm doing this using PHP code and a MySQL conneectio to the DB.
The problem is that there is about 58.000 products and it seems to take very long to update all products.
Here is my code:
<?php
$host = '127.0.0.1';
$uname = '*******';
$pwd = '*******';
$db = "*******";
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
echo 'Updating init...' . "<br>";
//Create an instance of the class Update to get and update the data
$update = new Update();
try
{
// Get the product list from prestashop's DB
$productsFromPS = $update->getProductListFromPS($con);
// Cycle through all the product IDs
foreach ($productsFromPS as $product)
{
// Id of the product
$id = (int) $product['id_product'];
// Price from PS
$pricePS = (float) $product['price'];
// Get the product's stock from PS
$stockPS = $update->getProductStockFromPS($con, $id);
// Physical and reserved quantities in PS
$physQty = $stockPS['physical_quantity'];
$resQty = $stockPS['reserved_quantity'];
// Get product's price and stock from Vendus
$priceAndStockVendus = $update->getPriceAndStockFromVendus($id);
// Price from Vendus
$priceVendus = (float) $priceAndStockVendus[0];
// Tools for float compardsion
$zero = (float) 0.00;
$epsilon = (float) 0.00001;
// If the price in Vendus is 0, put 0 to stock in PS
if(!(abs($priceVendus-$zero) < $epsilon))
$stockVendus = (int) $priceAndStockVendus[1];
else
$stockVendus = 0;~
// If the prices do not match, update price
if(!(abs($pricePS-$priceVendus) < $epsilon))
$update->updatePrice($con, $id, $priceVendus);
// If the stocks do not matcth, update stock
if ($stockVendus!=$physQty)
$update->updateStock($con, $id, $stockVendus, $resQty);
}
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
/*
Class which method to get and update data
*/
class Update
{
public function getProductListFromPS ($con)
{
try
{
$sql_q = mysqli_query($con,"SELECT `id_product`, `price` FROM `ps_product` ORDER BY `id_product` ASC");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo '4: ' . $output[4]['id_product'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output;
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage() . '<br>';
}
}
public function getProductStockFromPS ($con, $id)
{
try
{
$sql_q = mysqli_query($con,"SELECT `quantity`, `physical_quantity`, `reserved_quantity` FROM `ps_stock_available` WHERE `id_product` = $id");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo 'qty: ' . $output[0]['quantity'] . "<br>";
//echo 'phys qty: ' . $output[0]['physical_quantity'] . "<br>";
//echo 'res qty: ' . $output[0]['reserved_quantity'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output[0];
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function getPriceAndStockFromVendus ($id)
{
try
{
$url = 'https://www.vendus.pt/ws/v1.1/products/';
$apiKey = '***********';
$method = 'GET';
$params = array(
'reference' => $id,
);
$url .= '?' . http_build_query($params);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $apiKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
//echo 'URL to Vendus - ' . $url . '<br />';
$result = curl_exec($curl);
$resultArray = json_decode($result, true);
curl_close($curl);
return array($resultArray[0]['gross_price'], $resultArray[0]['stock']);
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updatePrice ($con, $id, $price)
{
try
{
$sql_q = mysqli_query($con,"UPDATE `ps_product` SET `price` = '$price' WHERE `id_product` = '$id'");
$sql_q = mysqli_query($con,"UPDATE `ps_product_shop` SET `price` = '$price' WHERE `id_product` = '$id' AND `id_shop` = '1'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Price updated (' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updateStock ($con, $id, $stock, $resQty)
{
try
{
$newPhysQty = $stock;
if ($newPhysQty!=0)
$newQty = $newPhysQty - $resQty;
else
$newQty = 0;
$sql_q = mysqli_query($con,"UPDATE `ps_stock_available` SET `physical_quantity` = '$newPhysQty', `quantity` = '$newQty' WHERE `id_product` = '$id'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Stock updated(' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
}
}
?>
The plan is to have this code run at certain intervals to keep the DB updated.
Am I doing something wrong? Is there a faster way to do this?
This code is running on a server with 2GB of RAM and not a very fast processor. Should it be ruinning on a computer with higher specs?
I will appreciate any remarks/critcs about the code and tips on how to improve it.
Thanks in advance! ;)
EDIT: It appears running the code produces a 500 Internal Server Error, any idea what could be causing this? If I run the foreach only once it doesn't occur. How can i check the error in detail? I have CPannel as the control panel for the server.

PHP mysqli_connect: I'm getting this error when my login page attempt to connect to the database

I'm new to my sqli the improved version of PHP.
<?php
// Class for the transparent access of MySQL
$con = mysqli_connect("host","database","port","user","passwd","conn","querytext","query_id","err","errno","record = array();","row = 0;","rows = 0;") or die ("Some error occured during connection " . mysqli_error($con));
function query($querystring) {
$this->querytext = $querystring;
$this->query_id = mysqli_query($this->querytext, $this->con);
$this->Errno = mysqli_errno($this->conn);
$this->Error = mysqli_error($this->conn);
if($this->query_id) {
if(strtolower(substr(trim($this->querytext),0,6)) == 'select'){
$this->rows = mysqli_num_rows($this->query_id);
} else {
$this->rows = 0;
}
$this->row = 0;
} else {
$this->rows = 0;
$this->row = 0;
$this->halt("Query failed!");
}
}
function setpassword($newpasswd){
$querystring = sprintf("SET PASSWORD = PASSWORD('%s')", $newpasswd1);
return $this->query($querystring);
}
function next_record() {
if($this->row < $this->rows) {
$this->record = mysql_fetch_array($this->query_id);
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row +=1;
$status = is_array($this->record);
} else {
$status = FALSE;
}
return $status;
}
function seek($pos) {
if(($pos >= 0 && $pos < $this->rows) &&
mysql_data_seek($this->query_id, $pos)) {
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row = $pos;
}
}
function close() {
$this->query = "";
$this->rows = 0;
$this->row = 0;
mysql_close($this->conn);
}
function htmltable () {
$resulttable='';
if($this->rows > 0){
$resulttable=sprintf("<table %s>", $tableoptions);
while($this->next_record()) {
/* Ueberschriften */
if($this->row == 1) {
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<th>" . $key . "</th>";
}
$resulttable=$resulttable . "</tr>\n";
reset($this->record);
} /* Ende Ueberschriften */
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<td>" . $value . "</td>";
}
$resulttable=$resulttable . "</tr>\n";
}
$resulttable=$resulttable . "</table>\n";
}
return $resulttable;
}
?>
You should be connecting to the database using PDO as it is more secure: http://php.net/manual/en/book.pdo.php
These tutorials are pretty good to follow: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://crewow.com/PHP-MySQL-Simple-Select-using-PDO-in-Bootstrap.php
Also, please make sure that your database credentials are in a separate file that gets included into the file you use to connect to the database.

Trying to get property of non-object CRUD

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.
Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

Facebook-PHP-SDK Getting friends list is very slow

Using below code to get friend's list ,But its takes lot of time to give the result.How can I get the result quicker.Can anyone help me to solve this issue?
or is there any other way I can get friends list?
try {
$requestFriends = $fb->get('/me/taggable_friends?fields=name&limit=100');
$friends = $requestFriends->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// if have more friends than 100 as we defined the limit above on line no. 68
if ($fb->next($friends)) {
$allFriends = array();
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
while ($friends = $fb->next($friends)) {
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
}
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
}
} else {
$allFriends = $friends->asArray();
$totalFriends = count($allFriends);
$counter = 0;
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
$counter++;
}
echo $counter;
}

How to run MySQL query with transaction in Zend Framework 2

I have zf2 model. Inside the model, there is a function to communicate with the database with transaction.
Between the transaction I'm calling a recursive function to do transaction, where I'm passing the transaction object. Without recursive function calling it's running fine, but when I'm going to call any function where some query is running, it sends false, and due to receiving false it's being rollbacked. Below are the example code:
<?php
namespace Admin\Model;
use Zend\Db\TableGateway\TableGateway;
use Exception;
class ProjectAssignTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* $empidArray = array(1, 2, 3, 5, 12, 35);
*/
public function saveProjectAssignment($project_id, $empidArray, $data) {
$connection = $this->tableGateway->getAdapter()->getDriver()->getConnection();
$connection->beginTransaction();
try {
$sqlDelete = "DELETE FROM rjs_assignproject WHERE project_id= '" . $project_id . "' ";
$connection->execute($sqlDelete);
for ($x = 0; $x < count($empidArray); $x++) {
$sqlInsert = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $empidArray[$x] . "',designation_id='" . $data['desgi_' . $empidArray[$x]] . "',comment='" . $data['comment_' . $empidArray[$x]] . "',datetime_from='" . $data['time_from' . $empidArray[$x]] . "',datetime_to='" . $data['time_to' . $empidArray[$x]] . "' ";
$resultHistory = $connection->execute($sqlInsert);
if (!$this->recursiveEntry($connection, $empidArray[$x], $project_id)) {
throw new Exception();
} else {
return true;
}
}
$connection->commit();
return true;
} catch (Exception $ex) {
$connection->rollback();
}
}
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true;
}
}
}
} catch (Exception $ex) {
return false;
}
}
}
Your method doesn't return anything after try/catch block:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
// ...
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true; // We will never get here
}
} catch (Exception $ex) {
return false;
}
// return null
}
Try this:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
}
}
}
} catch (Exception $ex) {
return false;
}
return true;
}

Categories