I'm making a script for a photographer website. We need to send pictures to the server via a PHP file. For info the host doesn't allow to modify php.ini.
So, the thing is: If I send files from my connection (fiber) everything works weel. But my friend doesn't have fiber. So I limited my bandwidth to 10MB/S. And there it's not working: the file is sent (around 17 sec execution) then I got a canceled request return.
Here is my angular code:
public sendFile(file: File): Observable<any> {
const formData = new FormData();
formData.append('thumbnail', file);
formData.append('action', 'uploadImage');
formData.append('pass', this.savedPass);
formData.append('format', file.type.replace('image/', ''));
return this.http.post<any>(environment.upload_address, formData, {
reportProgress: true,
observe: 'events',
headers: new HttpHeaders({ timeout: `20000` }),
});
}
And here is my PHP code (working weel with my fiber, so it must be something around max execution time):
<?php
ini_set('max_execution_time', '300');
set_time_limit ( 300 );
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function checkAdmin($pass) {
include $_SERVER['DOCUMENT_ROOT']."/creds.php";
if(isset($pass) && !empty($pass) && $pass === $admin_pwd){
return true;
}
return false;
}
function generateKey($length){
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$toReturn = '';
for($i = 0; $i < $length; $i++){
$newChar = $chars[random_int(0, strlen($chars))];
$toReturn .= $newChar;
}
return $toReturn;
}
function execQuery($query) {
include $_SERVER['DOCUMENT_ROOT']."/creds.php";
$mysqli = new mysqli($db_host.":".$db_port, $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$result = $mysqli->query($query);
if(is_bool($result)){
return [];
}
// Fetch all
$toReturn = [];
while($row = $result->fetch_assoc()){
array_push($toReturn, $row);
}
$mysqli->close();
return $toReturn;
}
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: *");
$allowed_types = [
'image/jpg',
'image/jpeg',
'image/png'
];
$isAdmin = false;
if(isset($_POST['pass']) && !empty($_POST['pass'])){
$isAdmin = checkAdmin($_POST['pass']);
}
if($isAdmin && isset($_FILES) && !empty($_FILES) && isset($_FILES['thumbnail']) && !empty($_FILES['thumbnail']) && in_array($_FILES['thumbnail']['type'], $allowed_types)){
$newKey = generateKey(10);
while(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.'photos/'.$newKey.'.'.$_POST['format'])){
$newKey = generateKey(10);
}
move_uploaded_file($_FILES['thumbnail']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/'.'photos/'.$newKey.'.'.$_POST['format']);
execQuery('INSERT INTO pictures (code, title, active) VALUES ("'.$newKey.'.'.$_POST['format'].'", "", 0)');
}
Does someone have asolution?
Related
I 'm working at with XAMPP server at my home pc.My files are in xampp/htdocs/marfo I am trying to fetch some records in a booking database lying on xampp\mysql\data\marfo. Althought i can read all others tables of the same database (using different files at the same directory) this specific table gives me this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/xampp/htdocs/marfo/booking.php. (Reason: CORS request not http)."
the code in js is:
function readres() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responceText != "NoResults") {
reservarray = JSON.parse(this.responseText);
// function to set whole site for this language
} else { return "Bad thing !!! Something went wrong .........." }
} else { return "Didn't found anything malaka.........." }
}
xmlhttp.open("GET", "booking.php", true);
xmlhttp.send();
}
and the code at PHP file:
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'marfo';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM bookings";
$result = $conn->query($sql);
$counter = 0;
if ($result->num_rows > 0) {
// output reservations
while ($row = $result->fetch_assoc()) {
$reservarray = array(
"datefrom" . $counter => $row["datefrom"], "dateto" . $counter => $row["dateto"], "name" . $counter => $row["name"]
);
$counter = $counter + 1;
}
echo json_encode($reservarray);
} else {
echo 'No results';
}
$conn->close();```
any help appreciated....
I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school
I have an angularjs service that sends a rest api link to a php file, the problem is that , this php file is calling another php file which contains a javascript code. When I execute the code in the service, it executes the php file , but the javascript code is just printed out without being executed. It's been a whole day of research but without any solution. Please can you tell me where the problem is? I have used require 'secondFile.php'; and include 'secondFile.php'; , I have also tried to bring the whole javascript code from the second file to the first file, so that I call the javascript locally, but it always prints the code without executing it.
Here is my code:
The angularjs service function:
var link = 'http://path/to/first.php';
$http.post(link, {idf : newDoc.idf})
.success(function (res){
console.log(res);
}).error(function (err) {
console.log(err);
});
the first php file, which is a remote file
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$method = $_SERVER['REQUEST_METHOD'];
//$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
var_dump($request);
$idf= $request->idf;
$val= $request->val;
switch ($method) {
case 'POST':
insertit($idf, $val);
break;
case 'PUT':
updateit();
break;
case 'REMOVE':
removeit();
break;
}
}
catch(PDOExecption $pe) {
echo "okay";
print "ERROR!".$pe->getMessage();
die();
}
function insertit($idf, $val) {
include 'connect.php';
$dataBilan = array($val);
$stmt = $DB->prepare("INSERT INTO `Test` (val) VALUES (?)");
$stmt->execute($dataBilan);
$last = $DB->lastInsertId();
$idf= $last;
$info_bilan= array(
'val' =>$val
);
$data = array(
'idf'=>$last,
'action'=>'update',
'table'=>'activite',
'data' =>$info_bilan
);
require 'second.php';
echo "okay done inserting";
}
and second.php:
<script src="pouchdb-5.3.1.min.js"></script><script type="text/javascript" language="javascript">
var dbRemote = new PouchDB('http://localhost:5984/Mydatabase');
var myDocs;
var value = <?php echo json_encode($data); ?>;
console.log(JSON.stringify(value));
if((value.idf != null) && (value.idf != 0))
{
console.log("-------here we go----");
dbRemote.allDocs({include_docs: true}).then(function (res) {
myDocs = res.rows.map(function (row) {
return row.doc; });
onUpdate(value);
});
}
}
function binarySearch(arr, docId) {
var low = 0, high = arr.length, mid;
while (low < high) {
mid = (low + high) >>> 1; // faster version of Math.floor((low + high) / 2)
arr[mid].id < docId ? low = mid + 1 : high = mid
}
return low;
}
function onUpdate(value)
{
console.log("couchdb's "+ myDocs.length);
if(myDocs.length !=0)
{
console.log("haha");
var index = binarySearch(myDocs, value.idf);
var doc = myDocs[index];
if(action== "update")
{
dbRemote.put(doc).then (function () {
console.log("Updated! ");
}).catch(function (err) {
console.log(err);
});
}
}
}
</script>
The content of second.php file is just printed out but it's not executed. When I execute first.php everything goes right , but when I execute the service I just see the printed file. Please any ideas?
Example:
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
I have made the login page using ionic and it seems to work well. The $_SESSION variable also gets displayed after successfull login. Then in another php file, when I try to print the same session variable, it shows undefined or not set. Also, the session expires after refresh and it shows an alert to login again
Here is my login php code
<?php
ob_start();
session_start();
$errmsg_arr = array();
$errflag = false;
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
require_once 'db_functions.php';
$db = new db_functions();
if(empty($_POST['doc_key']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else if(empty($_POST['password']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else
{
$doc_key = $_POST['doc_key'];
$password = $_POST['password'];
$user = $db->getDoctorByEmailAndPassword($doc_key, $password);
if( $user == true)
{
//session_regenerate_id();
$_SESSION['name'] = $user["name"];
$_SESSION['contact'] = $user["contact"];
$_SESSION['email'] = $user["email"];
$_SESSION['license_no'] = $user["license_no"];
$_SESSION['type'] = $user["type"];
$_SESSION['gender'] = $user["gender"];
$_SESSION['location'] = $user["location"];
$_SESSION['fees'] = $user["fees"];
$_SESSION['experience'] = $user["experience"];
$_SESSION['doc_key'] = $user["doc_key"];
//session_write_close();
$data['message'] = $_SESSION['name'];// "User logged in successfully";
echo json_encode($data);
}
else
{
$data['errors'] = 'Login Credentials are invalid';
echo json_encode($data);
}
}
?>
This is the code of other page where I want to display the session variable
<?php
ob_start();
session_start();
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$data = array();
$type_user = "";
if(isset($_SESSION['user_name']) || isset($_SESSION['license_no']))
{
if($type_user == "doctor")
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["license_no"] = $_SESSION["license_no"];
$data["doc_key"] = $_SESSION["doc_key"];
$data["gender"] = $_SESSION["gender"];
$data["type"] = $_SESSION["type"];
$data["location"] = $_SESSION["location"];
$data["fees"] = $_SESSION["fees"];
$data["experience"] = $_SESSION["experience"];
echo json_encode($data);
}
else
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["gender"] = $_SESSION["gender"];
$data["user_name"] = $_SESSION["user_name"];
echo json_encode($data);
}
}
else
{
$data["errors"] = "Please login first to see this";
echo json_encode($data);
}
?>
This page does not return the session data to controller. It shows blank
Here are the codes of controllers and ionic code
Controller for login page
.controller('doctorloginCtrl', function($scope,$http,$window) {
$scope.doctor = {};
$scope.loginDoc = function(){
$http({
method: 'POST',
url: 'http://localhost/drmedic/login_doctor.php',
data: $scope.doctor,
headers: {'ContentType': 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(data.errors)
{
alert(JSON.stringify(data.errors));
}
else
{
alert(JSON.stringify(data.message));
$window.location.href = "#/home";
}
});
}
})
Controller for the other page where I want to show the details
.controller('profileCtrl', function($scope,$http,$ionicSideMenuDelegate,$window) {
$ionicSideMenuDelegate.toggleLeft();
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_login_details.php'}).success(function(data) {
if(data.errors)
{
alert(data.errors);
$window.location.href = "#/select-role";
}
else
{
$scope.contents = data;
console.log($scope.contents);
}
});
})
After login, when I go to the profile page by typing localhost:8100/#profile, it shows blank.. It does not display the {{contents.name}} field
IONIC CODE for Profile page
<ion-view title="Profile">
<ion-content overflow-scroll="true" padding="true" scroll="false" class="has-header">
Hi {{contents.name}}
</ion-content>
</ion-view>
The sessions used to work properly for my other project. Can't figure it out why it isn't working for this one. Is it because of the Authentication-Allow-Cross headers??
Please help.
Use Javascript localStorage Property. It will store data in your device until you remove it. So this is very easy to keep some data in the device. You can acccess it from anywhere in your code if it is exists.
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
for more information visit https://www.w3schools.com/jsref/prop_win_localstorage.asp
Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.