PHP file upload - Not checking the file size - javascript

I'm trying to make a file upload form from two days but cant seem to get this to work. My code is checking the extension of the file but not checking the file size. I googled, tried different methods but unable to get this to work. Can someone help?
Here's the code -
<?php
if(isset($_POST['carsubmit']))
{
foreach($_POST as $key=>$val)
${$key}=addslashes($val);
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 2097152;
$upload_path = "resumes/";
$filename = $_FILES['attachresume']['name'];
$file_tmp =$_FILES['attachresume']['tmp_name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$cardupcheck = "select * from `careers` where `email` = '$email'";
$cardupresult = mysql_query($cardupcheck);
if(mysql_num_rows($cardupresult)==1)
{
?>
<script type="text/javascript">
notification('You have already sent us!','error');
</script>
<?php
}
else
{
if(!in_array($ext,$allowed_filetypes)){
?>
<script type="text/javascript">
notification('Please check the file extension. Only jpg, png and gif are allowed!','error');
</script>
<?php
}
else if($file_tmp > $max_filesize){
?>
<script type="text/javascript">
notification('too large!','error');
</script>
<?php
}
else
{
move_uploaded_file($file_tmp,"resumes/".$filename);
$carquery = "INSERT INTO `careers` (`name`, `email`, `phone`, `aoi`, `qual`, `resume`) VALUES ('$name', '$email', '$phone', '$aoi', '$qual', '$filename')";
$carresult = mysql_query($carquery);
if($carresult)
{
?>
<script type="text/javascript">
notification('Thank you! We will get back to you soon!','success');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
notification('There was an error. Please try after some time!','error');
</script>
<?php
}
}
}
}
?>

You are comparing file size with the file name. Get the size of the uploaded file by $_FILES["attachresume"]["size"].Use this code instead
<?php
if(isset($_POST['carsubmit']))
{
foreach($_POST as $key=>$val)
${$key}=addslashes($val);
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 2097152;
$upload_path = "resumes/";
$filename = $_FILES['attachresume']['name'];
$file_tmp =$_FILES['attachresume']['tmp_name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$file_size = $_FILES["attachresume"]["size"]; // Here is the size of the uploaded file
$cardupcheck = "select * from `careers` where `email` = '$email'";
$cardupresult = mysql_query($cardupcheck);
if(mysql_num_rows($cardupresult)==1)
{
?>
<script type="text/javascript">
notification('You have already sent us!','error');
</script>
<?php
}
else
{
if(!in_array($ext,$allowed_filetypes)){
?>
<script type="text/javascript">
notification('Please check the file extension. Only jpg, png and gif are allowed!','error');
</script>
<?php
}
else if($file_size > $max_filesize){
?>
<script type="text/javascript">
notification('too large!','error');
</script>
<?php
}
else
{
move_uploaded_file($file_tmp,"resumes/".$filename);
$carquery = "INSERT INTO `careers` (`name`, `email`, `phone`, `aoi`, `qual`, `resume`) VALUES ('$name', '$email', '$phone', '$aoi', '$qual', '$filename')";
$carresult = mysql_query($carquery);
if($carresult)
{
?>
<script type="text/javascript">
notification('Thank you! We will get back to you soon!','success');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
notification('There was an error. Please try after some time!','error');
</script>
<?php
}
}
}
}
?>
Hope this helps you

This one worked -
else if(($_FILES['attachresume']['size'] >= $max_filesize) || ($_FILES["attachresume"]["size"] == 0))

Related

Trying to open pdf file in new browser window

Cant get the PDF open in new browser window. There is a php code I use to set the PDF and open it!
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline; ");
header('Accept-Ranges: bytes');
$file_type = "in";
$flag = 0;
}
else{
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline;");
header('Accept-Ranges: bytes');
$file_type = "out";
$flag = 1;
}
?>
<?php session_start();
if (((isset($_SESSION['UserID'])) and (isset($_SESSION['Pin_code']))) and (isset($_COOKIE['CookieMy']))){
$form='<form action="login.php" method="get" style="width: 900px;margin: -1px auto -57px auto;" class="exit_but">
<input type="submit" name="exit" value="EXIT" style="margin-left: 800px;"></form>';
echo $form;
} else {
header("Location: login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
idleTimer = null;
idleState = false;
idleWait = 1200000;
var theElement = document.getElementById("elem");
$(document).ready(function(){
$(document).bind('mousemove keydown scroll click', function(){
clearTimeout(idleTimer);
idleState = false;
idleTimer = setTimeout(function(){
idleState = true;
window.location.href = "login.php"
}, idleWait);
});
});
</script>
</head>
<body>
<?php
function last(){
if (($_POST['name_check'])=="in"){
$type = '"pdf-in"';
$flag=0;
echo "<script>window.flag_in=false;</script>";
}
else{
$type = '"pdf-out"';
$flag=1;
echo "<script>window.flag_in=true;</script>";
}
if (!isset($aircraftid)){
$aircraftid = $_POST['hostcountry'];
$aircraftid='"'.$aircraftid.'"';
}
if (!isset($date)){
$date = $_POST['per1'];
$date=date($date);
}
include ("config.php");
//////////////////////////////////////////
$mysqli = new mysqli($dbconf['host'], $dbconf['user'], $dbconf['password'], $dbconf['dbname']);
if ($mysqli->connect_errno) {
echo "MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = mysqli_multi_query( $mysqli, "SELECT dn_get_flight_file_name($date,$aircraftid,$type);") or die( mysqli_error( $mysqli ) );
if( $query )
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
$PDF_File_Name=$row[0];
}
$result->free();
}
}
///////////////////////////////////
mysqli_close( $mysqli );
$qwerty=$PDF_File_Name;
///////////////////////////////////
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
if($flag==0){
$file_path_ftp = $ftp_path_pdf_in.$qwerty;
$file_path_local = "in/".$qwerty;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$qwerty;
$file_path_local = "out/".$qwerty;
}
$file_path_ftp = trim($file_path_ftp);
$file_path_local = trim($file_path_local);
$file = $file_path_local;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($file, $current_content);
$qwerty=$file_path_local;
$date2 = $_POST['date'];
$num = $_POST['num'];
return array ($qwerty,$date2,$num);
}
if (isset($_GET['name'])){
$qwerty=$_GET['name'];
}
else {
list ($qwerty,$date2,$num) = last();
}
if (!file_exists($qwerty)) {
$file_path_local=$qwerty;
$slash_occur = stripos($qwerty, '/');
$file_type = substr($qwerty, 0, $slash_occur);
$file_name = substr($qwerty, $slash_occur+1);
if($file_type=='pdf-in'){
$file_path_ftp = $ftp_path_pdf_in.$file_name;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$file_name;
}
echo "<h2>file_type = ".$file_type.", file_name = ".$file_name."</h2>";
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($qwerty, $current_content);
}
if (isset($_GET['date'])){
$date2=$_GET['date'];
}
if (isset($_GET['num'])){
$num=$_GET['num'];
}
?>
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
#readfile($ftp_path_pdf_in.$qwerty);
} else {
#readfile($ftp_path_pdf_out.$qwerty);
}
?>
</body>
</html>
I'm trying to open PDF file in the new (Chrome) browser window.
document.action =window.open('date_PDF.php', 'newWindow', 'width=1000, height=1000');
Error is Failed to load PDF document.
When I do document.getElementById("edit").action ="date_PDF.php"; it opens pdf.
I get the PDF file from the ftp server and than display it on date_PDF.php #readfile($ftp_path_pdf_in.$qwerty);
Where is the problem?
Thank you!
You have not defined the name_check html element. Also you have not passed the 'type' parameter in the url. I think the name_check and type are present on the page from where you open the pdf file.
If you want to open the pdf file using window.open then you should use the url: date_PDF.php?type=in
After the readfile statement you should have an exit statement. See the example for the readline function: http://php.net/manual/en/function.readfile.php#refsect1-function.readfile-examples

