Random page background: Halloween edition

ASP.NET, PHP, PHP Code Generator, PHP Form Generator, Tutorials

Happy Halloween everyone!

Just a little Halloween fun project. To make your website more interesting you can choose to display a random background image for each visitor. Here is how it’s going to look:

How to add this functionality to your project.

1. Download a set of sample images and unzip it to the output folder keeping directory structure. This should create a folder named backgrounds with a few images in there. You are free to add more images or to remove any you don’t need.

2. In PHPRunner proceed to Visual Editor, open Header file, switch to HTML mode and paste the following code there.

<?php
if (!$_SESSION["background"]) {
	$arr = array_diff(scandir("backgrounds"), array('..', '.'));
	$key = array_rand($arr);
	$_SESSION["background"]=$arr[$key];
}
echo('
<style type="text/css">
body {
height:100%;
background: transparent url("backgrounds/'.$_SESSION["background"].'") no-repeat center center fixed;
background-size:cover;
}
</style>');
?>

3. And here is the relevant code for ASPRunner.NET

For this code to work you need to run the latest ASPRunner.NET build. Paste it to header file in Visual Editor (HTML mode). Images also need to reside in ‘bacgrounds’ folder. For those who is interested header file is .cshtml. More info here.

@{ 
var file="";
if (!XSession.Session["file"]) {
	var rand = new Random();  
	var files =  Directory.GetFiles(Server.MapPath(webRootPath+"/backgrounds"),"*.*");  
	file = files[rand.Next(files.Length)];  
	file = Path.GetFileName(file);  
	XSession.Session["file"]=file;
}
else {
	file=XSession.Session["file"];
}

var url=@Href("~/backgrounds/"+file);

var text = String.Format("body {{ height:100%; background: transparent url({0}) no-repeat center center fixed; background-size:cover; }}", url);

@(Html.Raw(""));
}

7 thoughts on “Random page background: Halloween edition

  1. i would like to use this on ASP, can you please post the code for it? it will be nice to have the background change every time my client login.
    great work!!!
    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *