Web server exited unexpectedly, restarting new instance - php

I do not have any other option, but to ask here again... and problem is killing me for the past 5 hours. I got button that call javascript function, and then javascript opens another php page and does insert in MySQL database.
HTML code:
<ul>
<li id="ConfirmButton" name="Insert" onclick="GetAllIDs()"><a>Potvrdi</a></li>
</ul>
Javascript code:
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
http.open('get', 'insert.php?MatchID='+MatchID+'&TipID='+TipID+'&UserID=' + 1,true);
http.send(null);
PHP code:
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$userID = $_GET['UserID'];
// Escape User Input to help prevent SQL Injection
$MatchID = mysql_real_escape_string($matchID);
$TipID = mysql_real_escape_string($tipID);
$UserID = mysql_real_escape_string($userID);
$insertTicket_sql = "INSERT INTO
betslips(DateTime,MatchID,TipID,UserID)
VALUES(".$MatchID.",".$TipID.",'".date("Y-m-d H:i:s")."',".$UserID.")";
$insertTick= mysql_query($insertTicket_sql) or die(mysql_error());
So after I run this code and I use break point I see in my php code all parameters I sent over forms normally and it's all there, but when I reach code $insertTick I get error
web server exited unexpectedly, restarting new instance.
Has anyone seen this problem before, and how can I deal with it?
Thanks

