php Update filename from directory - php

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>

Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname

I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

Related

name of images from folder not printed on screen in php

I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.
i have the set the server using xampp.
how to correct this, i make the names of images from that folder printed on screen?
do i need to do anything extra
im a newbie in php. how can i achieve this?
<?php
function findImagesInFolder()
{
$folder = $_GET['C:\xampp\htdocs\firstsite'];
$images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
echo json_encode($images);
exit();
}
?>
It seems you have misused the $_GET variable.
I thing you want to just use the string value, ie.:
$folder = 'C:\xampp\htdocs\firstsite';
And note, the exit() terminates whole script after printing the json_encoded string.
So, to make the function reusable change it to get the path as a parameter $folder:
<?php
function findImagesInFolder($folder, $filter = '*.*')
{
// note, here we expect the path does not trail with backslash
$images = glob($folder . '\\' . $filter, GLOB_BRACE);
return json_encode($images);
}
// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>
Note: output as [] means empty array encoded to JSON.

If file with name.jpg exists do A else do B

I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.

How can I add variable names to the end of a file?

I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);

How to update csv column names with database table header

I am facing this problem some past days and now frustrate because I have to do it.
I need to update my CSV file columns name with database table header. My database table fields are different from CSV file. Now the problem is that first I want to update column name of CSV file with database table headers and then import its data with field mapping into database.
Please help me I don't know how I can solve this.
This is my php code:
$file = $_POST['fileName'];
$filename = "../files/" . $file;
$list = $_POST['str'];
$array_imp = implode(',', $list);
$array_exp = explode(',', $array_imp);
$fp = fopen("../files/" . $file, "w");
$num = count($fp);
for ($c = 0; $c < $num; $c++) {
if ($fp[c] !== '') {
fputcsv($fp, $array_exp);
}
}
fclose($fp);
require_once("../csv/DataSource.php");
$path = "../files/test_mysql.csv";
$dbtable = $ext[0];
$csv = new File_CSV_DataSource;
$csv->load($path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{ print_r($key[1]);
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into tablename($myKey)values($myVal)";
$res= mysql_query($query);
You have got an existing file of which the first line needs to be replaced.
This has been generally outlined here:
Overwrite Line in File with PHP
Some little explanation (and some tips that are not covered in the other question). Most often it's easier to operate with two files here:
The existing file (to be copied from)
A new file that temporarily will be used to write into.
When done, the old file will be deleted and the new file will be renamed to the name of the old file.
Your code does not work because you are already writing the new first line into the old file. That will chop-off the rest of the file when you close it.
Also you look misguided about some basic PHP features, e.g. using count on a file-handle does not help you to get the number of lines. It will just return 1.
Here is step by step what you need to do:
Open the existing file to read from. Just read the first line of it to advance the file-pointer (fgets)
Open a new file to write into. Write the new headers into it (as you already successfully do).
Copy all remaining data from the first file into the new, second file. PHP has a function for that, it is called stream_copy_to_stream.
Close both files.
Now check if the new file is what you're looking for. When this all works, you need to add some more steps:
Rename the original file to a new name. This can be done with rename.
Rename the file you've been written to to the original filename.
If you want, you then can delete the file you renamed in 5. - but only if you don't need it any longer.
And that's it. I hope this is helpful. The PHP manual contains example code for all the functions mentioned and linked. Good luck. And if you don't understand your own code, use the manual to read about it first. That reduces the places where you can introduce errors.
If you are managing to insert the table headers then you're half way there.
It sounds to me like you need to append the data after the headers something like:
$data = $headers;
if($fp[c]!=='')
{
$data .= fputcsv($fp, $array_exp);
}
Notice the dot '.' before the equals '=' in the if statement. This will add none blank $fp[c]values after the headers.

i need to get the name of a variable from a file

As the title said i need a way to set the variable name depending of what the name of the picture is (i got over 100 different pictures)
Since i got custom classes in another php file for each picture (like tags) like for example:
$picture1 = "hillside sunset";
$picture2 = "beach cyprus";
and so on, so i need to fetch each variable for each picture
Heres the current loop where the div class is going to be each pictures name ($PICTURENAME is just to define where this code goes and is irelevant codewise):
<?php
foreach (glob("img/*.jpg") as $filename)
{
$path = $filename;
$file = basename($path);
$file = basename($path, ".jpg");
echo '<div class="'.$PICTURENAME.'" id="'.$file.'"><img src="'.$filename.'"> '.$file.' </div>';
}
?>
Don't use 100+ variables. Using a database would make far more sense, but if you don't want to get into learning that (you should, though), using a data structure would still make far more sense.
You could create one array (and use it as a map), and have the filename as the key, and the value would be the tags.
In PHP, you can address a variable using another variable:
$name = "foo";
${$name} = "bar";
echo $foo; // prints "bar"
echo ${$name}; // the same as above
However, as Kitsune already recommended, you are better off using something else, e.g., an array.

Categories