I can't get the image from my directory - php

I try to get the image that is stored in a folder of my localhost, I do not understand what is the problem, the attribute in JSON IMAGEN get empty,
I need to convert it here..
<?php
/**
* Obtiene todas las metas de la base de datos
*/
const ESTADO = "estado";
const DATOS = "negocios";
const MENSAJE = "mensaje";
const CODIGO_EXITO = 1;
const CODIGO_FALLO = 2;
require '../data/Gastos.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
// Manejar petición GET
$negocios = Gastos::getAllNegocios();
//Definir el tipo de la respuesta
header('Content-Type: application/json');
$imagesPath = '/localhost:8888/htdocs/';
if ($negocios) {
$datos[ESTADO] = CODIGO_EXITO;
foreach($negocios as $meta) {
// Push an entry in the new array, replacing raw image with base64-encoded
$imgFileContents = file_get_contents($imagesPath.'/'.$meta['IMAGEN']);
$datos["negocios"][] = array(
'IDNEGOCIO' => $meta['IDNEGOCIO'],
'NOMBREIMAGEN' => $meta['NOMBREIMAGEN'],
'IMAGEN' => base64_encode($imgFileContents),
'NOMBRENEGOCIO' => $meta['NOMBRENEGOCIO'],
'DESCRIPCION' => $meta['DESCRIPCION'],
);
}
print json_encode($datos,JSON_UNESCAPED_UNICODE);
} else {
print json_encode(array(
ESTADO => CODIGO_FALLO,
MENSAJE => "Ha ocurrido un error"
));
}
}
?>
Get empty in JSON
{"estado":1,"negocios":[{"IDNEGOCIO":"1","NOMBREIMAGEN":"img_1","IMAGEN":"","NOMBRENEGOCIO":"YARYAS","DESCRIPCION":"Descripcion1"},{"IDNEGOCIO":"2","NOMBREIMAGEN":"img_2","IMAGEN":"","NOMBRENEGOCIO":"Skizza","DESCRIPCION":"Descripcion2"}]}
It is the directoy

I think it might be because you're $imagesPath URL is pointing to a directory incorrectly. In most localhost setups "htdocs" is already the default directory when travelling to the localhost server, so assuming its a relative URL it should be something like "http://localhost:8888/fotos/" not "http://localhost:8888/htdocs/fotos/".
Try:
$imagesPath = 'http://localhost:8888/';

Related

Create a csv file with a lot of txt files

