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 */ }
Related
How to make directory within directory by php loop?
Example: http://site_name/a/b/c/d
First create a then b within a then c within b then ....
Problem is here a,b,c,d all the folders created in root directory not one within one.
Here is my code -
<?php
$url = "http://site_name/a/b/c/d";
$details1 = parse_url(dirname($url));
$base_url = $details1['scheme'] . "//" . $details1['host'] . "/";
if ($details1['host'] == 'localhost') {
$path_init = 2;
}else {
$path_init = 1;
}
$paths = explode("/", $details1['path']);
for ($i = $path_init; $i < count($paths); $i++) {
$new_dir = '';
$base_url = $base_url . $paths[$i] . "/";
$new_dir = $base_url;
if (FALSE === ($new_dir = folder_exist($paths[$i]))) {
umask(0777);
mkdir($new_dir . $paths[$i], 0777, TRUE);
}
}
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
?>
please check this code. it will create nested folder if not exit
<?php
$your_path = "Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$array_folder = explode('/', $your_path);
$mkyourfolder = "";
foreach ($array_folder as $folder) {
$mkyourfolder = $mkyourfolder . $folder . "/";
if (!is_dir($mkyourfolder)) {
mkdir($mkyourfolder, 0777);
}
}
hope it will help you
You can actually create nested folders with the mkdir PHP function
mkdir($path, 0777, true); // the true value here = recursively
Dear friends the following answer is tested and used in my script -
<?php
$url = "http://localhost/Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$details = parse_url(dirname($url));
//$base_url = $details['scheme'] . "//" . $details['host'] . "/";
$paths = explode("/", $details['path']);
$full_dir = '';
$init = ($details['host'] == 'localhost') ? '2' : '1';
for ($i = $init; $i < count($paths); $i++) {
$full_dir = $full_dir . $paths[$i] . "/";
if (!is_dir($full_dir)) {
mkdir($full_dir, 0777);
}
}
?>
I have form :
<form method="post" enctype="multipart/form-data" action="edit_kategori.php">
<input type="file" name="icon-main" id="icon-main">
<input type="file" name="icon-hover" id="icon-hover">
<form>
I want to upload two images from two input files, but only the last one file I have choosen that uploaded. and here is my php:
$dirMain = $_FILES['icon-main']['tmp_name'];
$dirHover = $_FILES['icon-hover']['tmp_name'];
//main icon
$tempMain = explode(".", $_FILES['icon-main']['name']);
$newMain = round(microtime(true)) . '.' . end($tempMain);
$iconMain = $folder . basename($newMain);
//hover icon
$tempHover = explode(".", $_FILES['icon-hover']['name']);
$newHover = round(microtime(true)) . '.' . end($tempHover);
$iconHover = $folder . basename($newHover);
if (!empty($dirMain)&&!empty($dirHover)) {
$dir[] = $dirMain;
$dir[] = $dirHover;
$icon[] = $iconMain;
$icon[] = $iconHover;
for ($i=0; $i <= 1; $i++) {
move_uploaded_file($dir[$i] , $icon[$i]);
}
}
Is that because "tmp_name" can only store one file ? Thanks for helping :)
Just small mistake, loop through <= 1
for ($i=0; $i <= 1; $i++) {
move_uploaded_file($dir[$i] , $icon[$i]);
}
I guess storing $_FILES['yourvar']['tmp_name'] is causing issue. I have tried this both ways and it might useful to you the difference:
Method 1: (working)
move_uploaded_file($_FILES['icon-main']['tmp_name'], $_FILES['icon-main']['name']);
move_uploaded_file($_FILES['icon-hover']['tmp_name'], $_FILES['icon-hover']['name']);
Method 2: (not working)
$d = $_FILES['icon-main']['tmp_name'];
$k = $_FILES['icon-hover']['tmp_name'];
move_uploaded_file($d, $_FILES['icon-main']['name']);
move_uploaded_file($k, $_FILES['icon-hover']['name']);
I just find the way, I move file manualy using if, not looping...
$target = "../category/";
$dir = $target . basename( $_FILES['icon-main']['name']);
if(move_uploaded_file($_FILES['icon-main']['tmp_name'], $dir)) {
echo "<br>";
echo $dir;
} else {
echo "Fail";
};
$dir = $target . basename( $_FILES['icon-hover']['name']);
if(move_uploaded_file($_FILES['icon-hover']['tmp_name'], $dir)) {
echo "<br>";
echo $dir;
} else {
echo "Fail";
};
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!!
I've a simple problem of copying a a php folder to some directories, bu the problem is I can't the solution for that, the idea is that I've an Online Manga Viewer script, and what I want to do is I want to add comments page to every chapter, the I dea that I came with, is, I create a separate comments page file and once a new chapter added the the comments file will be copied to the folder of the chapter :
Description Image:
http://i.stack.imgur.com/4wYE0.png
What I to know is how can I do it knowing that I will use Disqus commenting System.
Functions used in the script:
function omv_get_mangas() {
$mangas = array();
$dirname = "mangas/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$mangas[] = $file;
}
}
#closedir($dir);
}
sort($mangas);
return $mangas;
}
function omv_get_chapters($manga) {
global $omv_chapters_sorting;
$chapters = array();
$chapters_id = array();
$dirname = "mangas/$manga/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$chapter = array();
$chapter["folder"] = $file;
$pos = strpos($file, '-');
if ($pos === false) {
$chapter["number"] = $file;
} else {
$chapter["number"] = trim(substr($file, 0, $pos - 1));
$chapter["title"] = trim(substr($file, $pos + 1));
}
$chapters_id[] = $chapter["number"];
$chapters[] = $chapter;
}
}
#closedir($dir);
}
array_multisort($chapters_id, $omv_chapters_sorting, $chapters);
return $chapters;
}
function omv_get_chapter_index($chapters, $chapter_number) {
$i = 0;
while (($i < count($chapters)) && ($chapters[$i]["number"] != $chapter_number)) $i++;
return ($i < count($chapters)) ? $i : -1;
}
function omv_get_pages($manga, $chapter) {
global $omv_img_types;
$pages = array();
$dirname = "mangas/$manga/$chapter/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (!is_dir($dirname . $file . '/')) {
$file_extension = strtolower(substr($file, strrpos($file, ".") + 1));
if (in_array($file_extension, $omv_img_types)) {
$pages[] = $file;
}
}
}
#closedir($dir);
}
sort($pages);
return $pages;
}
/*function add_chapter_comment($dirname){
$filename = $dirname.'comments.php';
if (file_exists($filename)) {
} else {
copy('comments.php', .$dirname.'comments.php');
}
}*/
function omv_get_previous_page($manga_e, $chapter_number_e, $current_page, $previous_chapter) {
if ($current_page > 1) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page - 1);
} else if ($previous_chapter) {
$pages = omv_get_pages(omv_decode($manga_e), $previous_chapter["folder"]);
return $manga_e . '/' . omv_encode($previous_chapter["number"]) . '/' . count($pages);
} else {
return null;
}
}
function omv_get_next_page($manga_e, $chapter_number_e, $current_page, $nb_pages, $next_chapter) {
if ($current_page < $nb_pages) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page + 1);
} else if ($next_chapter) {
return $manga_e . '/' . omv_encode($next_chapter["number"]);
} else {
return null;
}
}
function omv_get_image_size($img) {
global $omv_img_resize, $omv_preferred_width;
$size = array();
$imginfo = getimagesize($img);
$size["width"] = intval($imginfo[0]);
$size["height"] = intval($imginfo[1]);
if ($omv_img_resize) {
if ($size["width"] > $omv_preferred_width) {
$size["height"] = intval($size["height"] * ($omv_preferred_width / $size["width"]));
$size["width"] = $omv_preferred_width;
}
}
return $size;
}
And thanks for all of you!
Include the following line in all of your pages in a small php statement, if it covers two folder paths, use this. Which I think in your case it does.
<?php
include('../../header.php');
?>
And then save this in the main root directory. Which in your diagram is called "Main Folder"
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?