I would like to copy a file in Symfony2, but I'm getting an error:
Symfony\Component\Filesystem\Exception\FileNotFoundException: Failed to copy "../../../public_html/uploads/images/2011/03/MG_3839-ba�o.jpg" because file does not exist
$fs = new Filesystem();
$fs->copy('../../../public_html/uploads/images/'.$image, '../../../public_html/uploads/tmp/'.$image, true);
var_dump($image) gives 2011/03/MG_3839-baño.jpg and mb_detect_encoding($image) gives ASCII. Why is Symfony looking for a filename containing the � sign? I can't figure out where that sign is coming from, since var_dump() gives the correct filename.
Try this command :
$fs = new Filesystem();
$image = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $image);
$fs->copy('../../../public_html/uploads/images/'.$image, '../../../public_html/uploads/tmp/'.$image, true);
$file_name = strtr($file_name, "áéíóúâêôàãõçÁÉÍÓÚÂÊÔÀÃÕǺª", "aeiouaeoaaocAEIOUAEOAAOCoa");
Related
i'm new in php. and using php on xampp and also in real server. i have a php file that receives on image as String and saves it as image that im gonna use this file with a library in android that uploads image to php file.
the string is sent to php file but no file is saved as image. my problem is that i cant figure out how to get result of executing this php file. i cant get response with my upload library , if i could get echo from this file for test purpose, so i could test it or if i could get error log of execution of file in xampp. but i have no clue how to test php file that is not containing view so i cant echo any thing.
this is my php file code:
<?php
if($_POST){
$data = $_POST['imgBase64'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = ''.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = 'localhost/serverp/server.parhamcode.ir/'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
}
?>
try this:
<?php
file_put_contents('./debug.log', $_POST, FILE_APPEND);
then you'll get a debug.log file under the same folder as your PHP script.
you can change $_POST to any variable you want to check.
If you want to echo something in this log file :
file_put_contents('./debug.log', "any string is ok.", FILE_APPEND);
im trying to get the contents of file and storing it in a file on my system, that function is working fine, when i specify the url the function is working fine, but when supply a variable which has url stored in it, it stores an empty file, meaning it failed getting the contents of the file, i have tried dozens of solutions but none is working, there is also a solution on php.net but its also not working, here is the code:
$filePath = str_replace("Vary:", "", $items[13]);
//$encoding = mb_detect_encoding($filePath);
//$filePath = mb_convert_encoding($filePath, "ASCII", $encoding);
//$filePath = str_replace("?", "", $filePath);
//$filePath = addslashes($filePath);
//file_put_contents('path/'.$file_name, fopen("".$target_url."","r"));
file_put_contents('path/'.$file_name, fopen($filePath,"rb"));
Figured it out just trimmed the variable and it worked
$filePath = str_replace("Vary:", "", $items[13]);
$filePath = trim($filePath);
I am having an issue with imagick php library.
I am doing a recursive search in my file system and look for any pdf files.
$it = new RecursiveDirectoryIterator("/test/project");
$display = Array ('pdf');
foreach(new RecursiveIteratorIterator($it) as $file){
if (in_array(strtolower(array_pop(explode('.', $file))), $display))
{
if(file_exists($file)){
echo $file; //this would echo /test/project/test1.pdf
$im = new Imagick($file);
$im->setImageFormat("jpg");
file_put_contents('test.txt', $im);
}
}
}
However, I am getting an error saying
Fatal error: Uncaught exception 'ImagickException' with message 'Can not process empty Imagick object' in /test.php:57
Stack trace:
#0 /test.php(57): Imagick->setimageformat('jpg')
#1 {main}
thrown in /test.php on line 57
line 57 is $im->setImageFormat("jpg");
However, if I replace my $im = new Imagick($file) with $im = new Imagick('/test/project/test1.pdf'), the error is gone.
I don't know why this is happening. Can someone give me a hint for this issue? Thanks so much
According to this, the .jpg files' format is JPEG.
Note 1:
Your $file variable is an object SplFileInfo, but you are using it always like a string. Use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME flag in RecursiveDirectoryIterator's constructor, to be a real string.
Note 2:
You can filter the iterator entries with RegexIterator, f.ex.: new RegexIterator($recursiveIteratorIterator, '/\.pdf$/') (after Note 1). Or, you can use GlobIterator too for searching only pdf files.
As #pozs pointed out
Note 1: Your $file variable is an object SplFileInfo, but you are
using it always like a string.
Here's a code snippet which gets you the filename as string and has an optimized method to get the file extension:
<?php
$display = array ('pdf');
$directoryIterator = new RecursiveDirectoryIterator('./test/project');
// The key of the iterator is a string with the filename
foreach (new RecursiveIteratorIterator($directoryIterator) as $fileName => $file) {
// Optimized method to get the file extension
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if (in_array(strtolower($fileExtension), $display)) {
if(file_exists($fileName)){
echo "{$fileName}\n";
// Just do what you want with Imagick here
}
}
Maybe try this approach from : PDF to JPG conversion using PHP
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick();
$img->readImageFile($fp_pdf);
It also seems from reading other posts that GhostScript is faster?
I have a data URI I am getting from javascript and trying to save via php. I use the following code which gives a apparently corrupt image file:
$data = $_POST['logoImage'];
$uri = substr($data,strpos($data,",")+1);
file_put_contents($_POST['logoFilename'], base64_decode($uri));
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs 9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAxklEQVQYlYWQMW7CUBBE33yITYUUmwbOkBtEcgUlTa7COXIVV5RUkXKC5AxU EdyZVD4kyKxkwIrr9vd0c7Oih aopinLNsF6Qkg2XW4XJ7LGFsAAcTV6lF5/jLdbALA9XDAXYfthFQVx OrmqKYK88/7rbbMFksALieTnzu9wDYTj6f70PKsp2kwAiSvjXNcvkWpAfNZkzWa/5a9yT7fdoX7rrB7hYh2fXo9HdjPYQZu3MIU8bYIlW20y0RUlXG2Kpv/vfwLxhTaSQwWqwhAAAAAElFTkSuQmCC
Below the code is the actual image as a Data-URI. 'logoImage' is the string above, and $uri is the string minus 'image/jpeg;base64,'.
A quick look at the PHP manual yields the following:
If you want to save data that is derived from a Javascript
canvas.toDataURL() function, you have to convert blanks into plusses.
If you do not do that, the decoded data is corrupted:
$encodedData = str_replace(' ','+',$encodedData);
$decodedData = base64_decode($encodedData);
The data URI you have in your example is not a valid PNG image. This will never work and is unrelated to the code, it's related to the data.
Does not apply but might be of interest:
file_put_contents($_POST['logoFilename'], file_get_contents($data));
The idea behind: PHP itself can read the contents of data URIs (data://) so you don't need to decode it on your own.
Note that the official data URI scheme (ref: The "data" URL scheme RFC 2397) does not include a double slash ("//") after the colon (":"). PHP supports with or without the two slashes.
# RFC 2397 conform
$binary = file_get_contents($uri);
# with two slashes
$uriPhp = 'data://' . substr($uri, 5);
$binary = file_get_contents($uriPhp);
The all code that works :
$imgData = str_replace(' ','+',$_POST['image']);
$imgData = substr($imgData,strpos($imgData,",")+1);
$imgData = base64_decode($imgData);
// Path where the image is going to be saved
$filePath = $_SERVER['DOCUMENT_ROOT']. '/ima/temp2.png';
// Write $imgData into the image file
$file = fopen($filePath, 'w');
fwrite($file, $imgData);
fclose($file);
I have another way to do this with PHP.
$img = str_replace(' ','+',$img);
$i = explode(',', $img);
$imgData = array_pop($i);
$newName = 'digital_file/'. rand(10, 16) . '.' . str_replace('/', '.', mime_content_type($img) );
// data:image/png;base64
$imgData = base64_decode($imgData);
Now you can use file_put_contents($newName) to create the image file.
Produces a file with a random numerical name (e.g. "123123.image.png"). And of course it has correct mime type.
i have the followed code
$zip = new ZipArchive;
$res = $zip->open('tmp/articles.zip');
if ($res === TRUE) {
$zip->extractTo('tmp/');
$zip->close();
}
It works fine for archives with english filenames, but if i made archieve with russian characters, i have unreadable filenames. What should I do?
UPD: It doesn't work correctly when i use "unzip" from bash too.
Look at this code:
$z = new ZipArchive();
$res = $z->open('C:\Temp\Temp.zip');
if ($res)
{
$z->extractTo('C:\Temp\Temp');
$z->close();
}
$files = scandir('C:\Temp\Temp');
foreach ($files as $filename)
{
print iconv('cp866', 'utf-8', $filename).PHP_EOL;
}
This code prints normal filenames.
So, WinRar uses old ms-dos charset 'cp866' for Cyrillic.
Hope you can change this code to create rename algorithm :)
This method not always works. I've found myself installing an external library like 7zip to do this job and it soves the problem. It's hard to know the encoding charset used for a file in windows.
In my case I had to do this for avoiding errors in filenames after extraction.
Here are my variables:
// Extract file.
$tmp_dir = uniqid();
$zip_uri = "test.zip";
$destination_dir = "C:\\Users\\user\\AppData\\Local\\Temp\\$tmp_dir";
This is the ZipArchive method:
$zip = new ZipArchive();
$zip->open($zip_uri);
if (!$zip->extractTo($destination_dir)) {
die("Error extracting files.");
}
$zip->close();
This method not always worked, but the following does work beautifully (using 7Zip):
exec("C:\\7zip\\7za.exe e $zip_uri -o$destination_dir");
Hope it helps somebody to not spend hours trying with to figure out the encoding charset of a particular zipped file.