#mention and text or no #mention and text - php

I'm having a little issue with my php file and wondering if somebody can take a look.
If I update with an #mention and some text with the php below it will update the database and output the ajax. If it doesn't have an #mention and just text, it outputs nothing. How can I rectify the code to do both.
They are both contained with $_POST['newmsg'];
I have yet to escape my variables to prevent SQL injection.
PHP:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
session_start();
require_once "rawfeeds_load.php";
include_once "include/functions.youtube.php";
?>
<?
if(isset($_SESSION['id'])){
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])&& isset($_POST['red'])){
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}
}
PHP USER_CORE
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser,$date){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$date=date('y:m:d H:i:s');
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,'$date','$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser=rawfeeds_user_core::getuser($creatorid);
rawfeeds_user_core::add_notification(2,$_POST['toid'],$fromuser['id'],$fromuser['fullname']." posted a status on your wall","../singlepoststreamitem.php?sid=$last_id");
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
}
AJAX
$("form#myforms").submit(function(event) {
event.preventDefault();
var content = $(this).children("#toid").val();
var newmsg= $(this).children("#newmsg").text();
var username = $(".red").attr("href");
var privacy = $("#privacy").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg, privacy: privacy, red: username },
success: function(response){

Move the check for $_POST['red'] out of the main check:
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])){
// remove $_POST['red'] here -^
if (isset($_POST['red'])) { // check it here, otherwise your insert will not happen if $_POST['red'] is empty.
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
}
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}

Related

How do I apply today's date to images uploaded with ajax and php.

I have been searching the site for a solution and I found a few, but I do not know how to apply it to the code I am using. I want to add the date & time to the images uploaded by the user.
This is my PHP Page that I am ajaxing the image to.
<?php
session_start();
include_once("db_connect.php");
$username = $_SESSION['username'];
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "uploads/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
$sql = "UPDATE users4 SET profile_photo = '".$targetPath."' WHERE username = '".trim($username)."' ";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
?>
<div style="background-position: center;;height:155px;width:240px;background-image: url(<?=$targetPath?>);background-size: 100% auto;background-repeat: no-repeat;border-radius: 8px;" ></div>
<?php
}
}
}
?>
This my AJAX FUNCTION
$.ajax({
url: "uploadajax.php",
type: "POST",
data: new FormData(this),
beforeSend: function(){
$(".spinner4").show();
$(".fa-check").hide();
$(".upload-preview").hide();
},
contentType: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#targetLayer").css('opacity','1');
setInterval(function() {
$(".spinner4").hide();
$(".fa-check").delay(3000).fadeIn(200);
$(".button-bottom-container").fadeIn();
},500);
},
error: function()
{
}
});
So I have tried applying.
<?php
if (move_uploaded_file($tmp_name, $location.time().'_'.$name)) {
echo 'file uploaded! ';
}
?>
But with no success. I don't really know where to apply the "time()" function in my code to make it work. Any ideas? I'm sure this is a simple one.
I'm pretty sure the change needs to happen within
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "uploads/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
but, nothing I try is working. Yet... Thanks if you have some help to offer.
You can just use strtotime()
$targetPath = "uploads/".strtotime("now")."_".$_FILES['userImage']['name'];
To convert back use date("d-m-Y H:i:s", $time);
<?
$file_path = "some/directory/1501113258_file.jpg";
$part = explode ("_", basename($file_path));
$date_time = date ("d-m-Y H:i:s", $part['0']);
// will output 26-07-2017 23:54:18
?>

Cordova jquery ajax post to server php file

