JavaScript doesn't run after PHP header call - javascript

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.

Related

$_SESSION not working while successful login

index.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
email = $("#cs-username-1").val();
password = $("#cs-login-password-1").val();
if(email=='' || password=='')
{
$("#loginsuccess").html("<p id='red'>All fields are mandatory!<p>");
}
else
{
$.ajax({
type:"POST",
data:{"email":email,"password":password},
url:"login.php",
success: function(data)
{
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$("#loginsuccess").html('<p id="red">' + data.error + '</p>');
}
}
});
}
});
});
</script>
login.php
<?php
include("config.php");
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
$sql = mysqli_query($con,"select student_id from student where email='".$email."' and password='".$password."' and status='1'");
if (mysqli_num_rows($sql) > 0)
{
$results = mysqli_fetch_array($sql);
$_SESSION['student'] = $results['student_id'];
if (!isset($_POST))
{
header ("Location: dashboard.php");
}
else
{
echo json_encode(array('redirect' => "dashboard.php"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
?>
dashboard.php
<?php
session_start();
echo $_SESSION['student'];
/*if(!isset($_SESSION['student']))
{
header("location: index.php");
}*/
include('assets/db/config.php');
?>
In this code I am simply create login module. Here, what happen I am create login via jQuery where I have login.php file and I am storing student_id inside the session variable but when I redirect to dashboard.php and echo $_SESSION['student'] then it throw an error i.e. Notice: Undefined index: student in C:\xampp\htdocs\test\dashboard.php on line 3 I don't know why where am I doing wrong? Please help me.
Thank You
Please start the session in login.php file :
include("config.php");
session_start();
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
Or put the session_start in config.php file

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

Send data from both php and js to php

I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>

Login function not working

Okay so i made a login button and this is the function code, But it keeps showing the error " Login unsuccessful, Please try again... "
Thank you in advance...
I didn't really get what you were asking for so i put almost all the code in cause i am trying and trying and can't figure it out...
<?php
include_once ("php_includesss121/check_login_statusopop.php");
// If user is already logged in, header that user away
if ($user_ok == true)
{
header("location: user.php?u=" . $_SESSION["username"]);
exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if (isset($_POST["e"]))
{
// CONNECT TO THE DATABASE
include_once ("php_includesss121/db_conxx12.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if ($e == "" || $p == "")
{
echo "login_failed";
exit();
}
else
{
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if ($p != $db_pass_str)
{
echo "login_failed";
exit();
}
else
{
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("user", $db_username, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime('+30 days') , "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<script src="js/mainopop.js"></script>
<script src="js/ajaxopop.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == ""){
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'Please wait...';
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, Please try again...";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
</script>
</head>
<body>
<?php
include_once ("template_pageTopLoginPageopop.php"); ?>
<div id="pageMiddle">
<h2>Welcome ...</h2>
<h3>Log In Here</h3>
<!-- LOGIN FORM -->
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="300">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br />
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
<!-- LOGIN FORM -->
</div>
<?php
include_once ("template_pageBottomopop.php");
?>
</body>
</html>
And Javascript file ajaxopop.js:
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
Please note that password in DB Table should be md5
encrypted as in PHP, you are encrypting it to match further. If not, just remove md5 encryption from PHP Code.

PHP file upload - Not checking the file size

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))

Categories

Resources