i'm trying to read a lot of txt files and save the first line as a title, and the rest of text as a content, then export to a CSV file.
i create a id for CSV that increase by iteration, but when i have an error that i cant see in the iteration because when it save the content in the array add the last content to this value.
I need to create a CSV with 3 "columns" named, id, titulo and contenido and by each file, save in a array the information. One txt file, one iteration of array.
Sorry for my english.
this is my code:
<?php
/* Cogemos todos los archivos txt de la carpeta archivos del servidor */
$files = glob("archivos/*.txt");
/* Creamos el array para guardar los datos y le metemos la primera línea que es el nombre de los campos a importar */
$datosparacsv=array(array("ID","titulo","contenido"));
/* Creamos el id que tendrá cada campo del array para después poder importar */
$id = 0;
/* Recorremos cada archivo para coger los datos */
foreach($files as $file) {
/* Sacamos el título de la primera línea del archivo txt */
$titulo = trim(fgets(fopen($file, 'r')));
/* Sacamos el resto del contenido pero quitamos la primera linea con el condicional if*/
$archivo = file($file);
foreach ($archivo as $num=>$line){
if ($num==0) {
continue;
}
else{
$contenido .= $line."\n";
}
}
/* Añadimos el contenido extraido al array para luego pasarlo a CSV */
array_push($datosparacsv, array($id,$titulo,$contenido));
/* Sumamos uno al id para que sea único */
$id++;
}
$delimitador = ','; //parameter for fputcsv
$enclosure = '"'; //parameter for fputcsv
//convert array to csv
$archivocsv = fopen('entradas.csv', 'w+');
foreach ($datosparacsv as $data_line) {
fputcsv($archivocsv, $data_line, $delimitador, $enclosure);
}
$data_read="";
rewind($archivocsv);
//read CSV
while (!feof($archivocsv)) {
$data_read .= fread($archivocsv, 8192); // will return a string of all data separeted by commas.
}
fclose($archivocsv);
echo $data_read;
Example of files to read.
File 1.txt
Titulo 1
texto 1
File 2.txt
Titulo 2
texto 2
CSV
id, titulo, contenido, 0, Titulo 1, texto 1, 1, Titulo 2, texto 2
Thank you very much mates.
$contenido on line 19 is undefined and it's trying to concatenate a non-existent variable with .=. The $contenido variable also isn't required because each archive line is defined in $datosparacsv.
It's also unnecessary to define $delimitador and $enclosure because the defined values are also the default values.
Here's the correct PHP code with the expected CSV output with comments explaining each modified line.
It also preserves new lines and spaces in content as required.
<?php
/* Cogemos todos los archivos txt de la carpeta archivos del servidor */
$files = glob("archivos/*.txt");
/* Creamos el array para guardar los datos y le metemos la primera línea que es el nombre de los campos a importar */
$datosparacsv = array(
array(
"ID",
"titulo",
"contenido"
)
);
/* Creamos el id que tendrá cada campo del array para después poder importar */
$id = 0;
foreach($files as $file) {
/* Sacamos el resto del contenido pero quitamos la primera linea con el condicional if*/
$archivos = file($file);
// Remove and retrieve CSV heading values from each file with array_shift instead of a conditional in each $archivo iteration
$titulo = trim(array_shift($archivos));
// Append to the ID and title to the CSV data array with $datosparacsv[] instead of array_push() while incrementing the ID
$datosparacsv[$id + 1] = array(
$id++,
$titulo,
''
);
foreach ($archivos as $archivo) {
// Append each line from $archivos with preserved spaces and new lines
$datosparacsv[$id][2] .= $archivo;
}
// Trim leading and trailing whitespace
$datosparacsv[$id][2] = trim($datosparacsv[$id][2]);
}
$archivocsv = fopen('entradas.csv', 'w+');
foreach ($datosparacsv as $data_line) {
// Add the data to the CSV with the default delimiter and enclosure
fputcsv($archivocsv, $data_line);
}
?>
archivos/1.txt
Titulo 1
texto 1
archivos/2.txt
Titulo 2
texto 2
texto3
texto4
This saves entradas.csv with this data.
ID,titulo,contenido
0,"Titulo 1","texto 1"
1,"Titulo 2","texto 2
texto3
texto4"
i use this forme because i can format my anser better.
i need that the whole content of the file less the first line was in the column $contenido.
Now, with your code, works fine but if the same file has more than one line after content, it uses each line as a new line of the result.
For example i use now this files
Archivo 1.txt
Titulo 1
texto 1,texto 1
Some more text in file 1
Archivo 2.txt
Titulo 2
texto 2, texto 2, texto 2, texto 2, texto 2, texto 2
Some text 2 of the same archive
and this generates this entradas.csv
ID,titulo,contenido
0,"Titulo 1","texto 1,texto 1"
1,"Titulo 1",
2,"Titulo 1","Some more text in file 1"
3,"Titulo 2","texto 2, texto 2, texto 2, texto 2, texto 2, texto 2"
4,"Titulo 2",
5,"Titulo 2","Some text 2 of the same archive"
But i need that:
ID,titulo,contenido
0,"Titulo 1","texto 1,texto 1
Some more text in file 1"
1,"Titulo 2","texto 2, texto 2, texto 2, texto 2, texto 2, texto 2
Some text 2 of the same archive"
It's important that the contents saves all spaces and \n that they have in the txt file because this txt files are posts of a blog.
An example of one file.txt
¿Como puedo comer galletas?<-- Title
Las galletas se comen con la boca, poco a poco masticando.
<h2>¿Cuántos sabores de galletas hay?</h2>
Pues hay de todos los que puedas imaginar.
and all of this text after title have to stay in the same line saving \n and all.
One file only one line in the CSV.
thank you very much and im sorry for my english.

