Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys,

I would like to ask you how I can upload an image and then pass its path to the CSS file. I created a style.php file and it's working
PHP
<?php 


header('Content-type: text/css');

$bg = array('http://placehold.it/320x320', 'http://placehold.it/350x350', 'http://placehold.it/300x300'); 

  $i = rand(0, count($bg)-1);
  $selectedBg = "$bg[$i]"; 


 ?>


CSS
body{
 	background: url(<?php echo $selectedBg; ?>);
 }


But I do not know how to add another element to the array from another page. For example I would like to have an upload button so I can change the background later.
Posted
Updated 25-Mar-15 0:55am
v2
Comments
Member 10314038 27-Mar-15 6:45am    
Thank you for the replies. My goal is to let the administrator change the background image when he uploads a new image. I think I can do it by giving a name to the background image (e.g. bg-image.jpg) in the CSS file and when the new image is being uploaded it will be automatically renamed to bg-image.jpg. I hope it will work.

To upload and save files to server, refer to this: http://www.w3schools.com/php/php_file_upload.asp[^]
Always store the upload images in the same folder say "bg-images".
In the php script for changing the background image (your code shown), do not hard code the $bg array, instead scan the image folder to update the $bg array like this:
PHP
$dir = 'bg-images/';
// capture the image files in an array
$bg = glob($dir . '*.jpg');

http://php.net/manual/en/function.glob.php[^]
 
Share this answer
 
An alternative method would be to use a style sheet (.css file) for containing your image.

When you upload the image, using it's full path location, open, write, and close the style sheet. This would then take affect when the page was refreshed (as would solution 1).

For that matter, you could regenerate the entire webpage, with the new image embedded.

I wouldn't do the image with php: You can update without a refresh if, instead, you use javaScript, but you did specify php.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900