Check if background image is set - php

I'm working on a simple script - file input which will change the site's background to the given image. It works, but my problem starts when I refresh site - the background image disappears.
I was wondering how to set and check if the background was set, so it will be there as long since next file input ?
I was trying to do that with a constant but does not work, here is my code:
if (isset($_POST['submit_bgImg'])) {
$myTarget = 'img/' . basename($_FILES['bg_img']['name']);
if (move_uploaded_file($_FILES['bg_img']['tmp_name'], $myTarget)) {
print('<style> body {background-image:url(img/' . $myFile . ');}</style>');
define('MY_BG', $_FILES['bg_img']['name']);
}
}
if (defined('MY_BG')) {
print('<style> body {background-image:url(img/' . MY_BG . ');}</style>');
}
any help ?

If you want to keep it only for the user you must store MY_BG variable in Session or Cookies like :$_SESSION['my_bg'] = $_FILES['bg_img']['name'];
if you want to keep it forever you must store it on a file or a Database like MySQL
$conn = new MySQLi('host','user','password','database name');
$conn->query("INSERT INTO table VALUES ('" . $bg_name . "')");

Try out with echo in php instead of print.I recommended to you can use ajax.
if (isset($_POST['submit_bgImg'])) {
$myTarget = 'img/' . basename($_FILES['bg_img']['name']);
if (move_uploaded_file($_FILES['bg_img']['tmp_name'], $myTarget)) {
echo "<style> body {background-image:url(img/' . $myFile . ');}</style>";
define('MY_BG', $_FILES['bg_img']['name']);
}
}
if (defined('MY_BG')) {
echo "<style> body {background-image:url(img/' . MY_BG . ');}</style>";
}

Related

PHP not loading inline

I have a php file with the following code which is run inside a switch statement:
switch($valueFoo) {
case 'bar':
echo "<select id=\"selTheme\">";
$path = './files/css/themes/';
$files = array_values(array_diff(scandir($path), array('.', '..')));
for ($i = 0; $i < count($files); $i++) {
$cVal = substr($files[$i], 0, -4);
$cTitle = ucwords(substr($files[$i], 0, -4));
if ($cTitle==$_SESSION['setTheme']) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\" selected>" . $cTitle . "</option>";
} elseif ($i>=count($files)) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option></select>";
} else {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option>";
}
}
echo "...";
This is intended to create a list of options from a folder on my server. And it does indeed work. The problem is that it ONLY works AFTER the page is refreshed. I have been banging my head on my table trying to figure out why it does this only after the page is refreshed. I have no clue. I want the element to be filled with options as soon as it loads on page. I don't want the page to reload at all. It works by itself to populate an unordered list but I want it to be selectable options.
I don't see anything wrong with the code at all. I don't understand why the options list aren't being populated without a reloading of the page. I don't understand why it fills in perfectly when the page reloads. I would think that if it would do it properly AFTER the reload, it would do it just fine the first time it loads! Why isn't?
Please help me understand.
EDIT: This code comes as a return from an AJAX call. I am trying to run the for loop from that AJAX call. The loop doesn't run until the page reloads. Is there a way to force the AJAX call without the page load?
if you want a dynamic display of the folders content you'll have to use Ajax.
make sure that the session is already created and you're using 'session_start()' in the beginning of all your pages,
clarify your question/code to get precise answers

Variable for file directory path not being recognized

so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!
try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..

Smarty Variable Declaration Error

I have the PHP code:
$uid = $xUS['id']; // Current user id
$uname = $xUS['x_username']; // Current user name
$ulink = ''; // Current user profile URL (leave blank for none)
$upic = $xUS['config_forum_avator_head']; // Current user
$ismod = 0; // Is current user a moderator?
$sig = md5($uid . $uname . $ismod . 's79tvi40k95bs6mw');
$ssoParams = '&uid=' . $uid . "&uname=" .
urlencode($uname) . "&ulink=" . urlencode($ulink) . "&upic=" . urlencode($upic)
. "&ismod=" . $ismod . "&sig=" . $sig;</i>
My Smarty template file:
<iframe width='550' height='500' src='http://chatroll.com/embed/chat/pibux-chatroom?id=tgybumotNmY&platform=php{$ssoParams}&w=$0' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' allowtransparency='true'></iframe>
In this, the {$ssoParams} variable is returning a null value. Why? Please help out.
Read Smarty docs for example: http://www.smarty.net/docsv2/en/language.variables.tpl#language.assigned.variables
You need to assign a variable like:
$smarty = new Smarty();
$smarty->assign('ssoParams', $ssoParams); // assign(smarty var, PHP var);
$smarty->display('template_file.tpl');
And of course you need to include smarty files, define templates etc.
For basic working example look example 2.9. here:
http://www.smarty.net/docsv2/en/installing.smarty.basic.tpl#id2778275

PHP variable-infused link not writing to a variable?

http://www.reecemcmillin.com/albums/
<?php
$uncut = file_get_contents('http://www.google.com/#sclient=psy-ab&hl=en&safe=active&source=hp&q=' . $_POST['band'] . '+' . $_POST['album'] . '+zip+inurl:mediafire');
$strip1 = strstr($uncut, 'www.mediafire.com/?');
$link = substr($strip1, 0, 30);
echo $link;
?>
It doesn't seem to be writing the website content to $uncut. Can somebody help me figure out what's wrong? Thanks.<3
Clients are not supposed to send URI-fragments (the portion of the URI following #) to servers when they retrieve a document. PHP is probably sending a request for the google homepage, effectively: file_get_contents('http://www.google.com/');. If you echo $uncut, that's probably what you'll see you're getting back.
Try a querystring-based URI instead.
<?php
$uncut = file_get_contents('http://www.google.com/search?sclient=psy-ab&hl=en&safe=active&source=hp&q=' . urlencode($_POST['band']) . '+' . urlencode($_POST['album']) . '+zip+inurl:mediafire');

Hide Div if no image in the loop

Im looking to create a condition in wordpress loop. if no image then image box (.thumbHome{display:none})
this is in my function.php
function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
if($arrImages) {
$arrKeys = array_keys($arrImages);
$iNum = $arrKeys[0];
$sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
$sImgString = '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}
And my javascript:
window.onload = noImage();
function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}
I tried:
window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
}
RESULT: class hide added to all loop
I cant figure it another way, since im still new in coding.
thx
Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.
Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.
In your main loop, add an unique id to each .thumbHome div based on the image id. So like:
echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent
Then your else conditional (for whether there's a thumbnail) could be changed to:
else {
echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}
and your js function could be:
function noImage(var){
$(var).hide();
}
This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.

Categories