How to fix url contains arabic characters - php

I want to get the url of each file in certain directory
i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.
example:
this is my code output:
String A :
https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3
this code is not working in some android devices
but the next code works with all devices
String B:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
Note: i got String B from internet download manager that converts it automatically when i tried to use string A
my question is:
how to convert String A to String B by php
and is there better way to readdir and get the url of each file
My code is:
if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
//...
} else { //create object with two fields
sort($file);
$fileName = pathinfo($file)['filename'];
if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}

Try this one, I've used once for a legacy project:
function encode_fullurl($url) {
$output = '';
$valid = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*\'();:#&=+$,/?#[]%';
$length = strlen($url);
for ($i = 0; $i < $length; $i++) {
$character = $url[$i];
$output .= (strpos($valid, $character) === false ? rawurlencode($character) : $character);
}
return $output;
}
$url ="https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3";
echo encode_fullurl($url);
output:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
it is not very performing, but it should do what you need

this code worked for me
thanks every one
$res1 = "https://linkimage2url.com" .$path."/".$file;
$query = flash_encode ($res1);
$url = htmlentities($query);
function flash_encode($string)
{
$string = rawurlencode($string);
$string = str_replace("%2F", "/", $string);
$string = str_replace("%3A", ":", $string);
return $string;
}

Related

How can i add a number to a file name in php

