How can I take command input using php with shell_exec() - javascript

I am working on a project that takes users c++ code as input and compiles it from the server and sends the output to the user.
But here, If the c++ code has something like taking input from the user then that time my code fails. I want to do something from which I can take users input also on my website.
This is my php code -
<?php $code = $_POST['code']; if($_SERVER['REQUEST_METHOD'] == "POST"){
$md5hash = md5($code);
$filename = $_SERVER['DOCUMENT_ROOT'] . "/code/" . $md5hash . ".cpp";
$filexe= $_SERVER['DOCUMENT_ROOT'] . "/code/" . $md5hash . ".exe";
$dir = $_SERVER['DOCUMENT_ROOT'] . '/code';
//this will make the directory if the directory is not present
if ( !file_exists($dir) )
{
mkdir ($dir, 0777);
}
$myfile = fopen($filename,"w") or die("Unable to open file!");
fwrite($myfile,$code); //Store the user submitted code into a file
fclose($myfile);
$command1 = "C:\TDM-GCC-32\bin\g++ " . $filename . " -o ". $filexe;
$output1 = shell_exec($command1 . " 2>&1");
$output = shell_exec($filexe . " 2>&1");
$input =
if(empty($output1)){
echo $output;
}else echo $output1; } ?>
This is my index.php code
<center><textarea name="code" id="code" placeholder="Enter your C++ source code here.. " rows="15" cols="100%" style="padding:10px;font-size:18px"></textarea></center>
<center><button onclick="runcode();" style="cursor:pointer;padding:5px;display:flex;align-content:center;text-decoration:none;justify-content:space-around;background:brown;color:white;width:50%;">Run code</button>
Output -
<div>
<center><textarea placeholder="waiting.... " rows="15" cols="100%" style="padding:10px;font-size:18px" id="out"></textarea></center>
</div>
<center>Fix Bug on this code!
<?php include 'components/_footer.php' ?>
<script>
function runcode(){
document.getElementById('myoutput').setAttribute("class","show");
$codevalue= document.getElementById('code').value;
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("out");
serverResponse.innerHTML = this.responseText;
};
xhr.open("POST","runcode.php");
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("code="+$codevalue);
}
</script>
I search on internet but couldn't find a better solution please help me to take the input from the user and showing the output to user also user should be able to put there input incase some program ask for user input

Related

How to create a text file using php from the parameters passed to html page in url?

