I'm currently working on a login portal.
I already set the log in and log out functions and placed a session start button on every page.
My problem now is that I would like to update the user image based on the identity of who is logged in.
I'm using a template my boss chose, and this is the code where the image is:
<span>
<img src="../../global/portraits/5.jpg" alt="...">
</span>
Just a simple <img> tag with the link where the image is.
My project is in an html file with php implemented, and I tried to do this in the <span> tag, instead of <img>:
<?php
$W = ["Raffaella", "Milena", "Domiziana"];
$M = ["Umberto", "Domenico"];
if ($_SESSION["nome"] == $W) {
echo '<img src="W.jpg">';
} else if ($_SESSION["nome"] == $M){
echo '<img src="M.jpg">';
}
?>
where $_SESSION["nome"] represents the current user logged in. However, it doesn't do anything, not even producing an error.
Can someone explain how I can do it correctly, please? I'm new to php and trying to understand by studying alone on the internet
I was also considering JavaScript for this work (instead of PHP), but I don't know where to start
It looks like both $W and $M are array of names, rather than a single user, if that's the case, I assume you're trying to determine if a user is in that array. In PHP, you can use:
in_array($_SESSION["nome"], $W)
https://www.php.net/manual/en/function.in-array.php
which will return true/false.
if (true === in_array($_SESSION["nome"], $W)) {
echo '<img src="W.jpg">';
} else if (true === in_array($_SESSION["nome"], $M){
echo '<img src="M.jpg">';
}
But, this only gives two separate images for up to 5 unique names, and I'm not sure if that's what you're going for.
Related
In my PHP document I pull data from, for example, myDatabase. I then proceed to assign a value from a table in my Database to a variable. I know that this variable, which happens to be $fileLoc1, does have a value, for when I put
echo $fileLoc1;
It returns a value, or in my case a url to a file. Basically, what this does is tell the user if a file is available for download. I have the following code to check this.
if ($fileLoc1 === NULL) {
echo "<script>
document.getElementById ('alert-sng-available').style.display
= 'none !important';
</script>";
echo "<script>
document.getElementById ('alert-sng-Navailable').style.display
= 'block !important';
</script>";
}
In the code above #alert-sng-available is the alert that will show the green available div and the alert-sng-Navailable (not available) will show the red div.
When I first put this into my .php file, I thought nothing of it because it worked. $fileLoc1 is NOT null, therefore using the original settings of the div, showing the green, hiding the red. However if I edit the code ever so slightly...
if ($fileLoc1 !== NULL) {
echo "<script>
document.getElementById ('alert-sng-available').style.display
= 'none !important';
</script>";
echo "<script>
document.getElementById ('alert-sng-Navailable').style.display
= 'block !important';
</script>";
}
Can you guess what happens? Nothing. Absolutely, positively nothing. Below is an image showing results from both attempts. On the second snippet of code the green div should go away, being replaced by a red div. (yes, I'm using bootstrap, that's why I'm using the !important, but it doesn't work with or without it)
The Next picture will show the tag in the HTML once I change the if statement from === to !==
This is in inspect element, clearing showing php evaluated the !== equation to true, which is correct, but now the javascript doesn't work.
Lets try this again but with the === equation. It works! There are no script tags 'cause it evaluated to false as it should.
I'm at a loss here.
Yes, the divs are labeled correctly, no bootstrap isn't interfering. Because if I change the properties of both the alert-sng divs using "ctrl + shift + i" it works properly! Also, yes my javascript is at the bottom of the page
A gif showing it can work
You shouldn't be using the PHP–JS–HTML/CSS pipeline. In fact, you can simply rely on PHP itself to dictate what is shown/hidden on the page itself.
As you have not provided any markup in your code, I will be using a hypothetical example. Let's say you want to print <p>File available</p> when the $fileLoc1 variable is not null, and <p>File not available</p> otherwise, we can do this:
<?php
if ($fileLoc1 === NULL) {
echo '<p>File available</p>';
} else {
echo '<p>File not available</p>';
}
?>
For a more concise example, you can also use the ternary operators (?:), i.e.:
<?php
echo $fileLoc1 === NULL ? '<p>File available</p>' : '<p>File not available</p>';
?>
If you want both markups to be present so that you can manipulate them using JS later, you can even print both, and dictate the styles conditionally:
<p style="<?php echo $fileLoc1 === NULL ? 'display: none': 'display: block'; ?>">File available</p>
<p style="<?php echo $fileLoc1 === NULL ? 'display: block': 'display: none'; ?>">File not available</p>
In the case when $fileLoc is NULL, you will get the following markup:
<p style="display: none">File available</p>
<p style="display: block">File not available</p>
First time here so apologies if I'm doing something wrong.
I have the following php code:
<?php
$quoteFile = "quotes.txt"; //File holding qoutes
$fp = fopen($quoteFile, "r"); //Opens file for read
$content = fread($fp, filesize($quoteFile));
$quotes = explode("\n",$content); //Put quotes into array
fclose($fp); //Close the file
srand((double)microtime()*1000000); // randomize
$index = (rand(1, sizeof($quotes)) - 1); //Pick random qoute
?>
The code fetches a random quote from a text file by randomly choosing one of the lines of the .txt file.
I then echo out the result using:
echo $quotes[$index];
However what I want to achieve and don't seem to be able to is to have a button (html) that when clicked executes the echo $quotes[$index]; to the current page. So that each time the button is clicked it prints/echo's out a random quote from the .text file.
I did mess about with just setting a button up to refresh the page which by default made a new random quote display but it sometimes just reloaded a blank so I'm hoping someone can help me achieve this better or prompt me in the right direction. Thank tou.
You can try saving that variable into a session variable like this:
$_SESSION['quote'] = $quote['index'];
Then create an anchor element that redirects to current page:
Refresh
And print the result on the page:
<span><?php echo $_SESSION['quote']; ?></span>
To do all of this, you need to set a session. At top of your php file write:
session_start();
Hope that helps. :)
Your TXT file might have an empty line in it at the end or anywhere else. A second explanation of this, is that the way you are generating randomness is quite questionable.
Check out this simple example by W3 Schools.
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,1);
echo $a[$random_keys[0]]."<br>";
The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Or, simply:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Full Post: http://www.w3schools.com/php/func_array_rand.asp
Happy coding !
I hope someone has an answer for me,
I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php
src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>
what I would like to do is using js, dynamically update the src on a mouse click.
something like eg.
var imgSwitch = function(i){
Document.getElementById('js-img').src = "images/shop/
<?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}
Even to me this seems wrong which is why I've turned to the GURU's here
Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated
I am trying to figure out what you are asking, and I think this is your way to go:
var imgSwitch = function(i){
document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}
The change is in the i, you have to cut the string and add it as a variable.
But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.
A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.
In the function we pass the id as a parameter (onclick(changeSrc(this.id))) and we manipulate the src using the getElementById as we have the id.
<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />
<script>
function changeSrc(id) {
document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>
http://jsfiddle.net/tq1Lq5at/
Edit 1
You're using Document when it should be document, notice the lowercase d.
I have a webpage where admin users can edit the text on the page. But when they insert the text into the mysql database, it sometimes adds more and more white spaces before the acual content.
If you place your cursur before the first word on the page and spam backspace for a while, the whitespace in the database dissappears. But over time, the more you keep editing the page, more and more whitespaces are added again.
I did a lot of trouble shooting, but I just can't figure out what causes the whitespaces to be added. It does not always happen making it really difficult to troubleshoot.
Here's my code:
As my code is pretty long, I tried to translate most of the content to english.
If you want to translate something that in't already translated, the original language is Dutch.
over_ons.php - Shows edit button and page content from the database.
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper'><?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show Content
?><div id='editedText'><?php echo $inhoud; ?></p></div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
javascript.js - Sents page content to the php file sent_data.php:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable and send page content
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editedText").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php - Get page content from javascript,js and insert into database:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up which page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$tekst = trim($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Extra information:
PHP version: 5.5.15
jQuery version: 1.11.1
Testing in browser: Chrome
Database: phpMyAdmin 5.5.39
The content is inserted in a VARCHAR type with space for 10000 caracters
Thanks in advance for you help!
SOLUTION
Thanks to the great help of a lot of people, and especially #avnishkgaur, it is working perfectly now. Here is what I ajusted (also changed it in my code above, so that's working code now).
1. Removed all the white spaces I had in my code between <div id='editable'> and <?php
2. Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work)
3. Placed the editable text into another div as the code for getting the data from the database (was in the same div before)
4. Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before).
This was kind of an unexpected solution, so I think this could help others too.
As to why it is adding extra whitespace, I think it is because you are inserting the text from database into div directly (which contains some white space in html code, which is removed when page is rendered).
One efficient solution would be to insert your content in tag, probably like this:
<div class='big_wrapper'>
<p id='editable'></p>
</div>
Another solution is to trim the text before inserting into db. You can do that either at javascript post stage, or right before inserting in mysql db.
In jQuery, (which you are using) you can implement this :
data: 'tekst=' +$.trim(div_inhoud)+ '&pagina=' +pagina+ '&editor=' +$.trim(editor),
or in sent_data.php, you can use TRIM mysql function in your update query.
First of all, I would strongly suggest to use mysqli or PDO instead of the mysql functions in PHP, as these are deprecated. Please look into this on PHP.net.
As for your problem, I have no tried to reproduce the issue. I suggest you log and check what happens step by step, for example logging the div_inhoud var, are the spaces included at this stage already? And so on.
If you are in a hurry, you could also use the PHP function ltrim on the $tekst var in your sent_data.php, which would trim all spaces on the left side (Or any characters you would want to be trimmed from the string)
Try to add a trim() function in your send_data.php, this will help you to strip white spaces.
$tekst = trim($_POST['tekst']);
My guess is that the newlines after the <div id='editable'> and ?> and the indentation of <?php in over_ons.php is adding the extra whitespace. Specifically, a couple of extra /n's and also spaces from the indentation within the file.
You could trim the whitespace before saving it to your database, or alternatively, before the ajax call, or both.
In php, trim():
sent_data.php
$tekst = trim($tekst);
Or javascript, str.trim():
javascript.js
var div_inhoud = $("#editable").html().trim();
Also, you may want to consider using PHP Data Objects, instead of inserting variables directly into your SQL statements. It's actually really easy to use and in my opinion makes code easier to read and more reusable. There is a fantastic tutorial by Tuts+ that makes it easy to learn and get started. This will ensure you don't accidentally allow SQL injection issues into your application.
JQuery seems to be blocked
Hello there, I've been confronting this problem for several days, I just can't find a way to get this fixed, or around it.
What I want to do is simple, I want to read out every sub-folder of a big Project folder. Then assign a thumbnail image and a figcapture to this folder. With a simple for loop, php builds this for me. Everything works perfect and quick. The only thing is that the jquery won't respond. Even though I have created various menus with this technique. As you can see in my code, in the "script" tags, I have the jquery code which doesn't seem to work.
I don't know wheter php puts in a space somewhere or I just looked too long at this code for seing the error.
I appreciate any help.
<?php
/*Because of the "ease of use" aspect of this site, I prefered to write it completely in PHP,
advantage of that:
Images are loaded directly out of the folder, so I can just drag and drop something onto the server without having to write aditional code.
As you see, it can save a lot of time.*/
echo "<h1>Referenzen</h1><br>";
$projects = scandir('../src/sub/credentials'); //The credentials directory is being scanned and converted into an array.
$projectsSize = count($projects); //$size is being created. It counts the number of objects in the array which has been created above.
$projectsCaptions = file('../src/sub/captionsOfCredentials.txt'); //Edit the name of the figcaption in the "captionsOfCredentials.txt".
for($i = 2; $i < $projectsSize; $i++){ /*Simple "for" loop, that creates $i with the size of two, because PHP is 0-index based and has the "dot" and the "dotdot" folder. The loop stops at the end of the array($size).*/
echo '<a href="index.php#PRJ'.trim($projectsCaptions[$i]).'" class="ID'.trim($projectsCaptions[$i]).'">
<div class="projectFolder">
<img src="src/sub/credentialsThumb/project_00'.$i.'.jpg" width="100%" />
<figcaption>'
.$projectsCaptions[$i].
'</figcaption>
</div>
</a>';
/*Project folder level starts here.*/
$images = scandir('../src/sub/credentials/project_00'.$i);
$imagesSize = count($images);
for($k = 3; $k < $imagesSize; $k++){
$tempID = ('ID'.trim($projectsCaptions[$i]).'.php'); //$tempID is the entire file name including the .php part.
$handle = fopen($tempID, "a") or die ('Unable to open '.$tempID.' , please contact admin A.S.A.P..');
$imagesCode = 'test';
fwrite($handle, $imagesCode);
}
//end second for-loop
echo "
<script>
$(document).ready(function () {
$('#ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
</script>";
}
//end first for-loop
?>
You're selecting an element by id when you need to use class. Change the JS block to this:
$(document).ready(function () {
// Note ".ID" not "#ID"
$('.ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
UPDATE
It seems like you've also got an illegal character in $projectsCaptions[$i]. It's most likely a newline character. Try wrapping the above reference above in trim():
$('.ID" . trim($projectsCaptions[$i]) . "').click(function () {