PHP Undefined index (caused by jquery file upload) - javascript

I've been trying to get a file-upload working for a website I'm working on. I'm doing this outside of a form, and after days of searching I finally found something that fits my method from the answer on this question:
The thing is, as soon as I applied the code to my own script, I got 'Undefined index' errors, and when I removed it, everything went fine.
Here is my code:
HTML
<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>
jQuery
function newsItem(action){
var thumbnail = $('#newsitem-thumbnail')[0].files[0];
var fileReader = new FileReader();
fileReader.readAsText(thumbnail, 'UTF-8');
fileReader.onload = shipOff;
function shipOff(e){
var r = e.target.result;
if(action == "insert"){
$.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
thumbnail:thumbnail.name,
action:action,
data:r},
function(result){
console.log(result);
console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
if(result == "succes"){
window.location.reload();
}else{
$(".error-msg").html(result);
}
});
}else if(action == "delete"){
//To be implemented when I get the submit working D:
}
}
}
PHP (Please excuse the mess -needs serious cleaning)
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
echo print_r($_POST);
echo var_dump($_POST);
$message = $_POST['message'];
$action = $_POST['action'];
$thumbnail = $_POST['thumbnail'];
$data = $_POST['data'];
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
if($_POST['message'] != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "succes";
}
}else if($action == "delete"){
$sql = "";
}
?>
Does anybody see what's going wrong here? Or does anyone have an alternative option?
I hope someone can help me out with this issue.

Change it like this:
include("../assets/libs/SQLLib.php");
DB_Connect("test");
print_r($_POST); //Dont echo, what is already echoed
var_dump($_POST); //Dont echo, what is already echoed
$message = !empty($_POST['message'])?$_POST['message']:'';
$action = !empty($_POST['action'])?$_POST['action']:'';
$thumbnail = !empty($_POST['thumbnail'])?$_POST['thumbnail']:'';
$data = !empty($_POST['data'])?$_POST['data']:'';
if(!empty($thumbnail) && !empty($data)){
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
} else {
echo json_encode(array('error'=>'No data and thumbnail assigned'));
}
if($message != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "success";
}
}else if($action == "delete"){
$sql = "";
}
As well you only need to change error reporting level in .htaccess or php in order to prevent warning message to be displayed. In .htaccess:
php_flag error_reporting E_ERROR
If in .php file then
<?php error_reporting(E_RROR); //This displays only Errors, no warning and notices.

Hope you have tried using
isset($_POST) or isset($_POST['message']) if you get "Notice: Undefined index: message".

So in the end I opted out of a full jQuery-upload, and went for something else.
I am now uploading files purely through a PHP call, instead of a jQuery post event, with a small JavaScript check next to it to see if the form is submittable.
The code:
HTML
<div class='error-msg'></div>
<form method='post' action='requestPages/newsitems.php' enctype='multipart/form-data'>
News message
<textarea id='newsitem-message' name='newsitem-message' onchange='checkFormSubmit()'/>
<input type='file' name='newsitem-thumbnail' id='newsitem-thumbnail' />
<input hidden type='text' value='insert' name='newsitem-action'/>
<input class='submit' id='newsitem-submit' type='submit' value='Post news' disabled/>
</form>
PHP
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
var_dump($_FILES);
var_dump($_POST);
$message = $_POST['newsitem-message'];
$action = $_POST['newsitem-action'];
$errors= array();
$hasFile = false;
if($action == "insert"){
echo ($_FILES['newsitem-thumbnail'][0] == UPLOAD_ERR_NO_FILE);
if(isset($_FILES['newsitem-thumbnail']) && $_FILES['newsitem-thumbnail']['error'] != UPLOAD_ERR_NO_FILE){
$file_name = $_FILES['newsitem-thumbnail']['name'];
$file_size =$_FILES['newsitem-thumbnail']['size'];
$file_tmp =$_FILES['newsitem-thumbnail']['tmp_name'];
$file_type=$_FILES['newsitem-thumbnail']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['newsitem-thumbnail']['name'])));
$extensions= array("jpeg","jpg","png");
if(!in_array($file_ext,$extensions)){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
$hasFile = true;
}
if(empty($errors)){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$file_name."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
if($hasFile){
if(!move_uploaded_file($file_tmp,"../assets/images/thumbnails/".$file_name)){
echo "Moving the file failed!";
}
}
}
}else{
print_r($errors);
}
}else if($action == "delete"){
$sql = "";
}
?>
JavaScript
function checkFormSubmit(){
if($.trim($('#newsitem-message').val()) != ""){
$('#newsitem-submit').prop('disabled', false);
}else{
$('#newsitem-submit').prop('disabled', true);
}
}

Related

Javascript inside else statement isn't working. Message doesn't appear

I'm making a basic login for a php website, the function is really simple if checks if the data send using POST is in a MySQL table and if it's correct it would allow the user to proceed it the data is incorrect, it should show a message saying credentials are incorrect:
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
}
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
?>
The if statement is working so far, and even the else but the message isn't showing out at all, I'm trying to look where exactly is the problem but I can't found it.
Try this code. Your brackets are in the wrong position.
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
}
?>
Like mentioned in the comments you have one curly braket that messes up your code. The else statement is now checking for the first if statement in which you check the request type. But the else case with the count should be the else case to your if statement that checks the number of rows ($count).
Furthermore you need to concatenate strings in your echo because your JS code doesnt know about variables or values from your PHP script like this:
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
Then try this
}else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
Try this one. Probably you have an extra bracket } or is wrongly positioned and you are echoing $message as a string which is wrong. Use concatenation in this way to print your message
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
header('Refresh: 0; URL=index.php');

