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');
Related
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?
Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend
I want to display a message after a record has been successfully deleted. I tried everything but without success.
I have an external js file from which I call a PHP file that deletes the record.
JS file:-
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
ShowGoals();
}
);
var jsuccess = $("#myPhpValue").val();
console.log(jsuccess);
}
PHP file:-
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goal_id = $_POST['goalid'];
// $query = "DELETE from goals where user_id = '$userid' AND goal_id='$goal_id'";
// if (!$result = $mysqli->query($query)) {
// exit(mysqli_error($mysqli));
// }
$success = "true";
echo '<form><input type="hidden" id="myPhpValue" value="'.$success.'"/></form>';
mysqli_close($mysqli);
}
?>
I tried to send the $success variable back to js file with several ways but none worked. It seems that any output command (echo, alert, console.log) doesn't display anything and I don't know why.
I would appreciate any help!
You could simply return using echo and display the response directly :
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
...
echo true;
}
?>
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (response) {
if( response ){
// reload goals
ShowGoals();
console.log("Success message");
}
}
);
}
You could return a json format what gives you the ability to return multiple info like :
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data) {
var response = $.parseJSON(data);
if( response.success ){
// reload goals
ShowGoals();
console.log(response.message);
}
}
);
}
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
echo jdon_encode(['success'=>true,"message"=>"Deleted Successfully"]);
}
?>
finally I did it!
PHP file
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goalid = $_POST['goalid'];
$query = 'DELETE from goals where userid ='.$userid.' AND goal_id='.$goalid;
if (!$result = $mysqli->query($query)) {
exit(mysqli_error($mysqli));
}
$data = true;
echo($data);
mysqli_close($mysqli);
}
?>
JS file
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
if (data==true && status =="success")
ShowGoals();
else
alert("Problem");
}
);
}
So, I return what happen using data variable.
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
This piece should create a csv file. The method that is calling to the nonAjaxPost is:
function exportCSV()
{
nonAjaxPost('getExport', 'post', {action: '/getView', 'view': current_pi, 'parameters': encodeURIComponent(JSON.stringify(current_parameters))});
}
function nonAjaxPost(action, method, input) {
"use strict";
var form;
form = $('<form />', {
action: action,
method: method,
style: 'display: none;'
});
if (typeof input !== 'undefined') {
$.each(input, function (name, value) {
$('<input />', {
type: 'hidden',
name: name,
value: value
}).appendTo(form);
});
}
form.appendTo('body').submit();
}
My problem is that i just can't seem to understand how this is going to create a csv file for me. I'm probaly missing out on something that i just can't see.
I really hope someone could help me out.
Update:
This is the getExport function:
$databundle = $this->_getData();
$data = $databundle['rows'];
$columns_all = $databundle['columns'];
$columns = array("Id");
foreach($data[0] as $key => $column) {
$column = "";
$found = false;
foreach($columns_all as $col_search) {
if($col_search['key'] == #$key) {
$found = true;
$column = $col_search['title'];
break;
}
}
if($found) {
//echo $key . ",";
$columns[] = $column;
}
}
$contents = putcsv($columns, ';', '"');
foreach($data as $key => $vals) {
if(isset($vals['expand'])) {
unset($vals['expand']);
}
array_walk($vals, '__decode');
$contents .= putcsv($vals,';', '"');
}
$response = Response::make($contents, 200);
$response->header("Last-Modified",gmdate("D, d M Y H:i:s") . " GMT");
$response->header("Content-type","text/x-csv");
$response->header("Content-Disposition","attachment; filename=".str_replace(" ","_",$databundle['title'])."_".date("Y-m-d_H:i").".csv");
return $response;
It also calls the getData function which is this:
$viewClass = str_replace('/', '', (isset($_POST['view']) ? $_POST['view'] : $_GET['view']));
$fileView = '../app/classes/view.'.$viewClass.'.php';
if(file_exists($fileView))
{
require_once($fileView);
$className = 'view_'.$viewClass;
if(class_exists($className))
{
$view = new $className();
//Seek for parameters
if(isset($_REQUEST['parameters']))
{
//Decode parameters into array
$parameters = json_decode(urldecode((isset($_POST['parameters']) ? $_POST['parameters'] : $_GET['parameters'])),true);
//Get supported parameters
$parameterTypes = $view->getVars();
$vars = array();
foreach($parameterTypes as $key => $type)
{
//If a value is found for a supported parameter in $_GET
if(isset($parameters[$key]))
{
switch($type)
{
case 'int':
$vars[$key] = intval($parameters[$key]);
break;
case 'float':
$vars[$key] = floatval($parameters[$key]);
break;
case 'filterdata':
// todo: date validation
$vars[$key] = $parameters[$key];
break;
}
}
}
$view->setVars($vars);
}
return $view->getData();
}
else {
/*
header('HTTP/1.1 500 Internal Server Error');
echo 'Class ' . $className . ' does not exist.';
*/
return false;
}
}
else {
/*
header('HTTP/1.0 404 Not Found');
die('Cannot locate view (' . $fileView . ').');
*/
return false;
I hope this is sufficient.
In short what i am trying to find out is that the csv that it produces has more columns than columns headers and where the difference comes from
My guess would be that the page you are calling (on the server) is generating the CSV file.
You would need to write code on the server to do the conversion.
This method is making a post request to getView page. Your csv create code would be present on getView page.
This is the front end code that creates an invisible form with your data: current_parameters.
See the content of current_parameters in the the current file.
Review back-end code and look for the "getExport" function (it should be the current php file loaded)
If you just copied this function from some example... you have to add also the back-end code on your own.
Update:
look at the getExport code:
$contents = putcsv($columns, ';', '"');
$contents .= putcsv($vals,';', '"');;
First row insert the titles , and the second loops the data and insert the other rows.
Print the content of $columns and $vals and see what is happening.
There are some strange conditions for filtering the columns... but can help you if you don't show the data you try to parse.