I have this code on my computer and it runs perfectly fine but when someone else tries to run it in a different environment, getimagesize() is returning false every time for some reason (should be returning true a lot). Any ideas why this snippet of code would run completely different in different environments?
$i = 2;
while ($i != 0){
$theFile = "url/to/images/" . $image . $i . ".GIF";
//echo $theFile . "<br />";
if ($imageSize = #getimagesize($theFile)){
//echo "added...<br />";
$theRow .= "<a href='" . $theFile . "' rel='lightbox[" . $image . "]'></a>";
$i++;
}else{
$i = 0;
}
}
If I uncomment out the two lines there all $theFile's print to the screen fine and they are all valid URLs but it's just a bunch of
thisimage2.GIF
thatimage2.GIF
anotherimage2.GIF
...
They all end with 2.GIF but there are many that should have 3, 4, 5, 6 all the way up to 12.GIF but it's never increasing $i because it never returns true with getimagesize(). Again, when I uncomment echo $theFile . "<br />"; it prints valid URLs to images that the other person can paste into a browser address bar and see the image just fine.
I'm running php 5.4.17 and the exact same code works fine for me. The other machine is running php 5.4.7 and it's not working correctly. I tried to look up any differences between the two versions for getimagesize() but couldn't find anything.
Edit: When run without the "#" on getimagesize() on the machine where it's not working it gives the following warning: Warning: getimagesize(): Unable to find the wrapper “https” - did you forget to enable it when you configured PHP?
There are a couple things wrong here. Fortunately, most of them are easy fixes.
$image doesn't appear to be defined anywhere, but maybe it has and you just didn't include it.
There's no text in between each opening and closing <a> tag, so the only thing you'd see would be links like this: <a href='url/to/images/imagename1.GIF' rel='lightbox[]'></a> (but again, maybe that's intentional).
$theRow doesn't appear to echoed anywhere, but maybe it is and you just didn't include that part. Further, it doesn't look like $theRow was initially defined anywhere either.
Your while() loop will only display the last image processed. In this case, I'd use a for() loop instead.
If your goal is to build up $theRow and then display it all at the end, I'd go with something like this instead:
<?php
// EDIT: check to see if openssl exists first, due to the https error you're receiving.
$extensions = get_loaded_extensions();
if (!in_array('openssl', $extensions)) {
echo 'OpenSSL extension not loaded in this environment';
}
// Define $theRow first
$theRow = '';
// "Given that $i = 0, while $i is less than 3, auto-increment $i"
for ($i = 0; $i < 3; $i++){
$theFile = "url/to/images/" . $image . $i . ".GIF";
//echo $theFile . "<br />";
// Remove the # sign to display errors if you want
if ($imageSize = #getimagesize($theFile)){
//echo "added...<br />";
// Add to $theRow, using $theFile as the text displayed in between each <a> tag
$theRow .= "<a href='" . $theFile . "' rel='lightbox[" . $image . "]'>" . $theFile . "</a>";
}
else {
//This should only appear if $imageSize didn't work.
echo '$imageSize has not been set for ' . $theFile . '<br />';
}
}
// Now that $theRow has been built, echo the whole thing
echo $theRow;
Related
I am trying to update the Path environment variable in Windows with a PHP script, but if I use putenv() it doesn't change. I can get the paths list in the Path variable but I am not able to update it.
Another problem is that if I use getenv('Path') to get the paths list, I have a unique string with all paths merged from the Path variable of User and of the Machine.
I'm wondering if there is a better way to do that, maybe acting directly in the registry key to update User Path variable.
UPDATE
I think I found out a half-solution, but it doesn't work as expected.
What do I want to do?
I just want to make a script that allow me to switch from a PHP version to another changing the Path variable.
I made the script, it seems to work and the Path variable is successfully updated, but even if I close and reopen the cmd prompt if I type php -v it doesn't seems to get the updated var. If I open the Environment Variables windows, then open the "Path" variable and click on Ok and Ok again, then the refresh is got but the cmd prompt.
This is very strange to me, and if I have to do this everytime, then script loose its benefit...
I recorded a video, I hope it explain the problem better than my English...
https://1drv.ms/v/s!Ao2s4w8xSxBSh7RY4y5pB8u1g_QFSQ
This is the code of the script:
// Load PHP available versions
$laragon_php_paths = 'D:\www-servers\laragon\bin\php';
$php_paths = scandir($laragon_php_paths);
$path_var_name = "Path";
// Backup before doing a disaster
$date = new DateTime();
exec('REG EXPORT HKCU\Environment BackupUserEnvironment_' . $date->format('YmdHisv') . '.reg');
// Load registry key of user's Path environment variable
exec('REG QUERY HKCU\Environment /v ' . $path_var_name, $output, $result);
$path = explode(' ', $output[2]);
$path_array = explode(';', $path[count($path) - 1]);
// Get the current PHP Version and get the key of the item of the PHP bin path
foreach ($path_array as $key => $path_item) {
if (strpos($path_item, $laragon_php_paths) !== false) {
$the_key = $key;
$current_php_version = substr($path_item, strrpos($path_item, '\\') + 1);
}
}
echo 'Available PHP versions:' . PHP_EOL . PHP_EOL;
$i = 0;
foreach ($php_paths as $dir) {
if ($dir === '.' || $dir === '..') continue;
echo ' [' . ++$i . '] ' . $dir;
if ($dir === $current_php_version) {
echo ' [Current version]';
}
echo PHP_EOL;
}
// Get file descriptor for stdin
echo PHP_EOL;
echo 'Select a PHP version: ';
$fd = fopen('php://stdin', 'r');
$choice = (int) fgets($fd);
echo PHP_EOL;
// Check if choice is between 1 and number of choices
if ($choice > 0 && $choice <= $i) {
// Change the original php version with the new one
$new_php_version = $php_paths[$choice + 1];
$path_array[$the_key] = $laragon_php_paths . '\\' . $new_php_version;
echo 'PHP version changed to: ' . $new_php_version . PHP_EOL;
} else {
echo 'No allowed choice, nothing changed.';
echo PHP_EOL;
}
// Escape some chars for cmd
$new_path_var = str_replace(['%', ' '], ['^%', '" "'], implode(';', $path_array));
$cmd = 'REG ADD HKCU\Environment /f /t REG_EXPAND_SZ /v ' . $path_var_name . ' /d ' . $new_path_var;
// Execute
exec($cmd);
i have this code to display images, where each user has his own, i'll comment it to save your time
<?php
session_start();
$name=$_SESSION['valid_user']; //saved current username in variable
$loc="./uploads/"; //location of image directory
$path=$loc.$name; //current user's folder to save his images
echo $path."<br>"; //i used this to make sure the path is ok, only for testing
if(is_dir($path)) //if directory exists, show it exists,otherwise show it
{ //doesnt exists
echo "<br>exists";
}
else
{
echo "<br>not exists";
}
$files = glob($path."/");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i]; //picture number
print $num."<br />";
echo '<img src="'.$path.'" alt="random image" height="100" width="100"/>'."<br /><br />";
} //shows the picture till the last one
?>
the output that i get is this this
./uploads/user_name
exists
but it does not show the images, even though the folder is not empty (upload script works fine).
EDIT; solved it (low rep, cant answer my own question).
got it. For anyone who cares, this line here
echo '<img src="' . $path . '/' . $files[$i] . '" <!-- etc --> />';
wasn't working because i added $files, which already contained the path, and it was giving input to img src as
/uploads/username/uploads/username
so that was two times the same path.Upon removing $path, and using just
<img src="' . $files[$i] . '"
did the trick. Thank you all for your help.
I think you need to pass a wildcard path to glob: glob($path . '/*'). You are also not printing the filename in the image source attribute:
echo '<img src="' . $path . '/' . $files[$i] . '" <!-- etc --> />';
Also, your $num is actually the filename, not the picture number - that is $i. You could really simplify that loop using the foreach construct:
foreach($files as $filename) {
// etc
}
you need to add a pattern for using glob afaik
$files = glob($path."/*.*"); // all files
$files = glob($path."/*.jpg"); // all jpgs etc.pp
foreach($files as $idx => $file)
{
$num = $idx+1; //idx starts with 0 so we add one here
print $num."<br />";
echo '<img src="'.$path.'/'.$file'" alt="random image" height="100" width="100"/>'."<br /><br />";
}
Hi I am trying to get images to load into a page using the file names from an array,
This is what I have so far
<?php
$i=0;
$img=array("1.png","2.png","3.png","4.png");
while ($i<count($img))
{
echo "<img class='loadin' alt='imgg' src=" . "'http://www/images/" . $img[i] . "'" . "/" . ">" . "<br/>";
$i++;
}
?>
It seems to ignore the file name and just enters:
http://www/images/
as the source and ignores the file name from the array
Any Help would be great Thanks
Mikey
You forgot the dollar sign with your $i variable: $img[$i]
EDIT:
(btw. using a foreach-loop would be easier...)
foreach($img AS $filename) {
echo "<img class='loadin' alt='imgg' src='http://www/images/" . $filename . "'/><br/>";
}
I'm trying to create a bit of code to first check the content of a directory to see if a file exists and if it does, append a number to the filename. Unfortunately I can't get it to work at the moment, the php produces no errors but a new file is not created if one already exists. Here is my code atm:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Check_Output = exec("ls " . $Output_Directory . " | grep -w " . $Scan_Name_Output);
$j = 1;
while (!empty($Check_Output))
{
$Scan_Name_Output = $Scan_Name_Output . $j;
$j++;
If I replace the while loop with an if statement, it works - so it's not the file paths or anything that are causing the problem. I've tried a fair few combinations but can't get it to work.
I have tried using file_exists() but it doesn't work - I think it's because I'm passing it variables that have been put through escapeshellarg(). As a result I think file_exists literally looks for /path/to/dir/'Report1.txt' - obviously 'Report1.txt' doesn't exist, Report1.txt does. This is why I was using exec and ls.
Thanks for any responses
PHP has some nice functions built in to handle files. You should think about using file_exists() for example.
$basename = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Scan_Name_Output = $basename;
$j = 1;
while (file_exists($Scan_Name_Output)){
$Scan_Name_Output = $basename . $j;
$j++;
}
$ourFileHandle = fopen($Scan_Name_Output, 'w') or die("can't open file");
Try this:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
if (file_exists($Scan_Name_Output))
{
rename($Scan_Name_Output, $Scan_Name_Output . "1");
}
I have strong reason to believe that both functions rename() and unlink() are asynchronous, which, from my understanding, means that when the functions are called, the code below them are continued before it finishes its procedures on the filesystem. This is a problem for the internet app I'll explain below, because later code depends on these changes to already be set in stone. So, is there a way to make both synchronous, so that the code reader freezes when it hits these functions, until all of its tasks are fully carried out on the filesystem?
Here is the code in delete-image.php, which is called by ajax from another admin-images.php(the latter will not be shown):
`
foreach ($dirScan as $key => $value) {
$fileParts = explode('.', $dirScan[$key]);
if (isset($fileParts[1])) {
if ((!($fileParts[1] == "gif") && !($fileParts[1] == "jpg")) && (!($fileParts[1] == "png") && !($fileParts[1] == "jpg"))) {
unset($dirScan[$key]);
}
} else {
unset($dirScan[$key]);
}
}
$dirScan = array_values($dirScan);
// for thumbnail
$file = 'galleries/' . $currentGal . '/' . $currentDir . "/" . $dirScan[$imageNum - 1];
unlink($file);
for ($i = ($imageNum - 1) + 1; $i < count($dirScan); $i++) {
$thisFile = 'galleries/' . $currentGal . '/' . $currentDir . '/' . $dirScan[$i];
$thisSplitFileName = explode('.', $dirScan[$i]);
$newName = 'galleries/' . $currentGal . '/' . $currentDir . "/" . ($thisSplitFileName[0] - 1) . "." . $thisSplitFileName[1];
rename($thisFile, $newName);
}
// for large image
$fileParts = explode('.', $dirScan[$imageNum - 1]);
$file = 'galleries/' . $currentGal . '/' . $currentDir . "/large/" . $fileParts[0] . "Large." . $fileParts[1];
unlink($file);
for ($i = ($imageNum - 1) + 1; $i < count($dirScan); $i++) {
$thisSplitFileName = explode('.', $dirScan[$i]);
$thisFile = 'galleries/' . $currentGal . '/' . $currentDir . '/large/' . $thisSplitFileName[0] . "Large." . $thisSplitFileName[1];
$newName = 'galleries/' . $currentGal . '/' . $currentDir . "/large/" . ($thisSplitFileName[0] - 1) . "Large." . $thisSplitFileName[1];
rename($thisFile, $newName);
}
sleep(1);
echo 'deleted ' . $dirScan[$imageNum - 1] . " successfully!";
} else {
echo "please set the post data";
} ?>`
After this script returns its completed text, admin-images.php triggers a new function which populates an image table from these renamed and trimmed files. Sometimes it displays old names and files that were suppose to be deleted, and a simple page refresh gets rid of them. This seems to suggest that the above php script is running through all the code and spitting out echoed text to the mainfile before it completes its file-system manipulation (All of this other code is long and complicated, and hopefully unnecessary for the discussion at hand).
You'll notice, I've tried a sleep() function to halt the php script to hopefully give it time to finish. This is an ineligent, and problematic way of doing things, because I have to put a large amount of time to insure it works every-time, but I don't want the user to wait longer than she / he has to.
Mind that file-systems often use caches to reduce the load. Normally you won't notice, but sometimes you need to clear the cache if you need to have the real information. Check the configuration of your file-system if your issue is file-system related.
PHP itself uses a cache as well for some file-operations, so clear that, too.
See clearstatcache to clear the PHP stat cache.
Take note that this is a "view" issue, the file is actually deleted on disk, but PHP might still return it's there (until you clear the cache).
I suppose they are not asynchronous, because they return a result telling if the operation was successful or not.
I believe the problem happens because when you run scandir after making the modifications, it may be using "cached" data, from memory, instead of re-scanning the file system.
rename() is not, but unlink() is asynchronous on Windows.
Because there seems to be no way of waiting for a pending delete to finish, this answer suggests to rename a file before deleting it. PHP does not seem to do that, so you can assume it's asynchronous.
To use any file operation you are required to use the $_SERVER["DOCUMENT_ROOT"] to make that work. In case you wont do it.. the real operation wont work properly. Also in case you are using the Linux Server then you will be required to set the permissions for the folders in which you want to perform the file operation.
And mind it both the operations are synchronous they are not asynchronous. It also depends on the type of the server or the OS that you are using.