how to create zip from images base64 php - javascript

var imgAlums = window.document.getElementsByClassName("imgAlu");
var photos= [];
for (var i = 0; i < imgAlums.length; i++) {
photos.push(imgAlums[i].currentSrc);
}
//the photos array is filled //photos[0]=
data:image/;base64,/9j/4AAQSkZJRgABAQAAAQA...;
//photos[1]=data:image/;base64,/9j/4AAFWEJDKWMDCIWUEIOD...;
$.ajax({
type: 'POST',
url: '<?= URL_PROYECTO_SEGURO ?>/panel/assets/php/generateZipPhotos.php',
data: {"photos": JSON.stringify(photos)},
success: function (data) {
console.log(data);
alert("Operacion realizada con exito");
}
});
PHP code:
$nameZip = "test.zip";
$zip = new ZipArchive();
$zip->open($nameZip, ZipArchive::OVERWRITE);
$zip->addEmptyDir("Photos");
$photos= json_decode($_POST["photos"], true);
for ($i = 0; $i < count($photos); $i++) {
$data = $photos[$i];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$zip->addFromString("Photos/Photo" . $i . ".png", $data);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$nameZip");
header("Content-Transfer-Encoding: binary");
readfile($nameZip);
unlink($nameZip);
But does not generate the zip file correctly.
[edit]The zip file is generated but this has nothing inside. The problem is when you write in the zip file. The photo is misspelled

Related

Is there an easy way to update CSV with an API data?

I have a code that can get the Amazon product price if you gave it's "ASIN" (It's Amazon product identification number)... below you can find the code (I don't think there is a need to read the code anyway).
<?php
class AmazonAPI {
var $amazon_aff_id;
var $amazon_access_key;
var $amazon_secret_key;
var $url_params;
var $itemID;
var $xml;
var $operation;
var $signature;
var $response_groups = "Small,Images,OfferSummary";
var $error_message;
var $error=0;
public function __construct($affid, $access, $secret)
{
$this->amazon_aff_id = $affid;
$this->amazon_access_key = $access;
$this->amazon_secret_key = $secret;
}
public function build_url()
{
$url = "http://webservices.amazon.com/onca/xml?";
$this->response_groups = str_replace(",", "%2C", $this->response_groups);
$url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
$url_params .= "&AssociateTag=" . $this->amazon_aff_id;
if(!empty($this->itemID)) {
$url_params .= "&ItemId=" . $this->itemID;
}
$url_params .= "&Operation=" . $this->operation;
$url_params .= "&ResponseGroup=" . $this->response_groups;
$url_params .= "&Service=AWSECommerceService";
$url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url_params .= "&Version=2013-08-01";
$this->url_params = $url_params;
$url .= $url_params;
$url .= "&Signature=" . $this->generate_signature();
return $url;
}
public function generate_signature()
{
$this->signature = base64_encode(hash_hmac("sha256",
"GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
$this->amazon_secret_key, True));
$this->signature = str_replace("+", "%2B", $this->signature);
$this->signature = str_replace("=", "%3D", $this->signature);
return $this->signature;
}
public function item_lookup($id)
{
$this->operation = "ItemLookup";
$this->itemID = $id;
$url = $this->build_url();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$this->xml = simplexml_load_string($output);
return $this;
}
public function check_for_errors()
{
if(isset($this->xml->Error)) {
$this->error_message = $this->xml->Error->Message;
$this->error = 1;
}
if(isset($this->xml->Items->Request->Errors)) {
$this->error_message = $this->xml->Items->Request->Errors->Error->Message;
$this->error = 1;
}
return $this->error;
}
public function get_item_price($product)
{
$price = 0;
if(isset($product->LowestNewPrice)) {
$price = $product->LowestNewPrice->Amount;
} elseif(isset($product->LowestUsedPrice)) {
$price = $product->LowestUsedPrice->Amount;
} elseif(isset($product->LowestCollectiblePrice)) {
$price = $product->LowestCollectiblePrice->Amount;
} elseif(isset($product->LowestRefurbishedPrice)) {
$price = $product->LowestRefurbishedPrice->Amount;
}
return $price;
}
public function get_item_data()
{
if($this->check_for_errors()) return null;
$product = $this->xml->Items->Item;
$item = new STDclass;
$item->detailedPageURL = $product->DetailPageURL;
$item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
$item->title = $product->ItemAttributes->Title;
$item->smallImage = $product->SmallImage->URL;
$item->mediumImage = $product->MediumImage->URL;
$item->largeImage = $product->LargeImage->URL;
$item->price = $this->get_item_price($product->OfferSummary);
return $item;
}
}
?>
Then i echo the price with this code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();
echo $item->price;
Now if i have a csv sheet like this
https://ibb.co/dHS4EK
can i update the prices on column D and E given the asin found on column B and C,
so for example the value of cell D2 will get it using the following code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup(Value on cell D2)->get_item_data();
echo $item->price;
then save the csv file after updating it's prices, is there a simple easy way to do that in maybe php especially that i'm very new to coding?
Edit 1: I need the csv file to import it using WooCommerce import tool which only accept csv files
Thanks in advance
What you have to do is:
Parse the CSV file into an array. You can use PHP functions for that like str-getcsv
Find the correct line inside the array with either array_filter or a simple foreach loop.
Update the respective value with the new price
Create a CSV file from the array with fputcsv

AJAX to PHP Image Upload

I am attempting to upload multiple images from AJAX to PHP. Here's a run down of what I have so far.
HTML
<form>
<input class="images" type="file">
</form>
There could be more than one input field if the user has multiple images to upload.
Javascript
var imageObject = GetAllFiles($('.images'));
function GetAllFiles(_selector)
{
var newObject = {};
for (var i = 0; i < $(_selector).length; i++)
{
var elem = $(_selector)[i];
newObject[i] = $(elem).files;
}
return newObject;
}
$(document).on('click', '#submit', function() {
var _data = JSON.stringify(imageObject);
$.post('upload.php', { action: 'ImageUpload', data: _data }, function (e){
alert(e);
});
)};
Send data via AJAX after conversion to JSON
PHP
if(isset($_POST['action']))
{
$action = $_POST['action'];
switch($action)
{
case 'ImageUpload' : ImageUpload($_POST['data']); break;
}
}
function ImageUpload($jsonData)
{
$images = json_decode($jsonData);
foreach($images as $image)
{
$directory = "../images/maschine/";
$target_file = $directory . basename($_FILES[$image])['name'];
if (move_uploaded_file($_FILES[$image]["tmp_name"], $target_file))
{
echo('Success');
} else
{
echo('Failure');
}
}
}
Add id in the file input first, and remember the enctype='multipart/form-data' in form.
<input class="images" name="file[]" type="file" multiple>
after that in the script
<script>
$('YoursubmitbuttonclassorId').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
</script>
In the php file
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br
/>";
}
}
?>

How to convert image into base64 encoding format

I have a variable containing image which is returned from imagecopyresampled function, I want to convert this variable into base64 encoded format to return to my JavaScript file.
Error is that base64_encode and exif_imagetype funcions do not take image as input.
Here is my code:
<?php
$img_name = $_POST['name'];
$data = file_get_contents($img_name);
$crop_start_x = $_POST['crop_start_x'];
$crop_start_y = $_POST['crop_start_y'];
$crop_width = $_POST['crop_width'];
$crop_height = $_POST['crop_height'];
$dst_x = 0;
$dst_y = 0;
$src_x = $crop_start_x;
$src_y = $crop_start_y;
$dst_w = $crop_width;
$dst_h = $crop_height;
$src_w = $src_x + $dst_w;
$src_h = $src_y + $dst_h;
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
$src_image = imagecreatefromstring($data);
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
$type = exif_imagetype($dst_image);
$base64_image = 'data:image/' . $type . ';base64,' . base64_encode($dst_image);
echo $base64_image;
?>
This will work
$image = 'folder/your_image.png';
$type = pathinfo($image, PATHINFO_EXTENSION);
$imgdata = file_get_contents($image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($imgdata);
for imagecopyresampled
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
ob_start();
imagejpeg($dst_image, null);
$img = ob_get_clean();
$base64 = base64_encode($img)

Displaying multiple images with an ajax response

I am trying to display multiple images coming from a remote server on a single page, the page is a html file where putting php blocks wouldn't be doing anything to get thing I want
Using PHP version 5.6, the code for the php is
$dir = "uploads/image/dashed/";
$files = scandir($dir);
foreach ($files as $file)
{
if ( is_file($dir. $file) ){
echo $file;
}
}
the ajax response code is:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("\n");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
all I keep getting from the server is
1354876944ABF.jpg_MG_0085.jpg
and an empty image place holder (not two, just the one) for where the image
and the image address is showing two image names stuck together in one link
uploads/image/dashed/1354876944ABF.jpg_MG_0085.jpg
where the response link should be on two (for this example) different lines and images where the <img> is on the html inside the ajax call
Try This,
$dir = "uploads/image/dashed/";
$files = scandir($dir);
$i = 1;
$count = count($files);
foreach ($files as $file){
if(is_file($dir. $file)){
if($i == $count){
echo $file;
}else{echo $file.'|||';
}
}
$i++;}
and change ajax to:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("|||");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
thats using ||| as a delimiter.
EDIT: now it should work properly,
EDIT2: changed $i = 0 order, added $i++; at the end
scandir() is already giving you an array, so why not just json_encode it and return this? unset() any output that is not a valid file:
$files = scandir($dir);
$count = count($files);
for($i = 0; $i < $count; $i++) {
if ( !is_file($dir. $file) ){
unset($files[$i]);
}
}
echo json_encode($files);
then in your success block:
success: function(data){
$("#imageContent").html(data).append("<br/>");
var i,
json = JSON.parse(data);
for (i in json){
$("#imageContent").append("<img src='uploads/image/dashed/" + json[i] + "' width='300'>");
}
}

Trying to detect when download is ready

I am trying to create a zip folder on the fly. The zip will hold images that a user has selected from a library that is hosted on Amazon S3. Below is the code I have so far.
REQUEST URL FROM POST
function download_multi() {
//$user_id, $files, $project_id, $project_name
$this->load->library('aws');
$user = User::get_user();
$requestedHashes = $this->input->post("files");
$files = array();
foreach($requestedHashes as $hash) {
$files[] = hex_to_string($hash);
}
$project_id = $this->input->post("projectid");
$project = new Project($project_id);
$project_name = $project->project_name;
$this->aws->create_zip($user->id, $files, $project_id, $project_name, (int)$this->input->post("downloadToken"));
}
Create Zip
public function create_zip($user_id, $files, $project_id, $project_name, $cookie) {
//create a random folder name to avoid collision.
$this->folder = md5(time() . rand());
if(!mkdir('./files' . '/' . $this->folder, 0777, TRUE)) {
exit("Folder not created\n");
}
//create zipfile
$this->filename = $this->local_file_path . $this->folder . '/files.zip';
$zip = new ZipArchive();
if ($zip->open($this->filename, ZIPARCHIVE::CREATE) !== TRUE) {
exit("cannot open <$this->filename>\n");
}
//create options for downloading each file to the server
//temporarily to add to archive
$opt = array('preauth' => '+1 minutes');
//download each file to the server.
foreach ($files as $file) {
//generate a link.
$response = $this->s3->get_object($this->bucket, $this->_make_path($user_id, $project_id) . $file, $opt);
//get filename.
$file_name = explode('?', basename($response));
//add filename to array
$local_files[] = $file_name[0];
//copy the file from aws to local server.
if(copy($response, $this->local_file_path . $this->folder . '/' . $file_name[0])) {
$zip->addFile($this->local_file_path . $this->folder . '/' . $file_name[0], $file_name[0]);
}
}
//close zip
$zip->close();
//die(var_dump(file_exists($this->filename)));
//kill each temp file
/*foreach ($local_files as $file) {
unlink($this->local_file_path . $this->folder . '/' . $file);
}*/
//load download helper.
$this->ci->load->helper('download');
//download
stream_download("APP_{$project_name}_" . time() . ".zip", $this->filename, $cookie);
}
The Download Helper
function stream_download($filename = '', $data = '', $cookie = NULL)
{
//die($cookie);
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize($data));
}
flush();
}
JAVASCRIPT
downloadSelectedFiles: function(e) {
//window.XmlHttpRequest = new XmlHttpRequest();
console.log("Block UI");
var that = this;
var url = config.base + "projects/download_multi";
var projectId = $("li.selected").find('li.js-select-file').data('projectid');
var images = {};
images.hashes = [];
var token = new Date().getTime();
$("li.selected").each(function(i){
images.hashes.push($(this).find('li.js-select-file').data('filename'));
});
//window.location.href = url;
$.post(url, { files: images.hashes, projectid: projectId, downloadToken: token }, function(data){
var fileDownloadCheckTimer = window.setInterval(function() {
console.log("checking...");
var cookieValue = $.cookie('fileDownloadToken');
console.log(parseInt(cookieValue), parseInt(token));
if( parseInt(cookieValue) == parseInt(token) ) {
that.finishDownload()
} else {
console.log("Don't Match");
}
}, 1000);
/*var iframe = document.createElement("iframe");
iframe.src = config.base + data;
iframe.style.display = "none";
document.body.appendChild(iframe);
return false;*/
});
},
finishDownload: function() {
window.clearInterval(fileDownloadCheckTimer);
$.removeCookie('fileDownloadToken');
console.log("Unblock UI");
}
One thing I have noticed is that when I am checking to see of the cookie value and the token match one is a string and the other an int. Other that I also not that I only get the headers in my reposonse, I never actually get the download window.

Categories