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!!
Related
Here is my code it is working but I want the best practice
if(Input::hasFile('note_thumb')) {
$file = Input::file('note_thumb');
$fileName = substr($file->getClientOriginalName(), -4);
if ($fileName == '.jpg' || $fileName == 'jpeg' || $fileName == '.png') {
//is image
//return 'maaz';
$finalpath = "";
$file = Input::file('note_thumb');
$tmpFilePath = '/notes/thumnail/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFileName = preg_replace('/\s+/', '', $tmpFileName);
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFileName;
$finalpath .= $path;
/*if ($i != $count_file - 1) {
$finalpath .= ',';
}*/
$newNote->note_thumb = $finalpath;
}
Try this:
$extension = $request->note_thumb->getClientOriginalExtension();
From the documentation:
https://laravel.com/docs/5.6/requests
I'm trying to display images from folder. When I run my script I get following error -
"Only variables should be passed by reference in C:\wamp\www\salon\mainS\image_delete.php on line 72"
CODE:
<?php
$dir = 'uploads/';
$display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \''. $dir. '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($type, $display) == true)
{
echo'<div style="width:1170px;" >'.
'<div style="float:left; margin-right:5px;" >'.'<img style="width:200px; height:200px;"src="'. $dir. '/'. $file. '" alt="'. $file.'"/>'.'</div>'
.'</div>';
}
}
}
?>
my line 72 is
$type = strtolower(end(explode('.', $file)));
try this
$name_parts = explode('.', $file);
$type = strtolower(end($name_parts));
Try this:
$dir = 'uploads/';
if (file_exists($dir) == false) {
echo 'Directory \''. $dir. '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
try {
if (!is_dir($file) && (getimagesize($file))) {
echo'<div style="width:1170px;" >' .
'<div style="float:left; margin-right:5px;" >' . '<img style="width:200px; height:200px;"src="' . $dir . '/' . $file . '" alt="' . $file . '"/>' . '</div>'
. '</div>' . "\r\n";
}
} catch (Exception $e) {
continue;
}
}
}
Fix it by adding extra bracket, e.g.:
$type = strtolower(end((explode('.', $file))));
See: (<5.6) Occasionally significant parentheses
Assign the result of explode to a temporary variable and pass that variable at end, here is an example.
$tmp = explode('.', $fileName);
$fileExtension = end($tmp);
also to get extension you can also use following method
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
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);
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
I got a problem with a web upload. It is as follows:
I upload a picture and I look for the type (allowed jpeg, jpg, gif and png). Now I cut a part out of it and save it on a temporary resource which is created by the information of the type (if the type is jpg or jpeg, I use imagejpeg(), with PNG i use imagepng() and with gif I use imagegif()). Now this works. Then I save the images again.
And then I re-open them by imagecreatefromjpeg/-png/-gif. And then I get the error
Warning: imagecreatefromgif() [function.imagecreatefromgif]: 'uploads/gif/test.gif' is not a valid GIF file in /home/blabla/sliceit.php on line 88
Line 88 looks as follows:
$org_img = 'uploads/' . $name . "/" . $rand . (substr($type,0,1) != "." ? "." . $type : $type);
...
87: elseif ($type == ".gif") {
88: $src_img = imagecreatefromgif($org_img);
89: }
The same error happens also with png, but not with jpeg (because I wrote the following statement at the beginning:
ini_set('gd.jpeg_ignore_warning', 1);
). Jpeg warnings seem to be deactivated, but not the warnings for png and gif. And I created the image with mspaint, so they actually have to be valid.
Thanks for help.
Flo
EDIT: some code:
$name = 'something';
$filetype = substr($_FILES['datei']['name'],-4,4);
$filetype = strtolower($filetype);
$randomsessid = randomstring(60);
mkdir('uploads/' . $name);
move_uploaded_file($_FILES['datei']['tmp_name'],'uploads/' . $name . '/' . $randomsessid . (substr($filetype,0,1) == "." ? $filetype : "." . $filetype));
mysql_query("INSERT INTO SESSIONS VALUES('','" . $name . "','" . $randomsessid . "','" . strtolower($filetype) . "'," . time() . ")");
So now I got the file saved and the information in my table.
Now I'm linking to another file...
$id = mysql_real_escape_string($_GET["randid"]); //here I get the randomstring
if ($id == "") {
exit;
}
$unf = mysql_query("SELECT NAME, TYP FROM SESSIONS WHERE RANDOM = '" . $id . "'");
if (mysql_num_rows($unf) == 1) {
$f = mysql_fetch_object($unf);
$name = $f->NAME;
$filetype = $f->TYP;
}
else {
exit;
}
$image_resize = new image_resize; //this is a very useful class to resize images
$size = $_GET["size"]; //here is 'auto' inside
$log->debug('size: ' . $size);
if ($size == "custom" and isset($_GET["x"]) and isset($_GET["y"])) {
//blabla some code...
}
else {
$image_resize->load("uploads/" . $name . "/" . $id . (substr($filetype,0,1) == "." ? $filetype : "." . $filetype));
$image_resize->resize(600,600);
$image_resize->save("uploads/" . $name . "/" . $id . (substr($filetype,0,1) == "." ? $filetype : "." . $filetype));
}
And now another redirect ....
ini_set('gd.jpeg_ignore_warning', 1);
$id = $_GET["randid"];
if ($id == "") {
exit;
}
$tempsel = "SELECT * FROM SESSIONS WHERE RANDOM = '" . $id . "'";
$unf = mysql_query($tempsel);
if (mysql_num_rows($unf) != 1) {
$log->debug('tempsel: ' . $tempsel);
exit;
}
$f = mysql_fetch_object($unf);
$name = $f->NAME;
$type = $f->TYP;
for ($i = 1; $i <= 9; $i++) {
createImagePart($i,$name,$type,$id,$log); //$i = for loop, $name = the name from the beginning, $type defined, $id = random id, $log = a previously defined log class.
}
And the called function createImagePartI():
function createImagePart($nr,$name,$type,$id,$log) {
if (!isFolderSet($id . "/parts/")) {
mkdir("uploads/" . $id );
mkdir("uploads/" . $id . "/parts");
}
//prepare params....
$org_img = 'uploads/' . $name . "/" . $id . (substr($type,0,1) != "." ? "." . $type : $type);
$dst_img = 'uploads/' . $id . "/parts/" . $nr . (substr($type,0,1) != "." ? "." . $type : $type);
$tmp_img = imagecreatetruecolor(200, 200);
if ($type == ".jpg" or $type == "jpeg") {
$src_img = imagecreatefromjpeg($org_img);
}
elseif ($type == ".png") {
$src_img = imagecreatefrompng($org_img);
}
elseif ($type == ".gif") {
$src_img = imagecreatefromgif($org_img);
}
else {
exit;
}
$sX = ($nr-1)%3 * 200; //// watch this question:
$sY = floor(($nr-1)/3) * 200; //// http://stackoverflow.com/questions/6325169/variable-has-unexpected-value
imagecopy($tmp_img, $src_img, 0,0, $sX, $sY, 200, 200);
if ($type == ".jpg" or $type == "jpeg") {
imagejpeg($tmp_img, $dst_img,100); // because of ini_set i dont get an error here
}
elseif ($type == ".png") {
imagepng($tmp_img, $dst_img, 0); //on these functions, I get the errors
}
else {
imagegif($tmp_img, $dst_img); //also here i get an error
}
imagedestroy($tmp_img);
}
There is not too much to work from but sometimes when you use a process like you are PHP changes the image header to JFIF (JPEG) instead of GIF98a (GIF) so run a check on the header before you use imagecreatefrom....
Hope this helps a little bit, maybe more code would help us all?