How can i add a number to a file name in php - 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.

Related

How to fix url contains arabic characters

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;
}

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

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);

Write PHP to find a word in a text file using a loop

Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.

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