Hello I'd been exploring of using framework cakephp in implementing sites. In my current PHP script this error comes up: Undefined offset: 1 and its already giving me a headache. Can you guys help me out what I am doing wrong.
My code is here:
function file_upload($file_array, $id){
if(count($file_array))
{
$location = "files/library-files/";
foreach ($file_array as $file) {
$ext = explode(".", $file['name']);
$new_name = md5(uniqid());
$target_path = $location . $new_name .".".$ext[1];
if(move_uploaded_file($file['tmp_name'], $target_path))
{
$this->LibraryFiles->create();
$this->LibraryFiles->set('id', $new_name);
$this->LibraryFiles->set('library_id', $id);
$this->LibraryFiles->set('name', $file['name']);
$this->LibraryFiles->set('ext', $ext[1]);
$this->LibraryFiles->set('type', $file['type']);
$this->LibraryFiles->set('size', $file['size']);
if($this->LibraryFiles->save())
{
}
else
{
}
}
}
}
}
You can add the following check:
if(isset($ext[1]))
{
$target_path = $location . $new_name .".".$ext[1];
}
else if($file['name'] !== '.' && $file['name'] !== '..')
{
$target_path = $location . $new_name;
}
else
{
continue;
}
I just replaced this $target_path = $location . $new_name .".".$ext[1];
with
if (isset($target_path))
$target_path = $location . $new_name .".".$ext[1];
else
$target_path = '';
and now I am happy :D
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 am trying to extract file from a zip via PHP, I have some working code, but when I move it from one server to another it all of sudden stopped working :( In this code, it creates folders, I can see its doing that, but the files in the zip are not being extracted :(
Here is my code:
if($_FILES['url']['error'] == 0){
system('rm -rf ../images/galleries/' . $galleryName);
$filename = $_FILES["url"]["name"];
$source = $_FILES["url"]["tmp_name"];
$type = $_FILES["url"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if (!file_exists('../images/galleries/' . $galleryName)) {
mkdir('../images/galleries/' . $galleryName, 0777, true);
}
$target_path = '../images/galleries/' . $galleryName . '/' . $filename;
$image = $filename;
if(move_uploaded_file($source, $target_path)) {
$path = $target_path;
$zip = new ZipArchive();
if ($zip->open($path) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_")) . '_';
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
chmod('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], 0777);
}
$zip->close();
}
}
unlink($path);
$galleryClass->insertImage($connection, $_POST['galleryId'], $image, $_POST['link'], $_POST['order']);
}
I think the issue is with this:
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
is there another way to do this or is this a server problem?
Try using the extractTo() method instead of copy():
$zip->extractTo('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], $filename);
I've been working with image uploading and am wondering why this isn't working correctly? It doesn't move/upload the file with the new name if it already exists.
if(isset($_REQUEST['submit'])){
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
}
else{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");
}
}
else{
echo "invalid file.";
}
}
You've included the folder path in $loc, then you attempt to move a file to userpics/$loc, which is probably incorrect. See the comments:
$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
// $loc is now "userpics/example1.jpg"
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
// Now you're trying to move the uploaded file to "userpics/$loc"
// which expands to "userpics/userpics/example1.jpg"
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
// ...
As a general debugging tip, always check a function's return value to see if it was successful. Secondly, display the function's input values if it's failing. It will make debugging things a lot easier.
Try this:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
Thanks to here:Clickie!!
The main issue it's still the same:
This is my proyect
/
| index.php
|-test1
| test.php
The test.php
<?php
echo $variable;
?>
The index.php
<?php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php");
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
And it's works like a charm, the output is:
test
index
If i want to encapsulate this functionality in a function like this:
index1.php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php" );
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
}
rTest($full_path, $adm_extension);
I got this:
( ! ) Notice: Undefined variable: variable in C:\wamp\www\sandbox\test1\test.php on line 3
Any clue??
your script probably, when going through files, opens test.php before index1.php so $variable isn't defined yet
test it:
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
echo $item_path.'<br />';
require $item_path;
}
}
}
}
}
}
Ok, a friend help me to solve it out.
It's was a really dumb error. The problem was when I made the require, it was made in the function scope.
For my solution I do something like this:
function rTest($full_path, $adm_extension){
$paths = array();
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
$paths[] = $item_path;
}
}
}
}
}
return $paths;
}
foreach(rTest($full_path, $adm_extension) as $path){
require $path;
}