Not get info of coingecko API

I´m forking this repo https://github.com/FundacionPesetacoin/Pesetacoin_WooCommerce-Plugin and working fine. But when change the API for catch the price in other Site, not update
I try some differents links of API and make same.
Original code get info of his private API, and I want use other public API.
With original code, API show this info:
{"status" : "success" , "message" : "null", "ptc_btc" : "0.00000083", "btc_usd" : "5070.29", "btc_eur" : "4505.46", "supply" : "138188628.56442260", "ptc_eur" : "0.00373953", "ptc_usd" : "0.00420834" , "date" : "2019-04-13 10:20:07"}
and get "ptc_eur" of API for shows in shoppping cart.
Now I want use the new API of other site https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur than shows this info:
{"reecore":{"eur":0.0046564}}
I want use only the "eur" data , same the original code use the "ptc_eur" but dont work.
Sorry for my english.
ORIGINAL CODE:
//precio en PesetaCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "http://nodos.pesetacoin.info/api/api.php";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_ptc= $pesetas['ptc_eur'];
$ptc= $euros/$valor_ptc;
$ptc= round($ptc, 2);
//precio en PesetaCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "ptc") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$ptc."</b> de Pesetacoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
NEW CODE:
//precio en ReecoreCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_reex= $pesetas['eur'];
$reex= $euros/$valor_reex;
$reex= round($reex, 2);
//precio en ReecoreCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "reex") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$reex."</b> de Reecorecoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
It's because the now Coingecko API return a nested JSON which is simply a JSON file with a fairly big portion of its values being other JSON objects.
Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
Using Phrase, keys will be stored by separating levels with a dot.
The new API returns a nested JSON object, where you need two steps to access the desired value:
$valor_reex= $pesetas['reecore']['eur'];
You might want to use ready library for this. Like this one https://github.com/npabisz/coingecko-api.
Install via composer:
composer require npabisz/coingecko-api
And then get your reecore price by:
$client = new \CoinGecko\Client();
$data = $client->Simple->Price->get([
'ids' => 'reecore',
'vs_currencies' => 'eur',
]);
$reecorePrice = $data['reecore']['eur'] ?? null;

LiipImagineBundle Error encodage HTML

I use LiipImagineBundle for re-size my image after upload. I have a error when I tried to upload some Jpeg about HTML encodage.
With jpeg form my camera that's work, but not form my phone camera.
What my browser show only js error and return blank page ?
I didn't understand what is that error.
Full message in french :
L'encodage de caractères du document HTML n'a pas été déclaré. Le document sera affiché avec des caractères incorrects pour certaines configurations de navigateur si le document contient des caractères en dehors de la plage US-ASCII. L'encodage de caractères de la page doit être
déclaré dans le document ou dans le protocole de transfert.
controller Symfony2
private function compressFile($file) {
$path = $file->getWebPath();
$absPath = $file->getAbsolutePath();
$tmpPath = $absPath."tmp";
$filter = "image";
$container = $this->container;
$dataManager = $container->get('liip_imagine.data.manager');
$filterManager = $container->get('liip_imagine.filter.manager');
try {
$image = $dataManager->find($filter, $path);
$response = $filterManager->applyFilter($image, $filter);
//$response = $filterManager->get($this->getRequest(), $filter, $image, $path);
$fileCompressed = $response->getContent();
}
catch (\Exception $e) {
return "error";
}
$f = fopen($tmpPath, 'w');
fwrite($f, $fileCompressed);
fclose($f);
unlink($absPath);
rename($tmpPath, $absPath);
return null;
}
I have found help to create my compress Function here.
I tried to catch some Exception but nothing work.
Someone have a solution ?
Sorry for my English, I am learning it...
It may be a little bit anoying but have you set default_charset to "UTF-8" in your php.ini ?
If you use Apache: Is (AddDefaultCharset UTF-8) present on your httpd.conf ?
In your view: is is présent on between your HTML Header.
Check the encoding of your editor to UTF-8 without BOM if it's not configured yet and save all file you have generated with that correct charset.
If not this may be the origin of that bad behavior.
Have a nice day.
Best Regards