I want to compare input value of the input in the cordova app to an table in my database.
This is my jquery ajax post:
$('.postToken').click(function(){
console.log($('.valueToken').val());
var tokenValue = $('.valueToken').val();
$.ajax({
type: "POST",
url: "http://example.com/fysioWebapp/php/get_schema.php",
data: { dataString: tokenValue },
cache: false,
success: function(){
alert("Order Submitted");
}
});
and this is my get_schema.php on server:
<?php
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
var_dump($stringData);
?>
But it returns me null I first type in value data in my cordova app and then refresh the php page but keeps returning me null. Could somebody help me out on this issue?
Edit:
You need to see if the value exists in the database table like this
<?php
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
$checkToken = "SELECT * FROM Exercises WHERE YOUR_FIELD_NAME = ('$stringData')";
$checkResult = mysqli_query($conn, $checkToken);
if (mysqli_num_rows($checkResult) > 0) {
echo "Result already exists";
} else {
echo "0 results";
}
?>
Replace YOUR_FIELD_NAME for the column name you use for tokens.
The javascript I have already provided will console log wether or not the token exists.
Original
When you refresh the php file $stringData will be undefined.
Try this.
$('.postToken').click(function(){
console.log($('.valueToken').val());
var tokenValue = $('.valueToken').val();
$.ajax({
type: "POST",
url: "http://example.com/fysioWebapp/php/get_schema.php",
data: { dataString: tokenValue },
cache: false,
success: function(data){
console.log(data);
alert("Order Submitted");
}
});
});
This should console log the result of the var_dump.
If not change this line of the php file.
var_dump($stringData);
To.
echo var_dump($stringData);
You cannot just use ajax in your cordova app because of cross domain issues. Either you have to setup your server or php to get it or you can use jsonp.
For ajax solution you can try this on your php:
<?php
header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: origin, referer, content-type");
header("Access-Control-Max-Age: 1728000");
if(strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS'){
header("Content-Type: text/plain");
header("Content-Length: 0");
http_response_code(204);
exit;
}
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
var_dump($stringData);
?>

Warning:session_start() [function.session-start]: Cannot send session cookie - headers already sent by

i want to create a search functioanlity for my real estate website.here i have created search criteria and to fullfill this criteria i have used a jax call. this ajax will call php file and that file will send data to search page . here is my sample code. i dont know what issue is there.
thanks in advnce
function searchBuy() {
//alert("search Loaed");
$.ajax({
url: 'searchBuyCriteria.php',
type: 'POST',
//dataType: "json",
data: {
cat: $('#SelectCat').val(),
MaxArea:$('#SelectMaxArea').val()
}
}).success(function(data){
console.log("Success"+data);
alert(JSON.stringify(data));
}).error(function(data){
console.log("Error"+data);
});
} </scipt>
searchCriteria.php
<?php
include_once('_secure/conn.php');
$city = $_POST['SelectCity'];
$cat= $_POST['SelectCat'];
$rooms = $_POST['SelectRooms'];
$minRange = $_POST['SelectMinRange'];
$maxRange = $_POST['SelectMaxRange'];
$minArea = $_POST['SelectMinArea'];
$maxArea = $_POST['SelectMaxArea'];
$conn=mysql_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME);
mysql_select_db(DB_NAME);
$Searchqry ="Select * from tblcategory where category_title like '%".$cat."%' ";
$searchExec = mysql_query($Searchqry) or die(mysql_error());
$searchRow = mysql_fetch_array($searchExec);
//echo $searchRow;
echo json_encode($searchRow);
?>
conn.php
<?php
session_start();
ob_start();
if(!isset($path))
$path="./";
elseif($path=="")
$path="../";
require_once("settings.inc.php");
$database='srijanip';
$user='srijanip';
$pass='********';
$host='example.*****.in';
define("DB_HOST", "$host");
define("DB_NAME", "$database");
define("DB_USER", "$user");
define("DB_PWD", "$pass");
?>

Jquery, php ajax post 500 Internal Server Error returns

I have some problem with jquery ajax & php. I'm not good in php, but I have to create a login page with php.
The promblem is, when I try to get some information from the server I get server error insted of the value.
Here is my php code (if someone know better method to create login on server side, please correct me):
<?php
//$link = mysql_connect('localhost', 'root', '') or die('A kapcsolódás nem sikerült: '+mysql_error());
$link = mysql_connect("127.0.0.1", "qm", "soR624gA") or die("Nem sikerült kapcsolódni az adatbázishoz!"+mysql_error());
mysql_query("SET NAMES UTF8");
mysql_select_db("qm", $link);
$uname = mysql_real_escape_string($_POST['name']);
$pass = mysql_real_escape_string($_POST['pass']);
$fetch = mysql_query("SELECT * FROM felhasznalok WHERE nev ='{$uname}' AND jelszo = Sha1('{$pass}')") or die(mysql_error());
if (mysql_num_rows($fetch) == 1) {
$a = array();
$['true'] = 'true';
echo json_encode($a);
}else{
$a = array();
$['true'] = 'true';
echo json_encode($a);
}
?>
And here is the code of the login on the client side:
function handleLogin(){
var _url = preUrl + "login.php";
var name = $("#loginForm #name").val();
var pass = $("#loginForm #pass").val();
$.ajax({
type: 'POST',
url: _url,
data: {name: name, pass: pass},
dataType: 'jsonp',
beforeSend: function(){
if((!name) || (!pass)){
notify('error','Kérlek tölts ki minden adatot!');
return false;
}else{
$("#loginForm #loginBtn").prop("disabled", true);
}
},
success: function(data){
if(data[0].true == 'true'){
window.localStorage["username"] = name;
window.localStorage["password"] = pass;
$.mobile.changePage("#wall",{transition:"slide", reverse:false});
}else{
$('#loginForm #name').val("");
$('#loginForm #pass').val("");
notify('error','Hibás adatok!');
}
},
error: function(err){
//átírni ha a cordovajs be lesz szúrva!!!
alert('Hiba: '+err.message);
}
});
$("#loginForm #loginBtn").prop("disabled", false);
return false;
}
I tried it out on different servers but nothing changed. I only get the error.
You made a typo:
$['true'] = 'true';
Should probably be
$a['true'] = true;
(note the $ a )
Also note that whether your login would succeed or not, it will always fill that 'true value' with true. Looking at your Javascript, that's not what you want. Consider setting it on false in your else statement.
learn basic php: $['true'] = 'true'; is a flat-out syntax error. this is the most likely cause of your server 500 error.
Add string like that to see errors in your php script:
error_reporting(E_ALL);
ini_set('error_log', 'path_to_log_file');
ini_set('log_errors_max_len', 0);
ini_set('log_errors', true);

I need a help with this script ($.ajax())

Ajax:
$.ajax({
url: 'process.php',
type: 'post',
data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(),
dataType: 'json',
success: function(data){
if(data.success)
{
location.href = data.redirect;
}
else
{
alert(data.message);
}
}
});
And here is process.php code:
<?
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "test" && $_POST['loginPass'] == "test")
{
$data['redirect'] = "home.php";
$data['success'] = true;
echo json_encode($data);
}
else
{
$data['message'] = "<div id=Message>Your info is wrong...</div>";
$data['success'] = false;
echo json_encode($data);
}
}
?>
Sorry, but I'm from the Czech Republic and I don't speak english :D
Your data: misses a & right before loginPass=, which would lead to a garbled request. But maybe you should give jQuery an data object there anyway (it takes care of proper url encoding):
type: 'POST',
data: {loginName: $("#loginName").val(), loginPass: $("#loginPass").val()},
A second problem might be the lack of content-type in the php script. Add following on top (just to be sure this isn't why the result goes ignored):
<?php
header("Content-Type: application/json");
Another thing: You need more braces in the if statement, because && has higher precedence than the == comparison:
if(($_POST['loginName'] == "test") && ($_POST['loginPass'] == "test")) {
Since it is seemingly a PHP error, you must turn on error_reporting(E_ALL) and display_errors in the php.ini; If you still get no content returned from your URL, then add a print 'test123'; on top. And/or remove the test for REQUEST_METHOD (this adds no security anyway).

Categories