I am using following code and getting issue if there is an space in image name. And the issue is basically file is not loading at popwerpoint slide.
like:
$shape->setPath("C:/image/abc1.jpg"); // Working fine
$shape->setPath("C:/image/abc 1.jpg"); // Not working due to space in filename
I'm using the PHPPowerPoint class for generating powerpoint slides.
How do I get this to work?
EDIT
For the benefit of roine
public function setPath($pValue = '', $pVerifyFile = true) {
if ($pVerifyFile) {
if (file_exists($pValue)) {
$this->_path = $pValue;
if ($this->_width == 0 && $this->_height == 0) {
// Get width/height
list($this->_width, $this->_height) = getimagesize($pValue);
}
} else {
throw new Exception("File $pValue not found!");
}
} else {
$this->_path = $pValue;
}
return $this;
}
Try:
$shape->setPath("C:/image/abc%201.jpg");
If that works, you can use a simple string replace.
Try
$file_path = "C:/image/abc 1.jpg";
$clean_file_path = str_replace(" ", "%20", "$file_path");
$shape->setPath($clean_file_path);
Related
Is there a function built into PHP that acts like file_exists, but given file contents instead of the file name?
I need this because I have a site where people can upload an image. The image is stored in a file with a name determined by my program (image_0.png image_1.png image_2.png image_3.png image_4.png ...). I do not want my site to have multiple images with the same contents. This could happen if multiple people found a picture on the internet and all of them uploaded it to my site. I would like to check if there is already a file with the contents of the uploaded file to save on storage.
This is how you can compare exactly two files with PHP:
function compareFiles($file_a, $file_b)
{
if (filesize($file_a) == filesize($file_b))
{
$fp_a = fopen($file_a, 'rb');
$fp_b = fopen($file_b, 'rb');
while (($b = fread($fp_a, 4096)) !== false)
{
$b_b = fread($fp_b, 4096);
if ($b !== $b_b)
{
fclose($fp_a);
fclose($fp_b);
return false;
}
}
fclose($fp_a);
fclose($fp_b);
return true;
}
return false;
}
If you keep the sha1 sum of each file you accept you can simply:
if ($known_sha1 == sha1_file($new_file))
You can use a while loop to look look through the contents of all of your files. This is shown in the example below :
function content_exists($file){
$image = file_get_contents($file);
$counter = 0;
while(file_exists('image_' . $counter . '.png')){
$check = file_get_contents('image_' . $counter . '.png');
if($image === $check){
return true;
}
else{
$counter ++;
}
}
return false;
}
The above function looks through all of your files and checks to see if the given image matches an image that is already stored. If the image already exists, true is returned and if the image does not exist false is returned. An example of how you can use this function shown is below :
if(content_exists($_FILES['file']['tmp_name'])){
// upload
}
else{
// do not upload
}
You could store hashed files in a .txt file separated by a \n so that you could use the function below :
function content_exists($file){
$file = hash('sha256', file_get_contents($file));
$files = explode("\n", rtrim(file_get_contents('files.txt')));
if(in_array($file, $files)){
return true;
}
else{
return false;
}
}
You could then use it to determine whether or not you should save the file as shown below :
if(content_exists($_FILES['file']['tmp_name'])){
// upload
}
else{
// do not upload
}
Just make sure that when a file IS stored, you use the following line of code :
file_put_contents('files.txt', hash('sha256', file_get_contents($file)) . "\n");
I have made a form on the front end to upload some images. My idea is to automatically rename all files uploaded into unique id's.
I have looked at the SilverStripe API and I do not see anything about that. UploadField API
Is this possible?
Here is my solution bellow, in Silverstripe 3.X we must extend UploadField with another class. Then copy the ''saveTemporaryFile'' function into it.
Just before ''try'', just have to add :
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
Results :
class RandomNameUploadField extends UploadField {
protected function saveTemporaryFile($tmpFile, &$error = null) {
// Determine container object
$error = null;
$fileObject = null;
if (empty($tmpFile)) {
$error = _t('UploadField.FIELDNOTSET', 'File information not found');
return null;
}
if($tmpFile['error']) {
$error = $tmpFile['error'];
return null;
}
// Search for relations that can hold the uploaded files, but don't fallback
// to default if there is no automatic relation
if ($relationClass = $this->getRelationAutosetClass(null)) {
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
}
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
// Get the uploaded file into a new file object.
try {
$this->upload->loadIntoFile($tmpFile, $fileObject, $this->getFolderName());
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$error = $e->getMessage();
return null;
}
// Check if upload field has an error
if ($this->upload->isError()) {
$error = implode(' ' . PHP_EOL, $this->upload->getErrors());
return null;
}
// return file
return $this->upload->getFile();
}
}
Thanks #3dgoo to give me a part of the solution!
I don't now about a API but with some code I was able to do that.
You have two possibilities.
First using database.
Second using only code:
$directory = '/teste/www/fotos/';
$files = glob($directory . '*.jpg');
if ( $files !== false )
{
$filecount = count( $files );
$newid = $filecount+1;
$new_name = "foto_".$newid;
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
else
{
$new_name = "foto_1";
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
My example is for jpeg but you can look for hall types.
I have pdf files which are report cards of students.The report card names format is <student full name(which can have spaces)><space><studentID>.I need to download files.For this I have used the following code.
if(file_exists($folder_path.'/') && is_dir(folder_path)) {
$report_files = glob(folder_path.'/*'.'_*\.pdf' );
if(count($report_files)>0)
{
$result_data = '';
$result_data = rename_filenamespaces($report_files);
var_dump($result_data);//this shows the edited filename
foreach ($result_data as $file) {
if (strpos($file,$_GET['StudentID']) !== false) {
//code for showing the pdf docs to download
}
}
}
}
//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
$new_location = $location;
foreach ($location as $file) {
//check file has spaces and filename has studentID
if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
{
$new_filename = str_replace(" ","-",$file);
rename($file,$new_filename);
$new_location = $new_filename;
}
}
return $new_location;
}
The variable $result_data gives me the filename without spaces,but the for each loop is showing Warning:Invalid argument supplied for foreach(). But the filename is changed in the server directory immediately after running the function. This warning shows only for first time. I am unable to solve this.
$new_location = $new_filename;
$new_location is a array
$new_filename is a string
You have to use $new_location[$index]
or try
foreach ($new_location as &$file) {
...
...
$file = $new_filename;
I have code for getting files list in php, but if file name contain & character it doesn't display that file.
Here's the code:
Ps. I'm not php programmer and I really don't know what is this error.
All help will be very appreciated
Thanks so much in advance.
<?php
include_once('config.inc.php');
$current_dir = 'root';
if(array_key_exists('directory',$_POST)) {
$current_dir = $_POST['directory'];
}
// Creating a new XML using DOMDocument
$file_list = new DOMDocument('1.0');
$xml_root = $file_list->createElement('filelist');
$xml_root = $file_list->appendChild($xml_root);
// Setting the 'currentPath' attribute of the XML
$current_path = $file_list->createAttribute('currentPath');
$current_path->appendChild($file_list->createTextNode($current_dir));
$xml_root->appendChild($current_path);
// Replacing the word 'root' with the real root path
$current_dir = substr_replace($current_dir, $root, 0, 4);
$di = new DirectoryIterator($current_dir);
// Creating the XML using DirectoryIterator
while($di->valid())
{
if(false == $di->isDot())
{
if($di->isDir() && true != in_array($di->getBasename(),$h_folders))
{
$fl_node = $file_list->createElement('dir');
$xml_root->appendChild($fl_node);
}else if($di->isFile() && true !== in_array($di->getBasename(),$h_files)
&& true !== in_array(get_ext($di->getBasename()),$h_types))
{
$fl_node = $file_list->createElement('file');
$xml_root->appendChild($fl_node);
}else
{
$di->next();
continue;
}
$name = $file_list->createElement('name',$di->getBasename());
$fl_node->appendChild($name);
$path = substr_replace($di->getRealPath(), 'root', 0, strlen($root));
$path_node = $file_list->createElement('path', $path);
$fl_node->appendChild($path_node);
$di->next();
}else $di->next();
}
function get_ext($filename)
{
$exp = '/^(.+)\./';
return preg_replace($exp,'',$filename);
}
// Returning the XML to Flash.
echo $file_list->saveXML();
?>
The & character is used in HTML to write entities.
If you want to display arbitrary text in HTML, you need to escape it by calling htmlentities().
If you give some source I can help, file content not file name.
Example how get list of files:
$c = "/some/path/to/file/here";
if(is_dir($c)){
foreach(scandir($c) as $file){
if($file != '.' && $file != '..'){
$d = $c.DIRECTORY_SEPARATOR.$file;
echo " \"". realpath($d) ."\"\n";
}
}
}
I have an issue with my host (and maybe my internet connection) : i use filezilla to upload several huge .zip on my website (each .zip weighs ca. 500Mo) and the connection closes before the upload's end.
So, i thought i would upload a folder containing my photographies (in that way, filezilla uploads several little files and not ONE HUGE file), and then i will make an archive of these by passing through a php script.
Here is the code i did :
/*
params :
string $nom_archive: archive's name in '.zip' (ex. 'archive.zip', 'test.zip', etc.)
string $adr_dossier: the path of the folder to archive (ex. 'images', '../dossier1/dossier2', etc.)
string $dossier_destination : path of the folder where we will copy/paste the archive (ex. 'images/zip', '../archives', etc.)
DOn't change the params $zip and $dossier_base
*/
function zipper_repertoire_recursif($nom_archive, $adr_dossier, $dossier_destination = '', $zip=null, $dossier_base = '') {
if($zip===null) {
$zip = new ZipArchive();
if($zip->open($nom_archive, ZipArchive::CREATE) !== TRUE) {
return false;
}
}
if(substr($adr_dossier, -1)!='/') {
$adr_dossier .= '/';
}
if($dossier_base=="") {
$dossier_base=$adr_dossier;
}
if(file_exists($adr_dossier)) {
if(#$dossier = opendir($adr_dossier)) {
while(false !== ($fichier = readdir($dossier))) {
if($fichier != '.' && $fichier != '..') {
if(is_dir($adr_dossier.$fichier)) {
$zip->addEmptyDir($adr_dossier.$fichier);
zipper_repertoire_recursif($nom_archive, $adr_dossier.$fichier, $dossier_destination, $zip, $dossier_base);
}
else {
$zip->addFile($adr_dossier.$fichier);
}
}
}
}
}
if($dossier_base==$adr_dossier) {
$zip->close();
if($dossier_destination!='') {
if(substr($dossier_destination, -1)!='/') {
$dossier_destination .= '/';
}
if(rename($nom_archive, $dossier_destination.$nom_archive)) {
return true;
}
else {
return false;
}
}
else {
return true;
}
}
}
And then, i call my function that way :
zipper_repertoire_recursif('Myriam&Fabien_byGFernandez_Originales.zip', './Myriam&Fabien/Photos/originales/photos_originales', './Myriam&Fabien/Photos/originales')
But it won't work, and i don't know why.
I've checked if zip is enabled on my server and it is.
DO you have any idea on my problem?
Maybe I'm using ZipArchive the wrong way, but i can't figure out what i did wrong.
COuld you help me, please?
Thank you very much.