Goodevening to everyone, how can i add a number to a file name in php.
Let me explain; I want to save a file using a dropzone but i want to rename the file if it exist in the folder.
I've written down this code but the regex doesn't work and also if it's possible to insert the number before the extension of the file like google chrome does.
if(file_exists($target_file)){
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}else{
$pos=preg_match_all($target_file, "'('[0-9]{1,}')'");
$pos=$pos++;
$pos1=strpos($pos, $target_file, ")");
$pos1=$pos1-$pos;
$num=substr($target_file, $pos, $pos1);
$num = (int)$num;
$num =$num++;
$sostituisci="(".$num.")";
$target_file=preg_replace("'('[0-9]{1,}')'", $sostituisci, $target_file);
}
}
$name is the name of the file i want to save with the extension
the first $target_file of the code contain the full path + the name of the file
$target_file is a sting like /dropzone/upload/filename.txt and $name is a string like filename.txt. If the $targetfile exist i would to rename the $name like filename(1).txt or filename(2).txt and so on
also other solutions are accepted like a js library.
I assume you are referring to this set of code here.
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}
insert the number before the extension of the file
EDIT: Use explode() and re-format the ext.
EXAMPLE:
$target_path = "/assets/imgages/";
$name = 'img.jpg';
$name = explode('.', $name);
$format = $name[0].'(1).'.$name[1];
$path = $target_path.$format;
Will produce the following string:
/assets/img/notes(1).txt
Accept multiple dots in string.
$filename = 'company.jobtitle.field.text';
function formatDuplicateExtension($filename){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '(1).'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
echo formatDuplicateExtension($filename);
$filename = 'company.jobtitle.field.text';
OUTPUTS: //-->/assets/imgages/company.jobtitle.field(1).text
$name = 'trees.vac2012.img.jpg';
OUTPUTS: //--> /assets/imgages/trees.vac2012.img(1).jpg
I've found a solution idk if it's the best one because regex searches and substitutions are involved a lot of times and it seems to be they're resources consuming functions.
//this function insert the $number in the name of the file before .extension
function InsertBeforeExtension($filename,$number){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '('.$number.').'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
//this function check if there's a string like (number).ext in the name
//if yes increment the (number) in the string that become (number++).ext
//if no insert (1) before .ext
function insertnumber($string){
$matches=array();
$re = '/[(][0-9]+[)]\.[a-zA-Z]+/m';
preg_match_all($re, $string, $matches, PREG_SET_ORDER, 0);
if($matches[0][0]){
//if (number).ext is present
$re = '/[(][0-9]+[)]/m';
$str = $matches[0][0];
//select the (number) only
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
//remove parethesis
$str=substr($matches[0][0],1,-1);
//cast sting to an int for add a number
$int = (int)$str;
$int++;
//replace the last (number) match in the name of the file with (number++)
$re = '/(.*)[(][0-9]+[)]/m';
$subst = '${1}('.$int.')';
$result = preg_replace($re, $subst, $string);
}else{
//if (number).ext is not present insert (1) before .ext
$result=InsertBeforeExtension($string,1);
}
return $result;
};
$target_file = $target_path.$name;
//If the file exist repeat to find the number of file that doesn't exist
if( file_exists( $target_file )) {
while(file_exists( $target_file )){
$name=insertnumber($name);
$target_file = $target_path.$name;
}
}
The only problem is that if you have uploaded a file named like file(3).txt and you upload another file with the same name this function rename it in file(4).txt and not in file(3)(1).txt but for my scope this is not important
I've commented the code trying to be the most clear possible this solution seems to work well but i've not calculate the performance.

How to separate mp3, mp4 file name from string using php?

Hi anyone can help I want separate mp3, mp4 from imploded data in PHP
my data string
$data = "song1.mp3, video1.mp4, song2.mp3"
i want to divide into two separate strings 1 string contains only mp4 with (,) separated and another with mp3
my data from database:
$data = "song1.mp3, video.mp4, song2.mp3";
$mp4 = video1.mp4,video2.mp4,..etc;
$mp3 = song1.mp3,song2.mp3,..etc;
thank you
Assuming your songs names are well formatted, meaning that they are named as title.suffix
<?php
$data = "song1.mp3, video.mp4, song2.mp3";
$mp3 = [];
$mp4 = [];
$song_names = explode(',', $data);
foreach ($song_names as $song_name) {
$song_name = trim($song_name);
$parts = explode('.', $song_name);
if (count($parts) == 2) {
$suffix = $parts[1];
if ($suffix == 'mp3') {
$mp3[] = $song_name;
} else if ($suffix == 'mp4') {
$mp4[] = $song_name;
}
}
}
//using implode so that we won't have an extra comma hanging in the end
$mp4 = implode(', ', $mp4);
$mp3 = implode(', ', $mp3);
?>
Use explode() to converting string to array by , delimiter. Then loop through array items and get extension of file name using substr() and check it.
$data = "song1.mp3, video1.mp4, song2.mp3";
$mp4 = $mp3 = "";
foreach (explode(",", $data) as $file){
$file = trim($file);
substr($file, -3) == "mp4" ? $mp4.=$file."," : $mp3.=$file.",";
}
$mp4 = substr($mp4, 0, -1);
$mp3 = substr($mp3, 0, -1);
Check result in demo
This sounds like a job for a preg_match_all() regex:
<?php
$string = 'song1.mp3, video.mp4, song2.mp3';
$regex = '#([^,\s]+\.mp3)#';
preg_match_all($regex, $string, $mp3s);
$regex = '#([^,\s]+\.mp4)#';
preg_match_all($regex, $string, $mp4s);
var_dump($mp3s[0]);
var_dump($mp4s[0]);
Which gives you:
array(2) { [0]=> string(9) "song1.mp3" [1]=> string(9) "song2.mp3" }
array(1) { [0]=> string(9) "video.mp4" }
Here's the code in action https://3v4l.org/2EmkR
Here's the docs for preg_match_all() http://php.net/manual/en/function.preg-match-all.php
Ok - a slightly different approach using pathinfo
$data = 'song1.mp3, video1.mp4, song2.mp3';
$mp3s = [];
$mp4s = [];
foreach (explode(', ', $data) as $file) {
$type = pathinfo($file)['extension'];
$type === 'mp3' ? $mp3s[] = $file : $mp4s[] = $file;
}
echo implode(', ', $mp4s) . PHP_EOL;
echo implode(', ', $mp3s) . PHP_EOL;
Could definitely use some validation and so forth but as an MVP it does the trick.

Php simple algorithm for autoloader

Here's my "simple" algorithm:
if the class is named like 'AaaBbbCccDddEeeFff' loop like this:
include/aaa/bbb/ccc/ddd/eee/fff.php
include/aaa/bbb/ccc/ddd/eee_fff.php
include/aaa/bbb/ccc/ddd_eee_fff.php
include/aaa/bbb/ccc_ddd_eee_fff.php
include/aaa/bbb_ccc_ddd_eee_fff.php
include/aaa_bbb_ccc_ddd_eee_fff.php
if still nothing found, try to look if those files exist:
include/aaa/bbb/ccc/ddd/eee/fff/base.php
include/aaa/bbb/ccc/ddd/eee/base.php
include/aaa/bbb/ccc/ddd/base.php
include/aaa/bbb/ccc/base.php
include/aaa/bbb/base.php
include/aaa/base.php
include/base.php
If still not found then error.
I'm looking for a fast and easy way to convert this:
'AaaBbbCccDddEeeFff'
to this:
include/aaa/bbb/ccc/ddd/eee/fff.php
and then and easy way to remove latest folder (I guess I should look for explode()).
Any idea how to do this? (I'm not asking for the whole code, I'm not lazy).
Since you specifically asked not to have the whole code, here is some code to get you started. This takes the input and divides it into chunks delineated by changes in case. The rest you can work out as an exercise.
<?php
$input = "AaaBbbCccDddEeeFff";
$str_so_far = "";
$last_was_upper = 0;
$chunks = array();
while($next_letter = substr($input,0,1)) {
$is_upper = (strtoupper($next_letter)==$next_letter);
if($str_so_far && $is_upper && !$last_was_upper) {
$chunks[] = $str_so_far;
$str_so_far = "";
}
if($str_so_far && !$is_upper && $last_was_upper) {
$chunks[] = $str_so_far;
$str_so_far = "";
}
$str_so_far .= $next_letter;
$input = substr($input,1);
$last_was_upper = $is_upper;
}
var_dump($chunks);
?>
I think a regular expression would work. Something like preg_match_all('[A-Z][a-z][a-z]'
, $string); might work - that would match a capital letter, followed by a lowercase letter, and another lowercase letter.
As the other answers are regex, here's a non-regex way for completeness:
function transform($str){
$arr = array();
$part = '';
for($i=0; $i<strlen($str); $i++){
$char = substr($str, $i, 1);
if(ctype_upper($char) && $i > 0){
$arr[] = $part;
$part = '';
}
$part .= $char;
}
$arr[] = $part;
return 'include/' . strtolower(implode('/', $arr)) . '.php';
}
echo transform('AaaBbbCccDddEeeFff');
// include/aaa/bbb/ccc/ddd/eee/fff.php
This builds an array of the folders, so you can manipulate it as needed, for example remove a folder by unsetting the desired index, before it gets imploded.
Here is the first part of your algorithm:
AaaBbbCccDddEeeFff -> include/aaa/bbb/ccc/ddd/eee/fff.php
include/aaa/bbb/ccc/ddd/eee_fff.php
include/aaa/bbb/ccc/ddd_eee_fff.php
include/aaa/bbb/ccc_ddd_eee_fff.php
include/aaa/bbb_ccc_ddd_eee_fff.php
include/aaa_bbb_ccc_ddd_eee_fff.php
I think you can do last part independently based on my answer.
<?php
function convertClassToPath($class) {
return strtolower(preg_replace('/([a-z])([A-Z])/', '$1' . DIRECTORY_SEPARATOR . '$2', $class)) . '.php';
}
function autoload($path) {
$base_dir = 'include' . DIRECTORY_SEPARATOR;
$real_path = $base_dir . $path;
var_dump('Checking: ' . $real_path);
if (file_exists($real_path) === true) {
var_dump('Status: Success');
include $real_path;
} else {
var_dump('Status: Fail');
$last_separator_pos = strrpos($path, DIRECTORY_SEPARATOR);
if ($last_separator_pos === false) {
return;
} else {
$path = substr_replace($path, '_', $last_separator_pos, 1);
autoload($path);
}
}
}
$class = 'AaaBbbCccDddEeeFff';
var_dump(autoload(convertClassToPath($class)));

Scan special string using sscanf

I want for example to scan this $lang['foo1']='foo2'; from a PHP file so I tried
this but it doesn't work.
$file = "../lang/lang.en.php";
if(file_exists($file)) {
$text = fopen($file, 'r+');
$content = trim(file_get_contents($file, NULL, NULL, 221));
$i = 0;
do {
$n = sscanf($content, "\$lang['%s']=%s;", $s1[$i], $s2[$i]);
echo $s1[$i].'==>'.$s2[$i];
$i++;
} while($s1[$i]! = '' && $s2[$i] != '');
}
What is my problem?
You should just include('../lang/lang.en.php') like a normal PHP file.
Also, it's possible to make lang.en.php return an array directly with return, http://nl3.php.net/manual/en/function.return.php
I would recommend to use preg_match_all() in your case.
// Match
// $lang['PAGE_TITLE']='Meine Webseite Titel';
$content = file_get_contents('../lang/lang.en.php');
preg_match_all("~\$lang\['.+'\]\s=\s'.+';~", $content, $result);
var_dump($result);

How to Create a CSV file using PHP (and upload it)

For example, I have a variable "$foo" that includes all the data which I want to show in the CSV:
$foo = "some value,another value,last value";
My goal is to:
Create a CSV file named "some.csv" whose contents are equal to $foo
Upload "some.csv" to my server.
How can this be done?
Update: Here's the exact code that worked for me.
$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);
Number 1:
file_put_contents("foobar.csv", $yourString);
Number 2:
$c = curl_init("http://"...);
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "#foobar.csv"));
$result = curl_exec($c);
curl_close($c);
print_r($result);
note the # before the filename
See
fputcsv()
If $foo is already csv-formatted. You can use file_put_contents()
You don't specify the upload method. Here is an example using ftp (UNSECURE):
$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password#$url";
file_put_contents($hostname, $foo);
If you already have the variable with all the data you can use file_put_contents to save it as a csv
How to upload CSV file using PHP (Working Code)
Query Library
<?php
class query{
function mysql_query_string($string){
$enabled = true;
$htmlspecialchars = false; # Convert special characters to HTML entities
/****************************************************************
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
*****************************************************************/
if($htmlspecialchars){
# Convert special characters to HTML entities
$string = htmlspecialchars($string, ENT_QUOTES);
}
else{
/****************************************************************
'"' (double quote) becomes '"'
''' (single quote) becomes '''
****************************************************************/
//$string = str_replace('"',""",$string);
//$string = str_replace("'","'",$string);
}
if($enabled and gettype($string) == "string"){
# Escapes special characters in a string for use in a SQL statement
return mysql_real_escape_string(trim($string));
}
elseif($enabled and gettype($string) == "array"){
$ary_to_return = array();
foreach($string as $str){
$ary_to_return[]=mysql_real_escape_string(trim($str));
}
return $ary_to_return;
}
else{
return trim($string);
}
}
}
?>
Call Csv Method
public function csvFileSubmitData(){
$this->load->library('query');
$query=new query();
$root = DIR_PATH.'public/administrator/csv/';
$fileToUpload= (isset($_FILES['fileToUpload']) and $_FILES['fileToUpload']['size'] > 0 and
$_FILES['fileToUpload']['error'] == 0) ? $_FILES['fileToUpload'] : "";
if(is_array($fileToUpload)){ # CHECK UPLOADED FILE 1 FOR VALIDATION
$fileToUpload['name'] = str_replace(" ","_",$fileToUpload['name']);
$fileToUpload['name'] = str_replace("&","and",$fileToUpload['name']);
# CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
$fnarr = explode(".", $fileToUpload['name']);
}
$rand = rand(1000,10000);
$filecsv = $rand."_".$fileToUpload['name'];
$file1 = $root.$filecsv;
move_uploaded_file($fileToUpload['tmp_name'],$file1);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = $file1;
$addauto = 0;
$save = 0;
$outputfile = "output.sql";
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 1;
$queries = "";
$linearray = array();
$values = "";
$m =0;
$linestext = split($lineseparator,$csvcontent);
foreach($linestext as $line){
if($m++==0){
continue;
}
$lines++;
$line = trim($line," \t");
if($line == ''){
break;
}
$linearray = explode($fieldseparator,$line);
$topicname = $linearray[0];
$question = $linearray[1];
$answer1 = $linearray[2];
if(isset($linearray[1]) and $linearray[1] != ''){
$topicname = $query->mysql_query_string($linearray[0]);
$question = $query->mysql_query_string($linearray[1]);
$answer_type = $query->mysql_query_string($linearray[2]);
}
//Save Csv data in your table like this
//query(insert into topics SET `topic`='".$topicname."',`question`='".$question."');
}}
If you are using Codeignitor Framework so this code is too easy to integrate ,No hard&fast rule you can also use this code plain PHP as well as .....
Thanx
AbdulSamad
To create the CSV you would need to break your string into an array, then loop through it. After that you can save the file to any directory the web server account has access to on your server. Here is an example ...
//variables for the CSV file
$directory = '/sampledir/';
$file = 'samplefile.csv';
$filepath = $directory.$file;
//open the file
$fp = fopen("$filepath",'w+');
//create the array
$foo = "some value,another value,last value";
$arrFoo = explode(',',$foo);
//loop through the array and write to the file
$buffer = '';
foreach($arrFoo AS $value) {
$buffer .= $value."\r\n";
}
fwrite($fp,$buffer);
//close the file
fclose($fp);
Your file will now be written to the directory set in $directory with the filename set in $file.
-Justin

Categories