Rename folder which contains special characters using PHP - php

I have the following names in my database and also in directories.
Zúñnga
Mariè
etc...
The problem is I tried to do this:
$oldname = '/home/website/public_html/profile/Zúñnga';
$newname = '/home/website/public_html/profile/Zuunga';
rename($oldname, $newname)
And it doesn't work...
The names are stored in a database.
This is the following script I've been using to get the names out of the database, convert them to UTF-8, but simply the rename function doesn't work...
...
foreach($query as $item)
{
$name_tags = utf8_encode($item['name_tags']);
$oldname = '/home/website/public_html/profile/'.$name_tags.'';
$text = iconv('UTF-8','ASCII//TRANSLIT', $name_tags);
$text_1 = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $text);
$text_2 = preg_replace("/[^A-Za-z0-9- ]/", '', $text_1);
$name_tags_updated = str_replace(" ", "-", $text_2);
$newname = '/home/website/public_html/profile/'.$name_tags_updated.'';
rename($oldname, $newname)
$sql = 'UPDATE posts SET name_tags = "'.$name_tags_updated.'" where id = "'.$item['id'].'";
...
}
The query part is working fine; it's replacing the name with the good letters in the database, but when it comes to renaming the directory it simply doesn't work. Instead of changing the name to it's actual file, it just doesn't. I've tried to verify it this way
if(rename($oldname, $newname))
echo 'success';
else
echo 'fail';
it returns fail
On my website sometimes they are returned like this:
Mari�

Related

Compare for equality two cyrillic strings from sql database and .xls file in PHP

