I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.
Related
I adopted code from https://stackoverflow.com/a/44553006/8719001
but can't figure out why when uploading the same file "test.jpg" several times it only counts up once, creating "test-1.jpg" but not more ie. test-2.jpg, test-3.jpg.
Can anybody spot the issue and help please?
$keepFilesSeperator = "-";
$keepFilesNumberStart = 1;
if (isset($_FILES['upload'])) {
// Be careful about all the data that it's sent!!!
// Check that the user is authenticated, that the file isn't too big,
// that it matches the kind of allowed resources...
$name = $_FILES['upload']['name'];
//If overwriteFiles is true, files will be overwritten automatically.
if(!$overwriteFiles)
{
$ext = ".".pathinfo($name, PATHINFO_EXTENSION);
// Check if file exists, if it does loop through numbers until it doesn't.
// reassign name at the end, if it does exist.
if(file_exists($basePath.$name))
{
$operator = $keepFilesNumberStart;
//loop until file does not exist, every loop changes the operator to a different value.
while(file_exists($basePath.$name.$keepFilesSeperator.$operator))
{
$operator++;
}
$name = rtrim($name, $ext).$keepFilesSeperator.$operator.$ext;
}
}
move_uploaded_file($_FILES["upload"]["tmp_name"], $basePath . $name);
}
your while loop condition has a problem
while( file_exists( $basePath.$name.$keepFilesSeperator.$operator ) )
the $name variable still contains the full name of file, in this case test.jpg, you're testing a value like /home/test.jpg-1 so finally the while loop is never executed as the file test.jpg-1 never exists, that's why you always get the test-1.jpg on disk and not a ...-2.jpg or ...-3.jpg
I have to write a script that checks the progress of a file transfer that a background batch is doing. I know the number of files that the folder need to have to have the "complete" status. I'm trying the following in a background PHP:
$id = $_GET['id'];
$qtd = $_GET['qtd'];
checkProgress($id, $qtd);
function checkProgress($qtd, $id) {
$dirWav = "D:\\path\\to\\wav\\".$id."\\";
$dirMP3 = "D:\\path\\to\\mp3\\".$id."\\";
$progWav = array_diff( scandir($dirWav), array(".", "..") );
$progMP3 = array_diff( scandir($dirMP3), array(".", "..") );
$numWav = count($progWav);
$numMP3 = count($progMP3);
if ($numMP3 < $qtd OR $numWav < $qtd) {
sleep(5);
checkProgress($qtd, $id); //Here i'm trying to do it in a recursive way
} else {
//End script, record to the DB
}
}
I'm sure that the folder beign checked are empty on start, and that the batch is running flawless. But at the start of the script, it automatically goes to the end (I used a mkdir to check it in a lazy way).
How can I achieve what I want? I cannot check it via cronjob or something like that.
This is Powershell but I'd guess the overall function would apply to a batch file. Take input as two paths, run a FOR loop to count the files and compare. See here for counting files in a FOR loop.
Function Count-Folders{
Param
(
[parameter(Mandatory=$true,Position=1)][string]$source,
[parameter(Mandatory=$true,Position=2)][string]$dest
)
$path = #(gci -Path $source -dir)
$path2 = #(gci -Path $dest -dir)
If($path.Length -eq $path2.Length){
"Matches"
} Else{
"input folder counts do not match, check again!!!"
}
I want to rotate an uploaded and retrieved image from one location. Yes i am almost done. But the problem is, due to header("content-type: image/jpeg") the page redirected to another/or image format. I want to display it in same page as original image in. Here my code..
$imgnames="upload/".$_SESSION["img"];
header("content-type: image/jpeg");
$source=imagecreatefromjpeg($imgnames);
$rotate=imagerotate($source,$degree,0);
imagejpeg($rotate);
i also did with css property.
echo "<img src='$imgnames' style='image-orientation:".$degree."deg;' />";
But anyway my task is to done only with php. Please guide me, or give any reference you have
thanks advance.
<?php
// Okay, so in your upload page
$imgName = "upload/".$_SESSION["img"];
$source=imagecreatefromjpeg($imgName);
$rotate=imagerotate($source, $degree,0);
// you generate a PHP uniqid,
$uniqid = uniqid();
// and use it to store the image
$rotImage = "upload/".$uniqid.".jpg";
// using imagejpeg to save to a file;
imagejpeg($rotate, $rotImage, $quality = 75);
// then just output a html containing ` <img src="UniqueId.000.jpg" />`
// and another img tag with the other file.
print <<<IMAGES
<img src="$imgName" />
<img src="$rotName" />
IMAGES;
// The browser will do the rest.
?>
UPDATE
Actually, while uniqid() usually works, we want to use uniqid() to create a file. That's a specialized usage for which there exists a better function, tempnam().
Yet, tempnam() does not allow a custom extension to be specified, and many browsers would balk at downloading a JPEG file called "foo" instead of "foo.jpg".
To be more sure that there will not be two identical unique names we can use
$uniqid = uniqid('', true);
adding the "true" parameter to have a longer name with more entropy.
Otherwise we need a more flexible function that will check if a unique name already exists and, if so, generate another: instead of
$uniqid = uniqid();
$rotImage = "upload/".$uniqid.".jpg";
we use
$rotImage = uniqueFile("upload/*.jpg");
where uniqueFile() is
function uniqueFile($template, $more = false) {
for ($retries = 0; $retries < 3; $retries++) {
$testfile = preg_replace_callback(
'#\\*#', // replace asterisks
function() use($more) {
return uniqid('', $more); // with unique strings
},
$template // throughout the template
);
if (file_exists($testfile)) {
continue;
}
// We don't want to return a filename if it has few chances of being usable
if (!is_writeable($dir = dirname($testfile))) {
trigger_error("Cannot create unique files in {$dir}", E_USER_ERROR);
}
return $testfile;
}
// If it doesn't work after three retries, something is seriously broken.
trigger_error("Cannot create unique file {$template}", E_USER_ERROR);
}
You need to generate the image separately - something like <img src="path/to/image.php?id=123">. Trying to use it as a variable like that isn't going to work.
I haven't seen this asked yet, so if it is, can someone re-direct me?
I'm having an issue creating a full screen background for my WordPress theme that uses random images from the image library. I want to write a PHP function that can be used on multiple sites, so I can't simply use the direct path in the code. It also needs to work on MultiSite in such a way that it only pulls images that are uploaded to that site. Here's the code I'm working with:
HTML for my Background Div
<div id="background" class="background" style="background-image:url(<?php displayBackground();?>);">
</div>
PHP to randomize my image folder
<? php
function displayBackground()
{
$uploads = wp_upload_dir();
$img_dir = ( $uploads['baseurl'] . $uploads['subdir'] );
$cnt = 0;
$bgArray= array();
/*if we can load the directory*/
if ($handle = opendir($img_dir)) {
/* Loop through the directory here */
while (false !== ($entry = readdir($handle))) {
$pathToFile = $img_dir.$entry;
if(is_file($pathToFile)) //if the files exists
{
//make sure the file is an image...there might be a better way to do this
if(getimagesize($pathToFile)!=FALSE)
{
//add it to the array
$bgArray[$cnt]= $pathToFile;
$cnt = $cnt+1;
}
}
}
//create a random number, then use the image whos key matches the number
$myRand = rand(0,($cnt-1));
$val = $bgArray[$myRand];
}
closedir($handle);
echo('"'.$val.'"');
}
I know that my CSS markup is correct because if I give the DIV a fixed image location, I get a fullscreen image. Can anyone tell me what to do to fix it?
I'm trying to get a webpage to show images but it doesn't seem to be working.
here's the code:
<?php
$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" alt="random image">'." ";
}
?>
If the code should work, where do i put it?
If not, is there a better way to do this?
You'd need to put this code in a directory that contains a directory named "images". The directory named "images" also needs to have files in a *.* name format. There are definitely better ways to do what you're trying to do. Such would be using a database that contains all the images that you want to display.
If that doesn't suit what you want to do, you'd have to be much more descriptive. I have no idea what you want to do and all I'm getting from the code you showed us is to render every file in a directory called "images" as an image.
However, if this point of this post was to simply ask "How do I execute PHP?", please do some searching and never bother us with a question like that.
Another thing #zerkms noticed was that your for .. loop starts at iteration 1 ($i = 1). This means that a result in the array will be skipped over.
for ($i = 0; $i < count($files); $i++) {
This code snippet iterates over the files in the directory images/ and echos their filenames wrapped in <img> tags. Wouldn't you put it where you want the images?
This would go into a PHP file (images.php for example) in the parent directory of the images folder you are listing the images from. You can also simplify your loop (and correct it, since array indexes should start at 0, not 1) by using the following syntax:
<?php
foreach (glob("images/*.*") as $file){
echo '<img src="'.$file.'" alt="random image"> ';
}
?>
/**
* Lists images in any folder as long as it's inside your $_SERVER["DOCUMENT_ROOT"].
* If it's outside, it's not accessible.
* Returns false and warning or array() like this:
*
* <code>
* array('/relative/image/path' => '/absolute/image/path');
* </code>
*
* #param string $Path
* #return array/bool
*/
function ListImageAnywhere($Path){
// $Path must be a string.
if(!is_string($Path) or !strlen($Path = trim($Path))){
trigger_error('$Path must be a non-empty trimmed string.', E_USER_WARNING);
return false;
}
// If $Path is file but not folder, get the dirname().
if(is_file($Path) and !is_dir($Path)){
$Path = dirname($Path);
}
// $Path must be a folder.
if(!is_dir($Path)){
trigger_error('$Path folder does not exist.', E_USER_WARNING);
return false;
}
// Get the Real path to make sure they are Parent and Child.
$Path = realpath($Path);
$DocumentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// $Path must be inside $DocumentRoot to make your images accessible.
if(strpos($Path, $DocumentRoot) !== 0){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// Get the Relative URI of the $Path base like: /image
$RelativePath = substr($Path, strlen($DocumentRoot));
if(empty($RelativePath)){
// If empty $DocumentRoot === $Path so / will suffice
$RelativePath = DIRECTORY_SEPARATOR;
}
// Make sure path starts with / to avoid partial comparison of non-suffixed folder names
if($RelativePath{0} != DIRECTORY_SEPARATOR){
trigger_error('$Path folder does not reside in $_SERVER["DOCUMENT_ROOT"].', E_USER_WARNING);
return false;
}
// replace \ with / in relative URI (Windows)
$RelativePath = str_replace('\\', '/', $RelativePath);
// List files in folder
$Files = glob($Path . DIRECTORY_SEPARATOR . '*.*');
// Keep images (change as you wish)
$Files = preg_grep('~\\.(jpe?g|png|gif)$~i', $Files);
// Make sure these are files and not folders named like images
$Files = array_filter($Files, 'is_file');
// No images found?!
if(empty($Files)){
return array(); // Empty array() is still a success
}
// Prepare images container
$Images = array();
// Loop paths and build Relative URIs
foreach($Files as $File){
$Images[$RelativePath.'/'.basename($File)] = $File;
}
// Done :)
return $Images; // Easy-peasy, general solution!
}
// SAMPLE CODE COMES HERE
// If we have images...
if($Images = ListImageAnywhere(__FILE__)){ // <- works with __DIR__ or __FILE__
// ... loop them...
foreach($Images as $Relative => $Absolute){
// ... and print IMG tags.
echo '<img src="', $Relative, '" >', PHP_EOL;
}
}elseif($Images === false){
// Error
}else{
// No error but no images
}
Try this on for size. Comments are self explanatory.