I need my page bargraph.html to get parameters like .../bargraph.html?di=xxxx&mn=yyyy and save the values of di and mn using a php script in a text file named cred.txt. The code I'm using for bargraph.html is
<body>
<?php
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$location = "cred/".$file_name;
$text = $mobile_num."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
?>
</body>
The file named cred.txt is not created inside the cred/ directory and neither I get any errors. What am I doing wrong?
If the same thing can be done using JavaScript I'll use that instead of php for this purpose.
The question references bargraph.html - presumably the php code that you have is NOT on that page but a separate script? If that is the case then if you were to use exception handling to try to track down the issue it might help. Also, I have always found better success when using full paths as opposed to relative ones
<?php
if( isset( $_GET['mn'], $_GET['di'] ) ){
try{
$filename='cred.txt';
$mobile_num=filter_input( INPUT_GET, 'mn', FILTER_SANITIZE_STRING );
$device_id=filter_input( INPUT_GET, 'di', FILTER_SANITIZE_STRING );
/*
I have always found it is best to use a full path rather than relative
Change `path/to/` to the appropriate path
*/
$path=$_SERVER['DOCUMENT_ROOT'] . '/path/to/cred';
/* If the path does not exist, warn user */
if( !realpath( $path ) ){
throw new Exception( sprintf( 'Unable to find path: %s', $path ) );
}
/* Can the chosen directory be read? */
if( is_readable( $path ) && is_writable( $path ) ){
$file=$path . '/' . $filename;
#$text=$mobile_num . PHP_EOL . $mobile_num . PHP_EOL;
/* I think this is probably what you intended? */
$text=$device_id . PHP_EOL . $mobile_num . PHP_EOL;
$status=file_put_contents( $file, $text, FILE_APPEND | FILE_TEXT );
throw new Exception( $status ? sprintf('All good! Saved %s',$file) : sprintf('Error - unable to save %s',$file) );
} else {
/*
should set permissions if reading/writing of target folder failed
chmod($path,0777); etc
*/
throw new Exception( sprintf( 'The path %s is either not readable or writable',$path ));
}
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
?>
Using a plain HTML page you could send an ajax request to the above PHP script ( in code below called bargraph.php )
<html>
<head>
<title>ajax-store credentials</title>
</head>
<body>
<form id='bg'>
<input type='text' name='mn' id='mn' placeholder='Mobile number: eg 0141 353 3874' />
<input type='text' name='di' id='di' placeholder='Device ID: eg yellow banana' />
<input type='button' id='bttn' value='Go' />
</form>
<script>
document.getElementById('bttn').onclick=function(e){
var mn=document.getElementById('mn').value;
var di=document.getElementById('di').value;
if( mn != '' && di != '' ){
var xhr=new XMLHttpRequest();
xhr.onload=function(r){
document.getElementById('status').innerHTML=this.response;
};
xhr.onerror=function(r){
document.getElementById('status').innerHTML=err.message;
};
xhr.open('GET','?mn='+mn+'&di='+di,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
}
</script>
<div id='status'></div>
</body>
</html>
You can do like this.
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$path = getcwd();
$location = $path.'/cred/'.$file_name;
$text = $device_id."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
You need to give write permission on cred folder.

generate unique link that runs an images slider with different images

i searched all over the web and i couldn't find an answer, please help me!.
I have an HTML form, like this one:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="folder_name" placeholder="Folder name">
<input type="submit" value="Submit">
</form>
Now, upload.php takes number of images and store a link to the folder in MySQL.
Then i call query.php through angularJS $http to retrieve the link to the folder + the images.
Here is query.php:
session_start();
include 'connection.php';
header("Content-Type: application/json; charset=UTF-8");
$folder = $_SESSION["target_folder"];
$query = "SELECT * FROM links WHERE link LIKE '%$folder%'";
$stmt = $db->prepare($query);
$stmt->execute();
$imagesArray = [];
$images = [];
$response = "";
$imageArray = "";
$first_response = "";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images = unserialize($row["images"]);
$imagesArray = explode(",", $images);
foreach($imagesArray as $image) {
if ($response != "") {$response .= ",";}
$response .= '{"target_folder":"' . $row["link"] . '",';
//$response .= '"ext":"' . $row["ext"] . '",';
$response .= '"billboardNumber":"' . $image . '"}';
}
}
$response ='{"records":['.$response.']}';
echo $response;
Last is the slider in slider.html that retrieves the JSON data from query.php:
$http.get("php/query.php")
.success(function (response) {
$scope.slides = response.records;
});
Most important part, my question :-)
every time i run slider.html it overwrites the old slider.html link and outputs the images from the last JSON call.
how can i run slider.html for a month and still get to the same folder even if i generate another 1000 links to different folder.
i hope that someone will understand me :-)
thank you !!!

Storing a value of a variable in a text file

I have created a simple mechanism to grab a persons First and Last name (this is of course the very basic code). However I want to write the value of a variable to a text file. I have used some php, however it does not seem to work:
<?php $handle = fopen("log.txt", "a");
foreach($_GET as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
Therefore, I was wondering if there was any of code I could use to place this information into the text file? Your help is appreciated.
Initial code:
<head>
<script>
function getDetails()
{
var firstName = document.getElementById("firstName");
var nameElement = document.getElementById("lastName");
var theName = firstName.value;
var theLastName = lastName.value;
document.getElementById("someDiv").innerHTML += theName += theLastName;
}
</script>
</head>
<html>
<div id="someDiv">
Details:
</div>
<br><br>
<input id="firstName" type="text">
<input id="lastName" type="text">
<input type="button" value="Go!" onClick="getDetails();">
<br>
</html>
I would however prefer Javascript.
To write on a file via php, you can use the file_put_content() function.
Here's a simple code example:
// The file where to write
$file = 'db.txt';
// The content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content);
You can also append content to the file:
// The file where to write
$file = 'db.txt';
// Old content
$file_content = file_get_contents($file);
// Old + new content
$file_content .= $your_variable;
// Write the content
file_put_contents($file, $file_content);
You can also append to a file file_put_contents flags:
// The file where to write
$file = 'db.txt';
// New content
$file_content = $your_variable;
// Write the content
file_put_contents($file, $file_content, FILE_APPEND | LOCK_EX);
// FILE_APPEND: used to append the new contents at the end of the file
// LOCK_EX : used to avoid another user to write on the same file at the same time

Need Help Handling a XML HTTP File Upload Request

So, I looked up a tutorial for uploading and sending files to a server with an XML HTTP Request. I followed the tutorial, however, I think I must be missing something. While the file appears to be uploaded and sent, nothing in the "handler" file is ever accessed. Is there a PHP function I need to write to process it? For context, here is what I wrote:
$(document).ready(function()
{
$('#upload-button').click(function(event)
{
$('#upload-button').removeClass("btn-danger");
});
$( "#report-form" ).submit(function( event )
{
var form = document.getElementById('report-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
event.preventDefault(); // Stop the event from sending the way it usually does.
uploadButton.value = 'Submitting...'; // Change text.
var files = fileSelect.files;
var maxfiles = <?php echo $config['Report_MaxFiles'] ?>;
var mfs = <?php echo $config['Report_MaxFileSize'] ?>;
if(files.length > maxfiles) // Make sure it's not uploading too many.
{
uploadButton.value = 'You uploaded too many files. The limit is ' + maxfiles + '.'; // Update button text.
$('#upload-button').addClass('btn-danger'); // Make the button red, if so.
return;
}
var formData = new FormData(); // Make a "form data" variable.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
if(file.size / 1000 > mfs)
{
uploadButton.value = 'One of the files is too big. The file size limit is ' + (mfs) + 'kb (' + (mfs / 1000) + 'mb).';
$('#upload-button').addClass('btn-danger');
return;
}
formData.append('files[]', file, file.name); // Not really sure what this does, to be honest,
// but I think it makes a file array.
}
var xhr = new XMLHttpRequest(); // Construct an XML HTTP Request
xhr.open('POST', 'assets/class/FileHandler.php', true); // Open a connection with my handler PHP file.
xhr.onload = function ()
{
if (xhr.status === 200)
{
uploadButton.value = 'Files Submitted!'; // NOTE: I do get this message.
}
else
{
uploadButton.value = 'An error occurred.';
$('#upload-button').addClass("btn-danger");
}
};
xhr.send(formData); // I think this is where it dies.
});
});
At the "send(formData)" line, I'm not actually sure if it's sending. Do I set up some sort of listener in FileHandler.php that is activated when the files are sent via XML HTTP request? Or more specifically, how to I save the uploaded files to the server using my FileHandler.php file?
EDIT: I haven't been able to come up with any other PHP code in the FileHandler.php file than this, which I thought might be called when the form is sent (but it isn't):
EDIT 2: Okay, now I have something, but it isn't working (didn't expect it to). I think I may be using the variables wrong:
<?php
$uploaddir = 'data/reports/uploads/' . $_POST['id'] . "/";
$uploadfile = $uploaddir . basename($_FILES['files']['name']);
echo "<script>console.log('RECEIVED');</script>";
echo '<pre>';
if (move_uploaded_file($_FILES['files']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
It's not saving the file to the directory, nor is it printing the script message. How do I get my report.php file to execute these things in FileHandler.php?
Thanks to the help and patience of #Florian Lefèvre, I got it fixed. :)
The problem was with the path. It wasn't locating the path to the folder data/uploads/ and wasn't making the directory. Here is what I did:
$uploaddir = '../../data/reports/uploads/' . $_POST['id'] . "/";
echo "NAME: " . $_FILES['files']['name'][0] . "\n";
foreach($_FILES['files']['name'] as $filenumber => $filename)
{
$uploadfile = $uploaddir . basename ($filename);
echo "UploadDir " . $uploaddir . "\n";
echo "UploadFile " . $uploadfile . "\n";
echo '<pre>';
echo "MKDir for UploadDir which is: ". $uploaddir . "\n";
mkdir ($uploaddir);
if (move_uploaded_file ($_FILES['files']['tmp_name'][$filenumber], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print "</pre>";
}
var_dump ($_FILES);
I haven't gotten rid of some of the debug stuff yet, but that's the general solution.

Auto load search results when page loads

I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>

Categories