This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 6 years ago.
I am still new with using PHP, so i am having a problem which is when i run this code, the PHP show in my browser.
I tried saving the file. html and this is the result
and if I tried to save it .php, this is the result
and here is my code
Can anyone help me ?!
Code:
<?php
include_once ("php_includes/check_login_status.php");
//If user is already logged in, header it away
if ($member_ok == true)
{
header ("location: Member.php?u=".$_SESSION["Username"]);
exit();
}
?>
<?php
//AJAX calls this part to be executed
if ( isset($_POST["e"]))
{
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$sql = "SELECT MmeberID, Username FROM Member WHERE Email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if ($numrows > 0) // The member exists
{
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
$id = $row["id"];
$u = $row["username"];
}
$emailcut = substr($e, 0, 4); //Cut the first 4 character of their mail
$randNum = rand(10000,99999); // generate 5 digits random number
$tempPass = "$emailcut$randNum"; //concatinate these two var to make the new random pass
$hashTempPass = md5($tempPass); //hash this new random password
$sql = "UPDATE Member SET temp_pass='$hashTempPass' WHERE Username='$u' LIMIT 1"; //Update the member table with the new password
$query = mysqli_query($db_conx, $sql);
$to = "$e";
$from = "IT_Department#8bits.com";
$headers ="From: $from\n";
$subject ="yoursite Temporary Password";
$msg = '<h2>Hello '.$u.'</h2>
<p> Somebody recently asked to reset your Facebook password. Didnt request this change? If you didnt request a new password.</p>
<p>We can generated a temporary password for you to log in with, then once logged in you can change your password to anything you like.</p>
<p>After you click the link below your password to login will be:<br /><b>'.$tempPass.'</b></p>
<p>Click here now to apply the temporary password shown below to your account</p>
<p>If you do not click the link in this email, no changes will be made to your account. In order to set your login password to the temporary password you must click the link above.</p>';
if(mail($to,$subject,$msg,$headers))
{
echo "success";
exit();
}
else
{
echo "email_send_failed";
exit();
}
}
else
{
echo "no_exist";
}
exit();
}
?>
<!DOCTYPE html>
<html>
<header id = "PageHeader">
<script type="text/javascript" src = "Index.js"> </script>
<meta charset="utf-8">
<!-- The website title -->
<TITLE> 8 BITES </TITLE>
<!-- Include the CSS file with this HTML file-->
<link rel="icon" type="iamge/x-icon" href="C:/Users/hp1/Desktop/Website/Pictures/Logo.jpg">
<link rel="stylesheet" type="text/css" href="Style.css">
<img id = "HeaderLogo" src = "C:/Users/hp1/Desktop/Website/Pictures/T_Logo.jpg" alt="Logo" style="width:46px; height:46px;">
<h2 id = "HeaderQuote"> 8BITS </h2>
</header>
<body id ="ForgetPasswordPageBody">
<?php include_once("template_pageTop.php"); ?>
<h1> Generate temporary log in password </h1>
<p> Note: This password will last only for 24 hours. In orde to obtain a new valid password please contact us! </p>
<form id = "ForgotPassForm">
<div id = "Step1"> Step 1: Enter your Email! </div>
<input id = "Email" type="Email" onfocus="_('status').innerHTML ='';" maxlength="100">
<br/>
<button id = "ForgotPass" onclick="ForgotPass()"> Generate </button>
<p id = "status"> </p>
</form>
<script>
function ForgotPass()
{
var email = ("Email").value;
if (email == " ")
{
_("status").innerHTML = "Type your Email address!";
}
else
{
_("ForgotPass").style.display = "none";
_("status").innerHTML = 'Please wait...';
var ajax = ajaxObj ("POST", "forgot_pass.php");
ajax.onreadystatechange = function ()
{
if (ajaxRetrun (ajax) == true)
{
var response = ajax.responseText;
if (response == "success")
{
_("ForgotPassForm").innerHTML = '<h3> Step 2. Check your Email inbox please </h3>';
}
else if (response == "no_exist")
{
_("status").innerHTML = "This is Email is not registered!";
}
else if (response =="email_send_falied")
{
_("status").innerHTML = "Mail falid to be sent!";
}
else
{
_("status").innerHTML = "An unknow error occured!";
}
}
}
ajax.send ("e=" +e);
}
}
</script>
<?php include_once("template_pageBottom.php"); ?>
</body>
<footer id = "PageFooter">
<div id = "Info">
<ul id = "InfoLinks">
<li> About </li>
<li> Help </li>
<li> Terms </li>
<li> Privacy </li>
<li> <a href ="CookiesPage.html" target="_blank" > Cookies </a> </li>
<li> Adds Info </li>
<li> #2017 8Bits </li>
</ul>
</div>
<div id = "Media">
<ul id = "MediaLinks">
<li> <img src = "C:/Users/hp1/Desktop/Website/Pictures/Facebook.jpg" alt="Facebook" style="width:40px;height:40px;"> </li>
<li> <img src = "C:/Users/hp1/Desktop/Website/Pictures/YouTube.jpg" alt="YouTube" style="width:40px;height:40px;"> </li>
<li> <img src = "C:/Users/hp1/Desktop/Website/Pictures/Instagram.jpg" alt="Instagram" style="width:40px;height:40px;"> </li>
<li> <img src = "C:/Users/hp1/Desktop/Website/Pictures/Twitter.jpg" alt="Twitter" style="width:40px;height:40px;"> </li>
</ul>
</div>
</footer>
</html>
EDIT: If you have WAMP installed already, run it, and place your project folder inside of: c:\wamp\www (could vary upon version though).
To preview it, type on your browser URL: localhost/yourProjectFolderName
The problem is that you have no PHP web server installed on your computer. You're on Windows, so install Wamp : it's an all-in-one web server that includes Apache2 (the server), PHP (who will read and execute your php code), MySql ans lots of others components.
Related
I have a chatting system project php with a nav and has a child div called inbox where inbox has a children div.message and div.message__requests:
<div class="inbox">
<div class="messages">
<header>
<nav>
<a id="messages"><b>Messages</b></a><a id="messageRequests"><b>Message Requests</b></a>
</nav>
<hr>
<form action="includes/chatsearch-inc.php" method="POST">
<input type="text" name="search" placeholder="Search a user or applicant\'s name">
<button name="submit"><i class="fa fa-search"></i></button>
</form>
</header>
<section>';
$sql = "SELECT * FROM users WHERE NOT usersId ='".$_SESSION['userid']."';";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="user__container">
<input type="hidden" data-userid="'.$row['usersId'].'">
<img src="profilepic/'.$row['usersProfilePic'].'">
<div class="user">
<p><b>'.$row['usersName'].'</b></p>
<p class="message">You: dssasdas</p>
</div>
</div>
<hr>';
}
echo '</section>
</div>
<div class="message__requests">
<nav>
<a id="messages"><b>Messages</b></a><a id="messageRequests"><b>Message Requests</b></a>
</nav>
<section>
<div class="user__container">
<img src="profilepic/'.$profilepic.'">
<div class="user">
<p><b>'.$_SESSION['username'].'</b></p>
<p class="message">asdasdsd</p>
</div>
</div>
<hr>
<div class="user__container">
<img src="profilepic/'.$profilepic.'">
<div class="user">
<p><b>'.$_SESSION['username'].'</b></p>
<p class="message">asdasdsd</p>
</div>
</div>
<hr>
</section>
</div>
</div>
Where div.messages shows the users inbox like the home screen of facebook messenger app.
If I click the said nav, the inbox will pop in the middle of the screen and the div.message is the default content.
Now when I click a div.user__container inside my div.messages, I can load the user chat box, like when you click a user in facebook messenger inside the div.messages, replacing all the content of div.messages with what I have in my other php file (simulating a real time chat box):
$sql = "SELECT * FROM messages AS m LEFT JOIN users AS u ON m.outgoingUsersId = u.usersId WHERE (incomingUsersId = '$incoming' AND outgoingUsersId = '$outgoing') OR (incomingUsersId = '$outgoing' AND outgoingUsersId = '$incoming') ORDER BY msgId DESC;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['outgoingUsersId'] == $outgoing) {
$output .= '<div class="chat outgoing">
<div class="message">
<p>'.$row['msgContent'].'</p>
</div>
</div>';
}
else {
$output .= '<div class="chat incoming">
<img src="profilepic/'.$row['usersProfilePic'].'">
<div class="message">
<p>'.$row['msgContent'].'</p>
</div>
</div>';
}
}
echo $output;
}
And I can achieve this all by my jquery call:
$('section .user__container').click(function() {
var userid = $(this).children('input').data('userid');
$('.inbox .messages').load('includes/ajax-load/chatpage-aload.php',
{
usersid : userid
}, function() {
$('.user__inbox header i').click(function() {
// I want to load back to div.messages content
});
var sender = $('#chatForm #chatSender').val();
var receiver = $('#chatForm #chatReceiver').val();
setInterval(() => {
$.post('includes/ajax-func/getchat-afunc.php', {
outgoingUsersId : sender,
incomingUsersId : receiver
}, function (response) {
$('.user__inbox section').html(response);
});
}, 500
);
$('#chatForm').submit(function(e) {
e.preventDefault();
var message = $('#chatForm input[type="text"]').val();
$.post('includes/ajax-func/insertchat-afunc.php', {
outgoingUsersId : sender,
incomingUsersId : receiver,
message : message
}, function (data) {
$('#chatForm input[type="text"]').val("");
});
});
});
});
My question is, how can I go back to the main content of div.messages (like how users in messenger app can go bck to the home screen when the click the back button beside the users info in their header) without reloading the whole webpage, when I click the:
$('.user__inbox header i').click(function() {
// I want to load back to div.messages content
});
Or any recommendations to my code? Thanks
I want to create a Twitter share link from my website to share the first few lines of a blog by the user by fetching data from the PHP database. The data of the blog is stored in HTML format in the database. I tried fetching data and converting it to HTML decoded chars but when I try using that converted chars to Twitter link it re-adds HTML chars/tags before posting the tweet. Image attached for reference.
<script>
function share(a) {
let share_poem_ID = "#share-modal-" + a;
document.querySelector(share_poem_ID).style.display = "block";
}
function shareClose(b) {
let share_poem_ID = "#share-modal-" + b;
document.querySelector(share_poem_ID).style.display = "none";
}
</script>
<?php
include 'connection.php';
session_start();
$query = " Select * From $dbtable";
$result=#mysqli_query($connection,$query);
$row=mysqli_fetch_assoc($result);
foreach ($result as $row) {
$Poem = $row['Poem'];
$PoemShare = htmlspecialchars_decode($Poem);
echo "
<div>
<div class='the-poem'>
<div class='poem'>$Poem</div>
</div>
<div class='poem-options'>
<a class='share poem-option-list' id='report-btn-$ID' data-field-id='$ID' onclick='share($ID)'><i class='mdi mdi-share'></i></a>
</div>
</div>
<!--- Share Modal --->
<div class='modal-share' id='share-modal-$ID' role='dialog'>
<div id='modal_content-share' class='modal-content-share'>
<div class='page-container' id='page-content'>
<span id='twitter$ID' class='share-option'>
<i class='mdi mdi-twitter'></i>
Share via Twitter
</span>
<script>
$('#twitter$ID').on('click',function(){
window.open('https://twitter.com/intent/tweet?url=https://www.MartianJK.com/ms/login.php?u=$ID&text='$PoemShare'&hashtags=SpreadingSmiles', '_blank').focus();
})
</script>
</div>
</div>
</div>
";
}
?>
You can use strip_tags():
$PoemShare = strip_tags($Poem);
Or to keep <br> tag:
$PoemShare = strip_tags($Poem, '<br>');
$PoemShare = strlen($Poem) > 99 ? substr($Poem,0,100).'...' : $Poem;
$PoemShare = strip_tags($PoemShare, '<br>');
$PoemShare = preg_replace('<<br />>','%0A', $PoemShare);
$PoemShare = str_replace('&','%26', $PoemShare);
$PoemShare = str_replace('"','%22', $PoemShare);
$PoemShare = str_replace("'",'%27', $PoemShare);
echo var_dump($PoemShare);
This code made my work. Hope it helps others too. Credits to user #Syscall
On my main page I have a content box where I load the content using Jquery's load() from another page. All is working fine and it's quick and nice.
Next thing I want to do is to add a small filtering feature to it. The variable is sent to the main page (snappage.php) as a GET variable. However the php for the sql query is in another page (i.e all-snaps.php). Let me show you my code:
snappage.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
}
?>
<section class="main-snap-page-wrapper">
<nav class="all-snaps-countries">
<h4>Filter by country</h4>
<ul>
<?php
//GET COUNTRY FLAGS
$flagsql = mysql_query("SELECT * FROM countries");
while($getflag = mysql_fetch_array($flagsql)) {
$countryname = $getflag['countryname'];
$flag = $getflag['countryflag']; ?>
<li>
<a href="snappage.php?country=<?php echo $countryname?>">
<img src="<?php echo $flag?>" alt="">
<h5><?php echo $countryname?></h5>
</a>
</li>
<?php } ?>
</ul>
</nav>
<div class="all-snaps-page">
<nav class="main-page-tabs-wrapper">
<ul class="main-page-tabs" id="<?php echo $country?>">
<li class="active-tab">All</li>
<li>Female</li>
<li>Male</li>
</ul>
<div class="main-snaps-content"></div>
</nav>
</div>
</section>
<script type="text/javascript">
$('.main-snaps-content').load('all-snaps.php');
$('.main-page-tabs li').on('click', function () {
$('.main-page-tabs li').removeClass('active-tab');
$(this).addClass('active-tab');
var page = $(this).find('a').attr('href');
$('.main-snaps-content').load(page + '.php');
return false;
});
</script>
Next is the page which I load into .main-snaps-content from i.e all-snaps.php:
all-snaps.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
$newsql = mysql_query("SELECT * FROM users JOIN fashionsnaps ON users.id = fashionsnaps.userid WHERE country = '$country' ORDER BY snapid ASC");
}
else {
$newsql = mysql_query("SELECT * FROM fashionsnaps ORDER BY snapid ASC");
}
?>
<ul class="snaps-display">
<?php
//GET SNAPS BY ID
while ($getnew = mysql_fetch_array($newsql)) {
$newsnappics = $getnew['snappic'];
$newsnapid = $getnew['snapid'];
?>
<li>
<a href="snap.php?id=<?php echo $newsnapid?>">
<img src="<?php echo $newsnappics?>" alt="">
</a>
</li>
<?php } ?>
</ul>
So what I want to achieve here is to load the filtered content from all-snaps.php into the .main-snaps-content which is on snappage.php.
Where should I send this $country variable? On which page should I retrieve it?
You can do this pretty easily with jQuery load.
In snappage.php:
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: "<?php echo htmlentities($country); ?>"}));
Update:
You'll need better handling of the PHP GET/$country var. You can initialize it at the top of snappage.php like this:
$country = (isset($_GET['country'])) ? $_GET['country'] : '';
Then, your JS will need a conditional:
var country = "<?php echo htmlentities($country); ?>";
if (country) {
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: country}));
} else {
$(".main-snaps-content").load("all-snaps.php");
}
I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html
So i have this code that works in all my browsers but has a weird behavior in IE.
$(document).ready(function () {
//$.ajaxSettings.cache = false;
var refresh = setInterval(function () {
$('div#top_right').load('refresh.php?randval=' + Math.random() * 99999);
}, 5000);
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
});
This reloads my user panel div and checks if there is any new messages and such (and as you can see I tried modifying in for IE caching). This works well with all browsers, even IE, but in IE after the first reload it removes all the href attributes to the links (such as the messages link) in the user panel div. I have no clue why this is happening. Please help?
This is the code for refresh.php:
<?php
session_start();
include_once 'functions.php';
$user = $_SESSION['user'];
$new_message = FALSE;
$new_friend = FALSE;
$new_reply = FALSE;
$query = "SELECT status FROM messages WHERE recip='$user'";
$result = queryMysql($query, "divs");
while($row=mysql_fetch_assoc($result)){
if($row['status']=='new') $new_message=TRUE;
}
$query2 = "SELECT status from friends WHERE user='$user'";
$result2 = queryMysql($query2, "nezworld");
while($row2=mysql_fetch_assoc($result2)){
if($row2['status']=='pending') $new_friend=TRUE;
}
$query3 = "SELECT status from replies WHERE recip='$user'";
$result3 = queryMysql($query3, "divs");
while($row3=mysql_fetch_assoc($result3)){
if($row3['status']=='new') $new_reply = TRUE;
}
?>
<div id="top_right"><ul id="login2">
<li class="user_nav"><?php echo $user; ?></li>
<abbr title="Home"><a href="index.php" class='white'><li class='icons home'>N</li></a></abbr>
<abbr title="Messages"><a href="message.php?view=<?php echo $user; ?>" class='white'><?php if($new_message){?><li class='icons2 messages2'><?php }else{?><li class='icons2 messages'><?php }?>M</li></a></abbr>
<abbr title="Replies"><a href="replies.php?view=<?php echo $user; ?>" class='white'><?php if($new_reply){?><li class='icons2 replies4'><?php }else{?><li class='icons2 replies2'><?php }?>R</li></a></abbr>
<abbr title="Friend Requests"><a href="friends.php?view=<?php echo $user; ?>" class='white'><?php if($new_friend){?><li class='icons2 friends2'><?php }else{?><li class='icons2 friends'><?php }?>F</li></a></abbr>
<li><a class="submit" class='white' href="logout.php">LOGOUT</a>
</form>
</li>
</ul></div>