Inserting PHP objects to database - php

<?php
class Prof {
function get_block($lines, $prof_num) {
$reserve = 200;
$strings = implode("", $lines);
$start_line = preg_grep("/1\.$prof_num\.1\./m", $lines);
$prof_num+=1;
$end_line = preg_grep("/1\.$prof_num\.1\./m", $lines);
$prof_num-=1;
$start_pos = mb_strpos($strings, end($start_line));
$end_pos = mb_strpos($strings, end($end_line));
$finalContent = mb_substr($strings, $start_pos-$reserve, $end_pos-$start_pos+$reserve);
$from = "1.$prof_num";
$prof_num+=1;
$to = "1.$prof_num";
$cutted = mb_substr($finalContent, strpos($finalContent, $from), strpos($finalContent, $to));
$cutted = preg_replace("/$to\..*/", "", $cutted);
// echo $cutted;
// $this->get_id($cutted);
// $this->get_name($cutted);
}
function get_id($txt) { //gettind id
$txt = explode("\n", $txt);
$id = preg_grep("/\d\.\sCode\s/", $txt);
$id = preg_replace("/\d\.\sCode\s\–\s/","", $id);
$id = preg_replace("/\t/", "",$id);
$id = preg_replace("/\.\s+/", "",$id);
foreach($id as $item) {
echo $item ."\n";
}
}
function get_name($txt) { //getting name
$txt = explode("\n", $txt);
$name = preg_grep("/\sName/", $txt);
$name = preg_replace("/\d\.\sName\–\s/","",$name);
$name = preg_replace("/\t/", "",$name);
$name = preg_replace("/\.\s+/", "",$name);
foreach($name as $item) {
echo $item ."\n";
}
}
Obj1 = new Prof();
Obj1 -> get_name(get_block(file('text.txt'))); //ERROR HERE!!!!!!!!
How can I get to get_id and get_name through get_block method?
- get_block gets me the whole text from text file, starting from line number $prof_num.
- get_id gets me the id from the get_block text block. get_name just gets the name from
get_block.
I need to write these methods (id and name) to my database, but as I know, I can't do it, if I only manage to get text block with get_block.
Pls, ask me if something, maybe I just can't explain it. :D

This is wrong:
Obj1 -> get_name(get_block(file('text.txt')))
The function get_block() is not defined, it is a method of your Pro class.
So you would need:
$Obj1->get_name($Obj1->get_block(file('text.txt')));
or, if it is a static method:
$Obj1->get_name(Pro::get_block(file('text.txt')));
Also note that get_block() is defined as a method that takes 2 parameters, something that looks like a string (based on the name...) and a number (based on the name...). So sending it only an array - the return value of file() - will also fail.

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.

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

Replace valuie in text file with php

i have a text file with the following design:
john smith|1|john#smith.com|nopassword|admin
Tom smith|3|tom#smith.com|admin123|user
....
And so on.
Every field is delimited by "|".
What i need to do is replace values for example the password or the account type of a user in this text file.
Tom smith|5|tom#smith.com|admin1234|admin
I succeeded in finding the line and spiting it with explode() but how do i modify the value and write it back on the text file ?
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
foreach($mydb as $line) {
if(stristr($line,$name)) $pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
There are various ways to do this. Here's one way. I commented the code to explain how it works.
$name = $_POST['name'];
// use FILE_IGNORE_NEW_LINES so you won't have to deal with the line breaks
$mydb = file('./DB/users.txt', FILE_IGNORE_NEW_LINES);
// use a reference (&$line) so the code in your foreach loop modifies the $mydb array
foreach ($mydb as &$line) {
if (stristr($line,$name)) {
// assign the elements of the row to variables
list($name, $number, $email, $password, $type) = explode('|', $line);
// change whatever you need to change
$password = 'new password';
$type = 'new type';
// overwrite the line with the modified values
$line = implode('|', [$name, $number, $email, $password, $type]);
// optional: break out of the loop if you only want to do the replacement
// for the first item found that matches $_POST['name']
break;
}
};
// overwrite the file after the loop
file_put_contents('./DB/users.txt', implode("\n", $mydb));
PHP gives the options of reading, writing, and appending to files.
You need to open the file, read all content in, and then overwrite the file. You will get duplicate entries using append.
Here is an example code from https://www.w3schools.com/php/php_file_create.asp:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
For your code:
<?php
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
$output = array();
foreach($mydb as $line) {
if(stristr($line,$name)) {
$pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
// Glue the variables back together and overwrite $line so that it gets up in the array
$line = $name & "|" $position & "|" $email & "|" $password & "|" $atype & "\r";
}
// put everything in the $output array so that it can be writen to file after this loop
array_push($output, $line);
}
fclose($mydb);
// Write your output to file
$mydb = fopen('./DB/users.txt', "w") or die("Unable to open file!");
foreach($output as $line) {
fwrite($mydb, $line);
}
fclose($mydb);
?>

PHP Preg Match All fails when matching string with HTML.

I'm trying to match the class names in the following.
<section className="content_main_container">
<article className="comment_user_propic">
But only the "article" className is matched.
I've tried the following.
function comments(){
$str = <<<EOT
'<section className="content_main_container">
<article className="comment_user_propic">'
EOT;
return $str;
}
class obfusicate {
function change($str, $prefix){
preg_match_all('#'.$prefix.'="(.*?)"#',$str,$parts);
$array_len = count($parts[1]);
$class_count = 0;
$c_array = [];
foreach($parts[1] as $part){
$rand_name = self::rand_g();
$c_array[$part] = $rand_name;
++$class_count;
$str_1 = str_replace($part, $rand_name, $str);
}
return ['array'=>$c_array, 'string'=>$str_1];
}
}
$obs = new obfusicate;
$result = $obs->change(comments(), 'className');
echo var_dump($result['string']);
Your bug is here:
foreach($parts[1] as $part){
$rand_name = self::rand_g();
$c_array[$part] = $rand_name;
++$class_count;
$str_1 = str_replace($part, $rand_name, $str); //each time you start over replacing from $str and you lose your last $str_1 value
}
return ['array'=>$c_array, 'string'=>$str_1]; //Assigned after the loop so only the last $str_1 value is stored
EDiT: Look at my comment in the last line

Yet another question of my googlemaps problem

I have asked in two earlier questions to place multiple markers from a XML file created from Lightroom, which had to be tranformed in degrees instead of Degrees,Minutes,Seconds.
This part i managed but then...
The answers in the previous question were very informative but it's my poor skill of programming (first project) that i just cannot manage to solve it.
The problem is i want to show multiple markers.
the complete code:
<?php
require('GoogleMapAPI.class.php');
$objDOM = new DOMDocument("1.0", 'utf-8');
$objDOM->preserveWhiteSpace = false;
$objDOM->load("googlepoints.xml"); //make sure path is correct
$photo = $objDOM->getElementsByTagName("photo");
foreach ($photo as $value) {
$album = $value->getElementsByTagName("album");
$albu = $album->item(0)->nodeValue;
$description = $value->getElementsByTagName("description");
$descriptio = $description->item(0)->nodeValue;
$title = $value->getElementsByTagName("title");
$titl = $title->item(0)->nodeValue;
$link = $value->getElementsByTagName("link");
$lin = $link->item(0)->nodeValue;
$guid = $value->getElementsByTagName("guid");
$gui = $guid->item(0)->nodeValue;
$gps = $value->getElementsByTagName("gps");
$gp = $gps->item(0)->nodeValue;
$Deglon = str_replace("'", "/", $gp);
$Deglon = str_replace("°", "/", $Deglon);
$Deglon = str_replace("", "/", $Deglon);
$str = $Deglon;
$arr1 = str_split($str, 11);
$date = $arr1[0]; // Delimiters may be slash, dot, or hyphen
list ($latdeg, $latmin, $latsec, $latrichting) = split ('[°/".-]', $date);
$Lat = $latdeg + (($latmin + ($latsec/60))/60);
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {$Latcoorl = str_replace(" N ", "+",$latdir);}
else {$Latcoorl = str_replace ("S ", "-",$latdir);}
//$Latcoord=$Latcoorl.",";
$date1 = $arr1[1]; // Delimiters may be slash, dot, or hyphen
list ($londeg, $lonmin, $lonsec, $lonrichting) = split ('[°/".-]', $date1);
$Lon = $londeg + (($lonmin + ($lonsec/60))/60);
$londir = $lonrichting.$Lon;
If (preg_match("/W /", $londir)) {$Loncoorl = str_replace("W ", "+",$londir);}
else {$Loncoorl = str_replace ("E", "-",$londir);}
$Lonarr = array($Loncoorl);
foreach ($Lonarr as &$LonArray);
$Latarr = array($Latcoorl);
foreach ($Latarr as &$LatArray);
$titarr = array($titl);
foreach ($titarr as &$titArray);
$guarr = array($gui);
foreach ($guarr as &$guaArray);
$albuarr = array($albu);
foreach ($albuarr as &$albuArray);
print_r ($LonArray);
print_r ($LatArray);
print_r ($guaArray);
print_r ($albuArray);
$map = new GoogleMapAPI('map');
// setup database for geocode caching
// $map->setDSN('mysql://USER:PASS#localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('ABQIAAAAiA4e9c1IW0MDrtoPQRaLgRQmsvD_kVovrOh_CkQEnehxpBb-yhQq1LkA4BJtjWw7lWmjfYU8twZvPA');
$map->addMarkerByCoords($LonArray,$LatArray,$albuArray,$guaArray);
}
?>
The problem is that the "$map->addMarkerByCoords($LonArray,$LatArray,$albuArray,$guaArray);" only shows the last value's from the 4 arrays.
And there fore there is only one marker created.
The output (print_r) of for example the $guaArray is IMG_3308IMG_3309IMG_3310IMG_3311IMG_3312 (5 name's of filename's from photographs).
The function addMarkersByCoords from the 'GoogleMapAPI.class.php' is like this:
function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '') {
$_marker['lon'] = $lon;
$_marker['lat'] = $lat;
$_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
$_marker['title'] = $title;
$_marker['tooltip'] = $tooltip;
$this->_markers[] = $_marker;
$this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
// return index of marker
return count($this->_markers) - 1;
}
I hope that someone can help me ?
You must create the new instance of the google map above the foreach
like this
$map = new GoogleMapAPI('map');
// setup database for geocode caching
// $map->setDSN('mysql://USER:PASS#localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('ABQIAAAAiA4e9c1IW0MDrtoPQRaLgRQmsvD_kVovrOh_CkQEnehxpBb-yhQq1LkA4BJtjWw7lWmjfYU8twZvPA');
foreach ()
{
}
now you are creating every loop a new map with the last coord
Your foreach loops aren't accomplishing annything useful:
$Lonarr = array($Loncoorl);
foreach ($Lonarr as &$LonArray);
$LonArray is just one element from the $Lonarr array. I think the foreach loop is adding each element of the array onto one big string ($LonArray).

Categories