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?
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 eliminate directories from a statement and I can't seem to get rid of the . or .. directories while using PHP.
$album_num = $_POST['album_num'];
$album_directory = "../../galleries";
$albums = array_reverse(scandir($album_directory));
$album = $albums[$album_num];
if($album) {
if($album !== "." || $album !== "..") { //This line here
$image = glob($album_directory . "/" . $album . "/*.jpg");
$image = explode("/", $image[0]);
$image = end($image);
echo $album . ":" . $image;
}
} else {
echo "halt";
}
The line that has if($album !== "." || $album !== "..") does not seem to be working. Do I need to escape the dots?
Am I able to just delete them from the array to begin with?
Try this:
if($album) {
if($album !== "." && $album !== "..") { //This line here
$image = glob($album_directory . "/" . $album . "/*.jpg");
$image = explode("/", $image[0]);
$image = end($image);
echo $album . ":" . $image;
}
}
Change your if condition from || to &&
Use != instead of !==
I suppose u don't want that album evaluate to !==
$album_num = $_POST['album_num'];
$album_directory = "../../galleries";
$albums = array_reverse(scandir($album_directory));
$album = $albums[$album_num];
if($album) {
if($album != "." || $album != "..") { //This line here
$image = glob($album_directory . "/" . $album . "/*.jpg");
$image = explode("/", $image[0]);
$image = end($image);
echo $album . ":" . $image;
}
} else {
echo "halt";
}
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!!
Huh, this is my first serious web project and for that moment i've got simply big enigma.
The deal is to get previous and next file extension using its first letters, for instance:
there's file 04.jpeg 05.gif 06.tiff we're currently reading 05.gif so we remove extension
and now its '05' so we add one so we get '06' and HOW TO GET THAT FILE EXTENSION?!?!?!
Details:
The problem is that i need to fix my image browser which works in two modes:
Comics browser
[comics in folder looks like:
page00.extension
page01.extension
(...)
page09.extension
page10.extension
page11.extension
]
Single files browser
[single files in folder looks like:
01.extension
02.extension
03.extension
(...)
09.extension
10.extension
11.extension
]
[extension maybe jpg,jpeg,gif,png etc.]
Im getting current $extension and file name using $_GET var.
Here is some code - im working with bootstrap 3 framework:
Also im sorry that there's no comments but this isn't really complicated as it looks like
<?php
if($type == 2) {
$number = substr($clean, 4);
$nextnum = $number + 1;
$prevnum = $number - 1;
$prevpath = HOW TO GET IT WITH EXTENSION??
$nextpath = HOW TO GET IT WITH EXTENSION??
$nextext = '.' . substr(strrchr($prevpath,'.'),1);
$prevext = '.' . substr(strrchr($nextpath,'.'),1);
if ($nextnum >= 10) {
$next = 'page' . $nextnum . $nextext;
} else {
$next = 'page0' . $nextnum . $nextext; }
if ($prevnum >= 10) {
$prev = 'page' . $prevnum . $prevext;
} else {
$prev = 'page0' . $prevnum . $prevext; }
if ($clean === "page00") {
$prev = 'page00' . $extension; }
$count = 'page' . $x;
if ($clean === $count) {
$next = $count . $extension; }
} elseif($type == 3) {
$nextnum = $clean + 1;
$prevnum = $clean - 1;
$prevpath = HOW TO GET IT WITH EXTENSION?? <====== MY PROBLEM
$nextpath = HOW TO GET IT WITH EXTENSION?? <====== MY PROBLEM
$nextext = '.' . substr(strrchr($prevpath,'.'),1);
$prevext = '.' . substr(strrchr($nextpath,'.'),1);
if ($nextnum >= 10) {
$next = $nextnum . $nextext;
$prev = $prevnum . $prevext;
} else {
$next = '0' . $nextnum . $nextext;
$prev = '0' . $prevnum . $prevext; }
if ($clean === "01") {
$prev = '01' . $extension; }
if ($clean === $x) {
$next = $x . $extension; } }
echo '<br />
<div class="btn-group btn-group-justified">
<a class="btn btn-default" href="?browse=' . $prev . '" role="button">Poprzedni</a>
<a class="btn btn-default" href="' . $goback . '" role="button">Wyjdź</a>
<a class="btn btn-default" href="?browse=' . $next . '" role="button">Następny</a>
</div>';
?>
function get_next_file($file){
$maxdigits = 2; // assuming the file always ends with two digits
$dir = dirname($file) . DIRECTORY_SEPARATOR;
$fname = pathinfo($file, PATHINFO_FILENAME);
$name = substr($fname, 0, -$maxdigits);
$digits = substr($fname, -$maxdigits) + 1;
foreach(array('bmp', 'png', 'jpg', 'gif') as $ext){
$test = $dir . $name . str_pad($digits, $maxdigits, '0', STR_PAD_LEFT) . '.' . $ext;
if(file_exists($ext))return $ext;
}
return false; // no such file...
}
The complete function would look like the one above (not tested!). You would call it like so:
Assuming we have these files:
test01.png
test02.gif
test05.bmp
You get these results:
get_next_file('test01.png') => 'test02.gif'
get_next_file('test02.gif') => false // 'coz the other file is not consecutive
get_next_file('test05.bmp') => false // no other files to look for...
If you know the name of current file then you can search for files in a directory using glob:
if (is_array(glob('05.*'))) { /* do some stuff */ }
Else you can create a whilte-list of extensions and use file_exists:
foreach (array('jpg', 'jpeg', 'png') as $ext)
if (file_exists('05.'. $ext)) { /* do some stuff */ }