Can someone tell me why this php code doesn't work? It doesn't chek if file_exists, but it just run the code. Sorry for my bad (grammer) english, english is not my main langue :).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName;
$dest = "../Sites/NewSite1/$fileName";
if(file_exists($fileName)){
copy($src, $dest);
echo $fileName;
}else{
$fileName = "../templates/Default/$dirName";
$fileName = str_replace("$dirName", "$dirName/*", $fileName);
$dFiles = glob($fileName);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
copy($src2, $dest);
echo $src2;
}
}
}
if you want to check whether the file exists in the directory where you are trying to copy it to, then you need to provide file_exists() with the entire directory path, therefore do the following:
change this: if (file_exists($fileName)) {
to this: if (file_exists($dest)) {
Here is the right code: (it still need some tweeking).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName2 = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName2;
$dest = "../Sites/$websiteName/$fileName2";
if (!copy($src, $dest)) {
$fileName3 = "../templates/Default/$dirName/*";
$dest2 = "../Sites/$websiteName/$fileName2";
$dFiles = glob($fileName3);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
$fileName4 = $src2;
$fileName4 = str_replace("../templates/Default/$dirName/", "", $fileName4);
mkdir("../Sites/$websiteName/$dirName");
$dest2 = "../Sites/$websiteName/$dirName/$fileName4";
copy($src2, $dest2);
}
}
}
Related
I have a folder containing several photos all in .jpg
The name they should all have is STYLE_COLOR-n.jpg for example K14700_7132-6.jpg because I made a script that deletes all the photos greater than -6.jpg.
My problem is that I have photos that are badly renamed, i.e. they have an underscore at the end instead of the dash like :
K14700_7132_6.jpg
Some also have a dash on both like this:
K14700-7132_6.jpg
And so my delete script doesn't work if the pictures don't all have the same rename...
Is it possible to automatically replace all the dashes and underscores that are bad to have this format on all my folder STYLE_COLOR-n.jpg?
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file)
{
if (!in_array($file,array(".","..")))
{
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
$underscore = explode("_", $filename);
// echo $underscore[0]."<br>"; //KA0710
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6)
{
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
}
else
{
}
}
}
echo "Deleted photos !";
?>
Sure, this is the part you'll add to that code:
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
Note - this will permanently rename files (that need it) so BEFORE you run this in production, please test for the old/new rename arguments just to be safe!
Here is the whole enchilada
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".",".."))) {
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
// first fix the format
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
$underscore = explode("_", $filename);
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6) {
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
} else {
}
}
}
echo "Deleted photos !";
?>
I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.
I would like to upload some files to my server. So far, they have been successfully stored in a MySQL database, but the problem is that the uploaded file is not found in a folder that is located on the server.
Here's my code:
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
Is there anything I missed?
Please change $formatfile = array('pdf') to $formatfile = array('.pdf'=>'application/pdf');
$dir = $filename; Whis is vlaue of $filename ?
please use like this.
$dir = '/var/www/uploads/';
if(in_array($existence, $formatfile)){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
whenever you are uploading a file.try the full path.
<?php
$dir = $filename;
$target_dir = dirname(__FILE__).'/file/'.$dir.'/';
if (is_dir($target_dir) === false) {
mkdir($target_dir);
}
if (isset($_POST['submit'])) {
$formatfile = array('pdf');
$filetest = $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence = strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if (in_array($existence, $formatfile) === true) {
if ($pdfsize < 1044070) {
move_uploaded_file($file_tmp, $target_dir.$filetest);
}
}
}
$sql = 'INSERT INTO test (filename) VALUES ('.$filetest.')';
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
//Remove ""
move_uploaded_file($file_tmp, $target_dir.$filetest);
//If file upload then and then execute query.
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
}else{
//Fire error
}
}else{
//Fire error
}
}else{
//Fire error
}
I'm creating a function where users can upload multiple images and upload them to the server. Using a global variable for this matter works, but I've heard global variables are bad especially in OOP. So, I'm wondering what a good alternative would be? (I'm a starting PHP programmer, any detailed information is appreciated)
Code:
function addImgToNieuws($images){
if (isset($images) && $images != "") {
$countFiles = count($images["name"]);
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$output = $this->db->real_escape_string($db_file_name);
global $string;
$string .= ",$output";
$string = substr($string, 1);
}
echo $string;
}
}
function addImgToNieuws($images){
if (isset($images) && $images != "") {
throw new Exception("bad input bro");
}
$countFiles = count($images["name"]);
$db_names = array();
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$db_names[] = $this->db->real_escape_string($db_file_name)
}
return $db_names;
}
Assuming you wanted to get the $db_names. It's a little bit odd to do the escaping here, I would delay it until the very moment you insert it in the query.
If you really wanted the $db_names as a string you can do:
echo join(",", $obj->addImgToNieuws($images));
I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}