did anyone seen this problem before?
Not me, I dont use the mysql_* functions.
Your INSERT query parameter and values dont match.
So ive ported your example code to PDO perhaps its some interest:
<?php
//PDO Connect
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=yourDB','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
//Check that the variables are set
if(isset($_GET['MatchID']) && isset($_GET['TipID']) && isset($_GET['UserID'])){
//Prepare your query
$query = $con->prepare("INSERT INTO betslips (DateTime,MatchID,TipID,UserID)
VALUES ('".date("Y-m-d H:i:s")."', :matchID, :tipID, :userID)");
//Bind your values with the placeholders
$query->bindParam(":matchID", $_GET['MatchID']);
$query->bindParam(":tipID", $_GET['TipID']);
$query->bindParam(":userID", $_GET['UserID']);
//Execute
$query->execute();
die('Success!');
}else{
die('Error: Parameter not set.');
}
?>

Related

Unable to post API Rest PHP SQLITE

I'm looking for since few days to create a API Restful in PHP to add record on my sqlite database. But when I use POSTMAN to try it, my php code doesn't work, but it's work (with little modifies) with mysql databases.
Could you help me please ? (This code is just a test)
<?php
header('Content-Type: application/json');
try{
$pdo = new PDO('sqlite:database.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$retour["success"] = true;
$retour["message"] = "Connexion OK";
} catch(Exception $e){
$retour["success"] = false;
$retour["message"] = "Connexion impossible";
}
if ( !empty($_POST["ville_depart"]) && !empty($_POST["ville_destination"]) && !empty($_POST["date"]) && !empty($_POST["nb_heure"]) && !empty($_POST["prix"]) ) {
$requete = $pdo->prepare('INSERT INTO api (id, ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES (?, :ville1, :ville2, :date_vol, :nb, :prix)');
$requete->bindParam(':ville1', $_POST["ville_depart"]);
$requete->bindParam(':ville2', $_POST["ville_destination"]);
$requete->bindParam(':date_vol', $_POST["date_depart"]);
$requete->bindParam(':nb', $_POST["nb_heure_vol"]);
$requete->bindParam(':prix', $_POST["prix"]);
$requete->execute();
$retour["success"] = true;
$retour["message"] = "add flight";
$retour["results"] = array();
} else {
$retour["success"] = false;
$retour["message"] = "manque infos";
}
echo json_encode($retour);
// close the database connection
$pdo = NULL;
?>
The result from POSTMAN is not really "speaking", but I can't to find other informations (in the log files) to help me...
[edit to be conform at the previous code]
I think my problem come from my "$_POST" because, when I tried to put some values into the "INSERT" line, that works well.
ex:
$requete = $pdo->prepare("INSERT INTO api (id,ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES ('123', 'LYON', 'TLS', '2019-09-09', '13', '132')");
$requete->execute();

PHP PDO MySQL: Insert statement runs without error, no insert occurs

My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.

HTTP Error 500 when trying to execucute INSERT INTO sql query

I'm fairly new to php and SQL and just can't figure out the problem. Note that this is a school project, therefore the vulnerability to SQL Injections and saving the blank passwords are nothing to worry about.
After the User filled out the Login-form, he's redirected to this page:
[Some html]
<?php
if(isset($_POST['submit']))
{
ConnectSQL();
}
//Retrieve POSTed Login information
$Username = htmlspecialchars($_POST['RegUsername']);
$Email = htmlspecialchars($_POST['RegEmail']);
$Password = htmlspecialchars($_POST['RegPassword']);
function ConnectSQL() {
// SQL Server Extension Sample Code:
// (ConnectionInfo, obviously it's there in the real file)
$conn = sqlsrv_connect($serverName, $connectionInfo);
// PHP Data Objects(PDO) Sample Code:
try {
$conn = new PDO('sqlsrv:server = tcp:xxx.database.windows.net,1433; Database = userdb', 'arechon', '{NotTheRealPassword}');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully connected to SQL Server and DB";
Register();
}
catch (PDOException $e) {
print('Error connecting to SQL Server.');
die(print_r($e));
}
}
function Register($Username, $Email, $Password) {
$regquery = "INSERT INTO dbo.Users (Username, Email, Password) VALUES ('UsernameTest', 'EmailTest', 'PasswordTest')";
$conn->query($regquery);
echo '<script type="text/javascript">window.open("http://xxx.azurewebsites.net/Login.html", "_self");</script>';
The Code always seems to stop at $conn->query($regquery); and doesn't return any error messages. Sometimes it just stops, when I slightly modify the Code (e.g. replacing $conn->query($regquery); with $conn->exec($regquery); or using " instead of ') I get a HTTP500 error.
I found some similiar questions here on stackoverflow as well as on other plattforms, but none of the provided answers could solve this error. Note that I use SQL and NOT MySQL (though it wouldn't be a lot of work to change that if you think that could solve my problem).

sent an object to my server with ajax, cant seem to get the data with php

I have sent two pieces of data to my PHP with this bit of AJAX:
function ajax_post(){
// Create our XMLHttpRequest object
var request = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "php/addUser.php";
var username = document.getElementById("newUserName").value;
var password = document.getElementById("newUserPass").value;
var newUsername = "user_name="+username;
var newPassword="password="+password;
request.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
document.getElementById("output").innerHTML = return_data;
}
};
// Send the data to PHP now... and wait for response to update the status div
request.send({newUsername,newPassword}); // Actually execute the request
This is the PHP code that is supposed to take these two pieces of data and plug it into my mysql database.
//Connect to the database
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
$userName=$_POST['newUsername'];
$userPassword=$_POST['newPassword'];
$query="INSERT INTO users(user_name,password)
VALUES('$userName','$userPassword')";
if ($connection->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $connection->error;
}
$connection->close();
When the AJAX is run, it runs with no errors and sends the data to my PHP code on my server. The PHP code then runs and completes with no errors but then when I check my database the new user is inserted into the database but it is empty. I'm pretty sure it's something in my PHP code, but I haven't figured it out yet.
The argument to request.send() should be a URL-encoded string, not an object.
request.send(newUsername + '&' + newPassword);
Note that you should also use encodeURIComponent when setting the variables, in case they contain special URL characters.
var newUsername = "user_name=" + encodeURIComponent(username);
var newPassword = "password=" + encodeURIComponent(password);
Also, your object syntax was incorrect. The syntax for objects is
{ prop1: value1, prop2: value2, ... }
{ var1, var2 } should have given you a syntax error.
You're also using the wrong $_POST keys. The keys should match the parameter names before =, not the IDs of the form fields.
$userName = $_POST['user_name'];
$userPassword = $_POST['password'];
You should also use a prepared statement in the PHP instead of variable substitution, to prevent SQL injection problems.
$query = "INSERT INTO users (user_name, password) VALUES (?, ?)";
$stmt = $connection->prepare("ss", $userName, $userPassword);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $stmt->error;
}
$connection->close();
You post user_name and password with ajax. But in your PHP code you used $_POST['newUsername'] and $_POST['newPassword']. You can change either the ajax or PHP.
Example:
$userName = $_POST['user_name'];
$userPassword=$_POST['password'];
And your request from ajax should be
request.send(newUsername+"&"+newPassword);

forgot password page in php

I wanted to create a forgot password page. To avoid mailing the user with his details, I decided to display his details in an alert box, although I know that it is much less secure!
So, here's my code in the php file "forgotdetails.php".
//Here are my database details, which I can't show.
$conn= mysql_connect($dbhost, $dbuser, $dbpass);
// Check connection
if(!$conn){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('users');
if(!$db_selected){
die('wrong'.mysql_error() );
}
$post_username = $_POST['email']; // the ajax post username
$query = "SELECT * FROM users WHERE id='". $post_username. "'";
$results= mysql_query($query);
$row=mysql_fetch_assoc($results);
$username=$row['id'];
$password=$row['pass'];
if(mysql_num_rows($results)==0)
{
echo "pass= " . $password;
echo "You haven't registered yet! Go to the Home-Page to Register!";
/*$query = "SELECT * FROM users WHERE id='$post_username' AND pass='$post_password'";*/
}
else
{
echo $password;
echo "Your Login details are-:"."\nUser ID- ". $username . "\nPassword- ". $password . "\nLogin to your account, to change your password. ";
}
And here's my ajax function (inside the html file) which is getting called as the forgot password button is clicked-:
<script lang="javascript" type="text/javascript">
function ajaxFunction1() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function ()
{ if (ajaxRequest.readyState == 4)
{ var ajaxDisplay = document.getElementById('results');
alert (ajaxRequest.responseText);
ajaxDisplay.innerHTML = "<br/><br/><h2><font color='#18E618'>"+ajaxRequest.responseText+"</font></h2>"; } }
// Now get the value from user and pass it to
// server script.
var email = document.getElementById('email').value;
//var bitsmailid = document.getElementById('bitsmailid').value;
if ( email== "" || email== null || email== '') {
alert("BITS ID Not Filled");
exit();
}
/*if ( bitsmailid== "" || bitsmailid== null || bitsmailid== '') {
alert("BITS Mail ID Not Filled");
exit();
}*/
var queryString = "?email=" + email;
ajaxRequest.open("POST", "forgotdetails.php" +queryString, true);
ajaxRequest.send(null);
}
</script>
My query is that, the I need to check whether the query returned through SQL in the PHP File ($results) is empty or not and then I need to perform the functions as i have mentioned in my code. I have used mysql_num_rows($results)==0 condition (which I got to know after reading similar posts on Stack Overflow). Although it doesn't seems to evaluate correctly. It evaluates true always, even though there are entries in the database.
I have read all the posts concerning this type of questions on Stack Overflow, and after 12+ hours of testing the code with many different possibilities, still I am still unable to solve my query. I have provided all the details necessary for my query, however If anyone needs anything, I will provide them with you.
I am a newbie into Web Development, so please help me to solve my query. Thank You in advance for your Help!
I am sorry if you feel that this question has already been answered earlier, however I posted this again because those posts sadly couldn't help me. I have read all of them. Sorry!
It should be
$sql = "SELECT * FROM users WHERE id='". $post_username. "'";
$result = mysql_query($sql, $conn);
if ($result && (mysql_num_rows($result) > 0)) {
// user exists
// here you get row
$row = mysql_fetch_assoc($result);
}
I know it is without pdo and it is insecure.

Categories