Symfony2 How to call a require_once function that is on other server (java bridge)

Im trying to call some php code that I found in order to execute some java code to run a php jru jasper report.
Here is the code I want to run with Symfony
<?php
function DescargarArchivo($fichero)
{
$basefichero = basename($fichero);
header( "Content-Type: application/octet-stream");
header( "Content-Length: ".filesize($fichero));
header( "Content-Disposition:attachment;filename=" .$basefichero."");
readfile($fichero);
}
//Obtener Fecha de Hoy
$fecha = time ();
$fecha_partir1=date ( "h" , $fecha ) ;
$fecha_partir2=date ( "i" , $fecha ) ;
$fecha_partir4=date ( "s" , $fecha ) ;
$fecha_partir3=$fecha_partir1-1;
$reporte="Reporte_";
$filename = $reporte. date("Y-m-d")."_". $fecha_partir3.'_'.$fecha_partir2.'_'.$fecha_partir4.'.pdf';
//Llamando las librerias
require_once('http://localhost:8080/JavaBridge/java/Java.inc');
require('./php-jru/php-jru.php');
//Llamando la funcion JRU de la libreria php-jru
//$jru=new JRU();
$jru=new PJRU();
//Ruta del reporte compilado Jasper generado por IReports
//$Reporte='C://xampp//htdocs//reportes_javabridge//reportes//report1.jasper';
$Reporte='C://Dropbox//Apache Xampp//evaluacion_daci//web//reportes_javabridge//reportes//control_pago_estado_de_cuenta.jasper';
//Ruta a donde deseo Guardar Mi archivo de salida Pdf
//$SalidaReporte='C://xampp//htdocs//reportes_javabridge//'.$filename;
$SalidaReporte='C://Dropbox//Apache Xampp//evaluacion_daci//web//reportes_javabridge//'.$filename;
//Parametro en caso de que el reporte no este parametrizado
$Parametro=new java('java.util.HashMap');
$Parametro->put("id", 39);
//Funcion de Conexion a mi Base de datos tipo MySql
//$Conexion= new JdbcConnection("com.mysql.jdbc.Driver","jdbc:mysql://localhost/probando_reportesphp","root","clave");
$Conexion= new JdbcConnection("com.mysql.jdbc.Driver","jdbc:mysql://localhost/evaluaciones?zeroDateTimeBehavior=convertToNull","root","admin");
//Generamos la Exportacion del reporte
$jru->runReportToPdfFile($Reporte,$SalidaReporte,$Parametro,$Conexion->getConnection());
if(file_exists($SalidaReporte))
{
DescargarArchivo($filename);
if(file_exists($SalidaReporte))
{
if(unlink($filename))
{
}
}
}
?>
My problem here is that require_once is installed in other server and dont know how to call this from the controller

CodeIgniter and RESTful: how to remove backslashes from returned json?