PHP With ajax if else not working and md5()?

when i execute my javascript this code why just else statement is working but not if,and when i use md5($_POST['password']) can't login?? but when not using md5 everything is ok
help me please :)
this is my database
this is my javascript
<script type="text/javascript">
$(document).ready(function() {
$("form#form_login").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url :'../assets/js/utama/login.data.php',
data:formData,
async:false,
cache:false,
contentType:false,
processData:false,
success:function(data){
if(data == "success")
{
window.location = '../index.php?hal=home';
}else{
alert('error');
}
}
});
});
return false;
});
</script>
this is my php file
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password'])
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
}else{
echo "alert('errorr')";
}
}
?>
You need to echo "success" in your PHP script response.
semicolon(;) missing md5($_POST['password']);
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
Please make sure all "password_user" column contain the md5 string in Database. So you have to store md5 for a password at the time of user registration. You have one non-md5 entry in the database for user "reza". So for this user md5($_POST['password']) will not match in database.
And write echo 'success'; in IF statement in PHP script.
In your code, in your select query there is space after $email and also you need to echo success when your if condition is executed. Improvise your php code as below:
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='".$email."' AND password_user='".$pass."'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "alert('errorr')";
}
}
?>
Hope this will help!
Yes It will always go in else part because you haven't eco success from php file then how can it will be go in success!!!??
change your php script to
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
}
?>
Also mark that don't use mysql* its deprecated and completely remove in PHP7. Use mysqli* or PDO instead

PHP - AJAX - Validate simple login form (check if user is a especified one)

I have this simple form I'm testing. It's just a test for the beginning of a form that will be improved later on; I only need it to work correctly. I still don't have the database ready, so in my code I have two users that I want to pass as 'registered'.
Here's the code for the form:
<form action="" method="POST">
<label>User: </label>
<input type="text" name="user" id="usuario" />
<label>Password: </label>
<input type="password" name="password" id="password" />
<div class="text-center">
<button type="button" class="boton-submit" name="submit" onClick="login()">Sign In</button>
</div>
</form>
These two inputs are validated with JavaScript, and the values are sent through AJAX.
This is the code (only the AJAX part, the rest are only validations and they work fine):
function login(){
if(validationLogin()){
$.ajax({
url: "http://localhost/MyApp/extras/processLogin.php",
type: "POST",
data: {"user": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "OK"){
window.location.href = "http://localhost/MyApp/loginSuccess.php";
}else{
window.location.href = "http://localhost/MyApp/loginFail.php";
}
}
});
}else{
//alert("Incorrect data");
}
}
And this is code in the PHP file:
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if (isset($_POST['submit'])){
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
}
At the beginning, I had an action in the form that sent data to the PHP directly, and in that way it worked fine --> if user was LAURA or LUIS it would redirect to loginSuccess.php and greeted the user, if not, it would redirect to loginFail.php (that's why the headers are commented)
I just want to test that this functions, but when I modified the code to use AJAX, it always fails, even if the user is LAURA or LUIS, it redirects to the loginFail page...
I suspect there is some problem in the success function in the AJAX call.
Any help is appreciated :) Have a nice day!
There's no submit index your $_POST array, so this condition if (isset($_POST['submit'])){ ... will always fail. Remove this conditional check if (isset($_POST['submit'])){ ... } entirely, and refactor your backend PHP code in the following way,
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
?>

image not displaying in my form in php

I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.

How to PHP_SELF in a UI dialog?

So I've been spending hours on finding something specific to my issue, but I can't seem to find any.
I'm in the middle of creating a small CMS. My problem is that I don't know how to make a submitted form in a UI dialog to do the action of PHP_SELF inside of the UI dialog. I have a list of user which can be selected by a radio button. There is a delete button which has some javascript attached:
$('#delete_user').on('click', function(e) {
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
e.preventDefault();
return false;
});
Now, my problem is that I have made it to the UI dialog where i get the ID sent with the url, but I have no idea how to send a form and still keep it in the dialog with the underneath PHP:
<?php
if ((isset($_GET['id'])) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
} elseif ((isset($_POST['id'])) && is_numeric($_POST['id'])) {
$id = $_POST['id'];
} else {
echo "<p>An error has occurred. Please try again.</p>";
echo "Close";
$jQuery_close = <<<msg
<script>
$('.close_dialog').on('click', function(){
location.reload();
dialog("close");
});
</script>
msg;
echo $jQuery_close;
exit();
}
require('includes/db_con.php'); //making a connection to the database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') {
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) {
echo "<p>The user has been deleted</p>";
} else {
echo "<p>The user could not be deleted due to system error. Please try again.</p>";
}
} else {
echo "The user has NOT been deleted!";
}
} else {
$q = "SELECT email, CONCAT(firstname, ' ',lastname) AS name FROM users WHERE user_id='$id'";
$r = #mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if ($num = 1) {
while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)) {
echo "<p>Are you sure you want to delete this user?</p>";
echo $row['email'] . '<br />';
echo $row['name'];
}
echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
<input type="HIDDEN" name="id" value="' . $id .'" />
<input type="submit" name="sure" value="Yes" />
<input type="submit" name="sure" value="No" />
</form>';
} else {
echo "This page has been accessed in error";
}
}
mysqli_close($dbc);
?>
When pressing "yes" or "no" in the form, it just directly goes to a new page.
My question is, how do I fire the php and send the form within the dialog?
Place your e.preventDefault() at the start of the delete click handler, not at the end where you currently have it, it should be like this:
$('#delete_user').on('click', function(e) {
e.preventDefault();
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
return false;
});

Categories