I am using phpoffice/phpspreadsheet to process .xlss the file.
As the columns order in the file may varry depending on the file sender I have a table in database, where I store the sender name (in cirilic) and the number of columns for the rest of data.
So, before processing the file I need to compare if the sender name from database is the same as the content of a field in the file to get the coresponded columns values and process the file only if name values match.
Despite the fact, that I am 100% sure they are the same, whatever comparison I try return false.
1. File processing
$allowedFileType = [
'application/vnd.ms-excel',
'text/xls',
'text/xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
$targetPath = './tmp/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$filename = $_FILES['file']['name'];
$error = 0;
//Check if file is already uploaded
if (!empty($importFromFile->getImportedFileName($filename))) {
setEventMessages($langs->trans('FileExists'), null, 'errors');
$error++;
}
if (!$error) {
$Reader = new Xlsx();
$spreadSheet = $Reader->load($targetPath);
$excelSheet = $spreadSheet->getActiveSheet();
$spreadSheetAry = $excelSheet->toArray();
$sheetCount = count($spreadSheetAry);
foreach ($externalsales->getImportSettings() as $obj) {
$name1 = $obj->ref; //This is the name from the database
$name_row = $obj->distributor_name_row - 1;
$name_column = $obj->distributor_name_column - 1;
$name2 = $spreadSheetAry[$name_row][$name_column]; //this is the name from the file
//At this point, I need to compare returned names from database to the name in the file
}
}
2. Compare
print $name1 . ' - ' . $name2;
//returns ДЕЛИВЪРИ ООД - ДЕЛИВЪРИ ООД
//You can see they are same
print strcasecmp($name1, $name2);
print strcasecmp(trim($name1), trim($name2));
print strcasecmp(mb_strtolower($name1), mb_strtolower($name2));
//all 3 return "176"
print strcmp($name1, $name2);
print strcmp(trim($name1), trim($name2));
print strcmp(mb_strtolower($name1), mb_strtolower($name2));
//all 3 return "1"
print strcoll($name1, $name2) . '<br>';
//returns "1"
$coll = collator_create( 'bg_BG' );
$res = collator_compare( $coll, $name1, $name2 );
print $res;
//returns "1"
For the test, I have inserted second record in the database with random name that I am not sure is in the files.
For the first 3 options, the return is 32,32,-176, for the second 3 is 1,1,-1, 1 for strcoll and -1 for the collator.
Any help appreciated.
To check what was causing the error, I've used bin2hex() for both values. The result showed that there were some white spaces (I presume the 20 stand for space as %20 in html) in the string coming from the .xls file.
The output was:
print bin2hex($name1)
//d094d095d09bd098d092d0aad0a0d09820d09ed09ed094
print bin2hex($name1)
//d094d095d09bd098d092d0aad0a0d0982020d09ed09ed0942020
So when I strip those white spaces with str_replace(' ', '', $name1); the if condition if ($name1 === $name2) returns true, which is what I was looking for.
If anyone can explain the reasons for this difference better than me feel free to reply.

PHP NSUpdate Update of an TXT String

iam using NSUpdate to update DNS Records from PHP
all things working, but somthing going wrong when i want update/Add TXT Record
adding an Text Record is not so hard like SRV OF SPF
nope :) rlly
The Problem:
trying to add somthing like "This IS an TXT record"
after sending it from PHP to NSUPDATE (works with other Records)
Bind DNS Server get this :
Domain IN TXT "This" "IS" "an" "TXT" "Record"
but this is wrong ! inspected my code, looked arround..it dosent work ..
code :
<?php
if ($txt_true) {
$ttl2 = '36';
// TXT string could be almost anything, just make sure it's quoted.
// $txt_var = str_replace("'", "", $txt_var);
// $txt_var = str_replace('"', "", $txt_var);
//$txt_var = '"'. $txt_var.'"';
$data .= "update add ".$sub.".".$domain.". ".$ttl2." IN TXT ".$txt_var."\n";
}
this going to NSupdate ( data + nsupdate etc...) dotn follow block that is out commented
here:
function dns_update ($id_domain,$mydata) {
global $nsupdate;
if (domain_exists($id_domain)) {
$infos = domain_infos($id_domain);
$domain = $infos['domain'];
$dnsip = $infos['dnsip'];
$key = $infos['key'];
if ($key != '') { $add = ' -y '.$key; }
$data = "server $dnsip\n";
$data .= "zone $domain\n";
$data .= $mydata;
$data .= "\n";
$result = `echo "$data" | $nsupdate$add`;
return $result;
} else {
return false;
}
}
and Quote TXT Record happens from
HTML => INPUT => DO => Wirte DB & Function => NSUPDATE
You need quotes around the text data. If it contains any embedded quotes, they need to be escaped:
$txt_var = str_replace('"', '\"', $txt_var);
$data .= "update add $sub.$domain. $ttl2 IN TXT \"$txt_var\"\n";
Since this string contains double quotes, you should use single quotes in your echo statement:
$result = `echo '$data' | $nsupdate$add`;
However, a much better idea would be to use an API rather than doing this through the command line. See the Net_DNS2 library.

removing unwanted characters from string in php

I'm using a database to store variables of user names and then access them using php. A form with post method is used to invoke a php file which access the database, retrieves all the user names and then compares them with the entered values. The user names are stored in $row['name'] variable and the name is stored in $photographer variable.
The problem is that there are some characters attached in string of variable $row['name'] when being accessed from db which I can't get rid of.
I thought using these variables directly might be causing some problems so I saved their values in other two variables. But the problem didn't go away.
Below is the php code:
//pin check module
$connection = mysqli_connect("localhost","root","","members") or die(mysqli_error($connection));
$select_query_pin = "SELECT name, pin FROM members";
$select_query_pin_result = mysqli_query($connection, $select_query_pin) or die (mysqli_error($connection));
$total = mysqli_num_rows($select_query_pin_result);
$pin = $_POST['pin'];
$title = explode(",",$_POST['title']);
$url = explode(",",$_POST['url']);
$photographer = $_POST['photographer'];
$genere = explode(",",$_POST['genere']);
$entry = sizeof($title);
while ($total) {
--$total;
$row = mysqli_fetch_array($select_query_pin_result);
$name_sample = $row['name'];
$test_sample = $photographer;
// chop($name_sample);
// chop($test_sample);
preg_replace( "/\r|\n/", "", $name_sample );
// for ($i = 0; $i < strlen($name_sample); $i++) {
// if ($name_sample[$i] == " ")
// echo 'true';
// }
var_dump($name_sample,$test_sample);
if ($name_sample === $test_sample)
echo 'true<br>';
else
echo "false<br>";}
As you can see, I tried using the chop and preg_replace methods but it didn't work. When I check the strings using var_dump, it gives unequal lengths for equal strings. The html view of above code is this:html output
Is there a way to deal with it?