i'm struggling trying to remove the scaped characters from the json response in my CodeIgniter with PhilSturgeon REST Server.
Everything is working OK, but the problem comes with the response, when I access the URL to get the data in json format I get it, but with escaped characters.
Example:
http://localhost/revista_servidor/index.php/api/notas/nota/id/1
Gives me the next response:
[{"id":"1","autor":"Prueba autor","titulo":"Comprobaci\u00f3n de t\u00ed\u00edtulo.","subtitulo":"Comprobaci\u00f3n de subt\u00edtulo.","foto1":"http://link.a.foto/foto1","texto1":"Comprobaci\u00f3n de texto 1.\r\n","pauta1":"1","texto2":"Comprobaci\u00f3n de texto 2.\r\n","foto2":"http://link.a.foto/foto2","pauta2":"1","texto3":"Comprobaci\u00f3n de texto 3.","foto3":"http://link.a.foto/foto3","pauta3":"1","texto4":"Comprobaci\u00f3n de texto 4.","texto5":"Comprobaci\u00f3n de texto 5.","texto6":"Comprobaci\u00f3n de texto 6.","datosweb":"http://link.a.pagina.de.datos/","adelanto":"Comprobaci\u00f3n del texto de adelante","nrorevista":"69"}]
It escapes URLs adding a backslash \ and changing specials characters (ó in this example) with: \u00f3.
I've tried adding stripslashes()but didn't work.
I checked the response in developers tools and it comes as expected: Content-Type: application/json.
How can I fix this encoding problem? I've also checked the configuration files and there seems to be nothing to change for this issue.
I hope someone can point me in the right direction, below is my code:
Controller: /application/controllers/api/notas.php
function nota_get() {
// ID verification.
if ( !$this->get('id') ) {
// NO ID.
$this->response(NULL, 400);
}
$nota = $this->Notas_model->get( $this->get('id') );
if ($nota) {
stripcslashes($this->response($nota, 200));
}
else {
$this->response(NULL, 404);
}
}
Model: /application/models/notas_model.php
function get($id = 0) {
$this->load->database();
if ( $id ) {
$query = $this->db->get_where( 'notas', array('id' => $id) );
}
else {
$query = $this->db->get('notas');
}
return $query->result();
}
I don't know if this matters, but this data will be accessed via javascript in the client side.
Thanks in advance!
Its just the way JSON works, try json_decode function.
e.g:
$json = json_decode($json_string);
$json->autor;
1) You need to be using json_decode() and then urldecode(), instead of stripslashes()
2) Both urldecode() and stripslashes() take a string as an argument, while you are trying to feed into it an object -- which gets "autoreduced" into something that depends on the PHP version... Whatever it is, it's probably not what you are expecting.
In your code:
if ($nota) {
stripcslashes($this->response($nota, 200));
}
you'll need a) save the result of decoding to the same or another variable, b) to loop through your object ( $nota ) and unescape the value in each key-value pair.
Try
...
$cleanObject = array();
if ($nota) {
$decodedObject = json_decode($this->response($nota, 200));
foreach ( $decodedObject as $key => $value ) {
$cleanObject[$key] = urldecode( $value );
}
}
echo "<pre>";
print_r($cleanedObject);
echo "</pre>";
// output
/*
Array
(
[id] => 1
[autor] => Prueba autor
[titulo] => Comprobación de tíítulo.
[subtitulo] => Comprobación de subtítulo.
[foto1] => http://link.a.foto/foto1
[texto1] => Comprobación de texto 1.
[pauta1] => 1
[texto2] => Comprobación de texto 2.
[foto2] => http://link.a.foto/foto2
[pauta2] => 1
[texto3] => Comprobación de texto 3.
[foto3] => http://link.a.foto/foto3
[pauta3] => 1
[texto4] => Comprobación de texto 4.
[texto5] => Comprobación de texto 5.
[texto6] => Comprobación de texto 6.
[datosweb] => http://link.a.pagina.de.datos/
[adelanto] => Comprobación del texto de adelante
[nrorevista] => 69
)
*/
...
Hopefully, this is what you are looking to achieve.
Depending on your further needs, you may have to re-encode the result. Based on javascript you mention, you may then need to convert the result back to JSON:
$unescapedAndJSONencodedObject = json_encode( $cleanObject );

Categories