Delete image from Database using PHP (wordpress) along with it's record in DB

I have this code that deletes a student record from the database, it deletes the student information as well as where an image is stored on the server however, I also want it to delete the image file itself, not just the record. How can I do this.
This code is where the user clicks to delete the student.
<a href="javascript:void();" onclick="deleteItem
(<?php echo $student_row->id;?>,<?php echo $_REQUEST['regNumber'];?>,
<?php echo $student_row->id;?>,'parent')">Delete</a>
This code is the JS code referenced above:
function deleteItem(registration_number,parent_id,id,type)
{
var parent_id = "<?php echo $_REQUEST['regNumber'];?>";
var url_pass="<?php echo get_site_url();?>/student-delete/?
regNoIndivid="+registration_number+
"&parentId="+parent_id+"&id="+id+"&type="+type;
if (confirm("Are you sure?")) {
window.location.href = url_pass;
}
return false;
}
This is from student-delete:
if($_REQUEST['type'] == "teacher")
{
$where=array("id"=>$_REQUEST['id']);
//echo "<pre>";print_r($where);echo "</pre>";
//$delete_row=$wpdb->delete('wp_new_student_user', $where);
$delete_row = $wpdb->query('DELETE FROM wp_new_student_user WHERE id
='.$_REQUEST['id']);
$wpdb->show_errors();
if($delete_row)
{
$url_location=get_site_url()."/my-account-teacher/?
regNumber=".$_REQUEST['parentId']."&type=tea&back_list=yes";
?>
<script type="text/javascript">
window.location.href="<?php echo $url_location;?>";
</script>
<?php
}
}
elseif ($_REQUEST['type'] == "parent") {
$where=array("id"=>$_REQUEST['id']);
//echo "<pre>";print_r($where);echo "</pre>";
//$delete_row=$wpdb->delete('wp_new_student_user', $where);
$delete_row = $wpdb->query('DELETE FROM wp_new_student_user WHERE id
='.$_REQUEST['id']);
$wpdb->show_errors();
if($delete_row)
{
$url_location=get_site_url()."/my-account-parent/?
regNumber=".$_REQUEST['parentId']."&type=par&back_list=yes";
?>
<script type="text/javascript">
window.location.href="<?php echo $url_location;?>";
</script>
<?php
}
}
Please use PHP UNLINK function to delete the file
if($delete_row)
{
unlink(Path to the file);
}

JavaScript doesn't run after PHP header call

I'm trying to redirect using PHP header/even a JavaScript work around call inside php to my clients.php webpage.
The problem is that PHP header/the work around loads the webpage flawlessly but the Javascript still isn't ran.
Additional notes is that after the header or even Javascript redirect to the page, trying to refresh the page won't have the Javascript load. Only switching between a webpage and coming back to clients.php does the Javascript actually run.
I have also tried this: JavaScript not loading after PHP header() redirect
but to no avail.
Here are parts of my code segmented, just because its quite lengthy.
clients.php
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
script.php
if($update_statement) {
$_SESSION['message_success'] = "$_membername's Careplan has been successfully updated.";
echo "<script type='text/javascript'>window.location.href = '../clients.php';</script>";
//header("Location:". $redirect);
//exit();
}
Note that clients.php and script.php are not in the same file.
Per Riggs request
<?php
session_start();
$message="";
if(isset($_POST["login"])) {
$redirect = NULL;
if($_POST['redirect'] != '') {
$redirect = $_POST['redirect'];
}
if(empty($_POST['username']) || empty($_POST['password'])) {
$message = "Both fields must be filled out.";
$_SESSION['sysLogin'] = "$message";
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
require('server_connection.inc');
$connection = connect_to_db(DB_SERVER, DB_UN, DB_PWD, DB_NAME);
$user=mysqli_real_escape_string($connection, $_POST['username']);
$pass=mysqli_real_escape_string($connection, $_POST['password']);
$statement = "select * from Credentials where UserName='$user' AND Password='$pass';";
$result = $connection->query($statement);
if($result->num_rows == 1) {
// lets determine the type of user that logged in
// if not employee but CEO, Manager, ETC, its an Admin
$employeeid = ($result->fetch_assoc())["EmployeeID"];
$check = "select Employees.Position, Employees.Name, Employees.ID from Credentials, Employees where (Credentials.EmployeeID = Employees.ID) AND Employees.ID = '$employeeid';";
$result_two = $connection->query($check);
if($result->num_rows == 1) {
$the_row = $result_two->fetch_assoc();
if($the_row["Position"] == "Employee") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "employee";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
} else if($the_row["Position"] == "CEO" || $the_row["Position"] == "Manager") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "admin";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
}
} else {
$message = "Unable to Parse Employee. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
} else if($result->num_rows == 0){
$message = "Incorrect username or password";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
$message = "Database Login Error. Too many retrieved accounts. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
}
}
function write_to_log($message) {
$file = fopen("logfile.txt", "w") or die("Unable to open file!");
fwrite($file, "$message\n");
fclose($file);
}
function connect_to_db($server, $username, $pwd, $dbname) {
$conn = mysqli_connect($server, $username, $pwd);
if(!$conn) {
echo "" . mysqli_error($conn);
exit;
}
$dbh = mysqli_select_db($conn, $dbname);
if(!$dbh) {
echo "" . mysqli_error($conn);
exit;
}
return $conn;
}
?>
This script merely links session while also checking for the login validity of the user
The message passing does indeed work with headers to another file 'dashboard.php' but redirecting from script.php to dashboard.php doesn't yield the message, thus an implication still arises.
The tmp JavaScript variable is not being defined since you haven't started the session. Include session_start(); at the top of your code.
<?php session_start(); ?>
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
To my surprise, the issue wasn't with the Javascript at all nor positioning like the thread posted suggested. Rather the issue seemed to have been with my PHP and calling $_membersname.
For advice to trouble shoot this later on, make sure no errors are outputted, even if PHP doesn't find any. This is from a variable that hasn't be declared.

Connecting to database via PHP and displaying contents on browser

I am connecting to an SQL server via PHP script and displaying the contents retrieved on the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
All 3 files are in the same folder.
The browser just displays a null and I don't hit any of the logging information from the .php file. Is my method right? Am I using the right javascript event?
Change your connection.php in this way:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
You need to change mime type of your response. Moreover you cannot print out anything else than json data. That's way I removed from your code these lines:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
Try using a relative pathname for connection.php here: d3.json("connection.php"
Something like "/dirname/connection.php".
You can test connection.php alone using a full pathname, like http://www.yourserver.xxx/dirname1/dirname2/...connection.php

AJAX, jQuery, javascript for a chatroom

So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)

Categories

Resources