Rename images in database to md5 but keep extensions

As the title says I'm wanting to change the image names stored in a database to md5 but keep the image extension, I had a go with the code below but it failed (probably due to the fact I haven't a clue what I'm doing) ...any ideas on how I could achieve my goal?
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$query = "SELECT img FROM post";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$name = substr($row['img'], -4, 4);
$ext = get_file_extension($row['img']);
$notmd5 = $row['img'];
$md5img = md5($name).'.'.$ext;
$q = "UPDATE post SET img='$md5img' WHERE img='{$notmd5}'";
$r = mysql_query($q) or die(mysql_error());
}
..........................................................
Update
Answer:
Rename files in dir/folder and db names at same time:
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
//path to directory to scan
$directory = "thumbs/";
$directory2 = "md5/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.*");
//print each file name
foreach($images as $image)
{
$imag = str_replace($directory, '', $image);
$ex = get_file_extension($imag);
$new = md5($imag).'.'.$ex;
rename($image, $directory2.$new);
$q = "UPDATE post SET img='$new' WHERE img='{$imag}'";
$r = mysql_query($q) or die(mysql_error());
}
When I originally asked my question I had already renamed the images in dir/folder but I had a backup of them so mixed the to jobs together and got my goal :)
First off, I'd recommend a batch update like this just be done with pure SQL, especially if the business logic is as simple as this, it can all be done natively in MySQL for sure.
Anyway.., one thing that pops out is the substr call to get the $name of the file, it's hardcoded to get only 4 characters and it's actually getting the extension not the name.
Try this instead:
$ext = get_file_extension($row['img']); // get ext first
// use length of $row['img'] - length of file extension to extract name
substr($row['img'], 0, strlen($row['img']) - strlen($ext) - 1);
Just do it in pure SQL:
UPDATE post SET img = CONCAT_WS('.',
MD5(TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(img, '.', -1)) FROM img)),
SUBSTRING_INDEX(img, '.', -1)
)

Insert data from custom PHP function into MySQL database

I'm having problems inserting a particular line of code into my MySQL database. It inserts three rows just fine, but the "html_href" row isn't going in for whatever reason. Here is my code:
function html_path() {
$title = strtolower($_POST['title']); // convert title to lower case
$filename = str_replace(" ", "-", $title); // replace spaces with dashes
$html_href = $filename . ".html"; // add the extension
}
And my MySQL query code:
$query = "INSERT INTO work (title, logline, html_href, synopsis) VALUES";
$query .= "('".mysql_real_escape_string($_POST['title'])."',";
$query .= "'".mysql_real_escape_string($_POST['logline'])."',";
$query .= "'".html_path()."',";
$query .= "'".mysql_real_escape_string($_POST['synopsis'])."')";
$result = mysql_query($query);
The title, logline, and synopsis values go in just fine, but the html_href() function inserts a blank row.
It looks like your html_path() function isn't returning anything.
Try:
function html_path() {
$title = strtolower($_POST['title']); // convert title to lower case
$filename = str_replace(" ", "-", $title); // replace spaces with dashes
$html_href = $filename . ".html"; // add the extension
return $html_href;
}
Your html_path() does not return the $html_href variable. Add
return $html_href;
before you close it, and it should work perfectly.

Categories