Validating Bulk phone Number with Numverify web API in PHP - javascript

This is what I have done so far base on what I saw on their documentation page
The phone list is paste separated by comma(,) in a line break inside the textarea
e.g
2144667308,
6823259843,
2173196699,
6163091855,
6163093109
with the below code it only saved all the above listed number inside Invalid_Phones_numbers.txt, please any help will be more appreciated
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<center>
<form action="test2.php" method="post">
<textarea name="input" rows="8" cols="20" required></textarea>
<button class="btn btn-primary" type="submit" name="submit"> Submit </button>
</form>
</center>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
//$leads_gatewayapi=array($_POST['leads_gatewayapi']);
$input = array($_POST['input']);
foreach ($input as $msisdn) {
$json['input'][] = ['msisdn' => $msisdn];
//$msg_gatewayapi=$_POST['msg_gatewayapi'];
$api_multiple = "c375c6c106b14d830b7*********";
$country_code_m = "US";
echo $msisdn; // this is to know maybe array value passes( 2144667308, 6823259843, 2173196699, 6163091855, 6163093109 as the output)
$ch = curl_init('http://apilayer.net/api/validate?access_key=' . $api_multiple . '&number=' . $msisdn . '&country_code=' . $country_code_m);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$validationResult = json_decode($json, true);
//$obj = json_decode($resu);
if (empty($validationResult['carrier'])) {
$myfile = fopen("Phone_Check_Result/Invalid_Phones_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
} elseif (!empty($validationResult['carrier']) && ($validationResult['line_type'] == "mobile")) {
$myfile = fopen("Phone_Check_Result/Valid_Mobile_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
} elseif (!empty($validationResult['carrier']) && ($validationResult['line_type'] == "landline")) {
$myfile = fopen("Phone_Check_Result/Valid_Landline_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
}
}
if ($validationResult) {
echo "Its Working!!!";
}
$validationResult['valid'];
$validationResult['number'];
$validationResult['local_format'];
$validationResult['international_format'];
$validationResult['country_prefix'];
$validationResult['country_code'];
$validationResult['country_name'];
$validationResult['location'];
$validationResult['carrier'];
$validationResult['line_type'];
}
?>

#Sami, The api code you see is for illustrations purposes, not a working one...

Related

Pass PHP variable from HTML form to Javascript

could you help me pass a variable that was taken from a html form into javascript.
The form asks for the tablename
<br>
New tablename:<br>
<input type="text" name="table">
It is passed through PHP:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
A first action is underway, and created successfully: the Geoserver postgis table is created through PHP curl (entire code below)
then the javascript tries to get $table with a PHP insert; this will help it load the newly created postgis Geoserver table from the PHP, into the WFST javascript ;
<?php
echo "var thedata = " .$table. ";\n";
?>
...
var wfstPoly = new L.WFST({
url: 'https://mappingforyou.eu/geoserver/ows',
typeNS: 'opendata',
typeName: thedata,
But this code doesn't work:
<?php
echo "var thedata = " .$table. ";\n";
?>
--
The code works fine except for the thedata javascript variable.
The entire form:
<!DOCTYPE html>
<html>
<body>
<h2>PG GS input test</h2>
<form method="POST" action="test1.php">
User:<br>
<input type="text" name="user">
<br>
Password:<br>
<input type="password" name="password">
<br>
New tablename:<br>
<input type="text" name="table">
<input type="radio" name="geom" id="Point" value="Point" />
<label for="Point">Point</label>
<input type="radio" name="geom" id="MultiLineString" value="MultiLineString" />
<label for="MultiLine">Line</label>
<input type="radio" name="geom" id="MultiPolygon" value="MultiPolygon" />
<label for="MultiPolygon">Area</label>
<br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Into this javascript test1.php page:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"/>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.toolbar.js/0.3.0/leaflet.toolbar.css" />
<style>
html, body, #map {
margin: 0;
height: 100%;
width: 100%;
}
</style>
<title>Leaflet-WFST polygon demo</title>
</head>
<body>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<link rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet.draw.css" />
<script src="https://mappingforyou.eu/javascript/leaflet.draw-src.js"></script>
<link type="text/css" rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet-easybutton.css" />
<script type="text/javascript" src="https://mappingforyou.eu/javascript/leaflet-easybutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
<script src="https://mappingforyou.eu/javascript/leaflet-wfst.src.js"></script>
<script>
function jsFunction(){
<?php
echo "var thedata = " .$table. ";\n";
?>
var map = L.map('map', {editable: true}).setView([48.5, 2], 10);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var wfstPoly = new L.WFST({
url: 'http://localhost:8080/geoserver/ows',
typeNS: 'workspace',
typeName: thedata,
crs: L.CRS.EPSG4326,
geometryField: 'geom',
style: {
color: 'blue',
weight: 2
}
}).addTo(map)
.once('load', function () {
map.fitBounds(wfstPoly);
});
////// draw and edit
var drawControl = new L.Control.Draw({
draw:{circle:false, circlemarker:false, rectangle:false,
},
edit:{featureGroup: wfstPoly } });
map.addControl(drawControl);
map.on('draw:created', function (e) {
var layer = e.layer;
wfstPoly.addLayer(layer)});
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer( function (layer) {
wfstPoly.editLayer(layer);
})
});
// Save button
L.easyButton('fa-save', function () {
wfstPoly.save();
}, 'Save changes').addTo(map);
}
</script>
<?php
// Open log file
$logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file");
// Initiate cURL session
$service = "http://localhost:8080/geoserver/rest"; // replace with your URL
$ws = "workspace";
$ds = "database";
$request = "/workspaces/" . $ws . "/datastores/" . $ds . "/featuretypes";
$url = $service . $request;
$ch = curl_init($url);
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
define("GEOSERVER_REST_HOST", "http://localhost:8080/geoserver/rest");
define("GEOSERVER_USER", "admin:password");
// Optional settings for debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //option to return string
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $logfh); // logs curl messages
//Required POST request settings
curl_setopt($ch, CURLOPT_POST, True);
//$passwordStr = "admin:geoserver"; // replace with your username:password
curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);
//POST data
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-type: text/xml"));
$xmlStr = "<featureType>";
$xmlStr .= "<name>".$table."</name>";
$xmlStr .= "<nativeName>".$table."</nativeName>";
$xmlStr .= "<title>".$table."</title>";
$xmlStr .= "<srs>EPSG:4326</srs>";
$xmlStr .= "<attributes>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>geom</name>";
$xmlStr .= "<binding>com.vividsolutions.jts.geom.".$geometry."</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>description</name>";
$xmlStr .= "<binding>java.lang.String</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>timestamp</name>";
$xmlStr .= "<binding>java.util.Date</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "</attributes>";
$xmlStr .= "</featureType>";
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);
//POST return code
$successCode = 201;
$buffer = curl_exec($ch); // Execute the curl request
// Check for errors and process results
$info = curl_getinfo($ch);
if ($info['http_code'] != $successCode) {
$msgStr = "# Unsuccessful cURL request to ";
$msgStr .= $url." [". $info['http_code']. "]\n";
fwrite($logfh, $msgStr);
} else {
$msgStr = "# Successful cURL request to ".$url."\n";
fwrite($logfh, $msgStr);
}
fwrite($logfh, $buffer."\n");
curl_close($ch); // free resources if curl handle will not be reused
fclose($logfh); // close logfile
echo '<script type="text/javascript">jsFunction();</script>';
return $success;
?>
</body>
</html>
In the code you provided, this:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
...comes after this:
echo "var thedata = " .$table. ";\n";
The initial assignment of PHP variable $table needs to come before it is used.
And if the table name, provided by the form text input, is a string, $table needs to be quoted for when it gets assigned to the Javascript variable thedata:
For example:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
Keep in mind, PHP executes on the server, and the resulting text, containing HTML, Javascript, CSS, is sent to the browser through HTTP. The browser never gets PHP code. The browser only gets HTML, Javascript, and CSS. Once the browser gets these from the server it evaluates the Javascript and renders the HTML and CSS.
This, on the server:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
...is executed resulting in this:
function jsFunction(){
var thedata = "user provided table name";
<!-- ... -->
...which is then sent as text to the browser.
I elaborate further on the distinct PHP and Javascript execution contexts here: https://stackoverflow.com/a/72023066/2743458
Try below
var thedata = <?php echo $table; ?>+"\n";

How to Show result after uploaded file in PHP

I have a script that uploads the video to a server, everything is correct but there is a problem, after the upload of the video to the server is completed
it shows all the uploaded files in the (uploads) folder as array!
I only want the result of the file I just uploaded, and it doesn't show me the previous files!
I need ffmpeg to improve video quality
index.php
<?php
//index.php
?>
<!DOCTYPE html>
<html>
<head>
<title>Personal Video Uploader</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-body">
<div class="container">
<form action="upload.php" class="dropzone font" id="dropzoneFrom">
</form>
</form>
<br />
<div id="preview"></div>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: true,
timeout: 300000,
acceptedFiles:"video/*",
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
list_image();
});
},
};
list_image();
function list_image()
{
$.ajax({
url:"upload.php",
success:function(data){
$("#preview").html(data);
}
});
}
$(document).on('click', '.remove_image', function(){
var name = $(this).attr('id');
$.ajax({
url:"upload.php",
method:"POST",
data:{name:name},
success:function(data)
{
list_image();
}
})
});
});
</script>
upload.php
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$result = array();
$files = scandir('upload');
$output = '<div class="row">';
if(false !== $files)
{
foreach($files as $file)
{
if('.' != $file && '..' != $file)
{
$output .= '
<img src="thumb/'.$file.'.png" class="img-thumbnail" width="246px" height="138px" style="height:138px;" />
<button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
';
}
}
}
$output .= '</div>';
echo $output;
?>
EDIT:
I put the example on an Array, I don't want it, I just want it to show the downloaded video I just uploaded as a result.
EDIT 2 :
There are some who say type $location and it displays the downloaded file, but this does not work!!!
I just tried more than once and with several uses, there is no display where the text is empty
This is an example of that
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$output .= 'Successfly file is "'.$location.'"';
echo $output;
?>
Result : Successfly file is ""
no name file :(
EDIT 3 :
this code upload.php
functions not working
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
echo "The file " . $location . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $upload . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $uploadStr . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $locationStr . " has been uploaded";
// not working
?>
this error:
[23-Apr-2022 12:31:56 Asia/Riyadh] PHP Notice: Undefined variable: location in /home/prdix/public_html/test/upload.php on line 38
line 38: echo $location;
About the developer solution Markus AO
I did the experiment and it is quite good, but dropzone is still missing, because I will upload a large video and the normal upload compresses the video before uploading, here is a picture from my mobile while uploading, but this does not happen with dropzone
I want to implement this in dropzone as well, because this library does not compress the video, but upload it in full size.
Thank you bro.

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

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

Get statement not adding to database

i'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.

Javascript output online usernames in HTML table

I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
$query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
$query->execute();
$query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
$query->execute();
}
function addOrRefresh($ID){
$query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
$count = $query->fetchColumn();
if($count == 0){
$query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
$query->bindParam(':ID', $ID);
$query->execute();
}
else{
$query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
removeRefresh();
$ID = $_GET['id'];
addOrRefresh($ID);
$query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
$query->execute();
$onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
$resultaat = "";
foreach($onlineUsers as $user){
$resultaat .= "<p>{$user['username']} <br></p>";
}
echo "$resultaat";
}
?>
You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
<?php
session_start();
$ID = $_SESSION['ID'];
if (isset($_POST['logout'])) {
session_destroy();
$query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
?>
<html>
<head>
<title>Stratego</title>
<Link href="../layout/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./js/HeartBeat.js"></script>
<script>
$(document).ready(function () {
heartbeat.setSpelerId( <?php echo $ID; ?> );
heartbeat.polling();
});
</script>
</head>
<body>
<form method='post' name='logout' action="../setup/logout.php">
<input type='submit' name='loggout' value='Log me out'>
</form>
Singleplayer
<div id="online-list">
</div>
</body>
<?php echo "<script>
function heartbeat(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById(\"online-list\").innerHTML = xhttp.responseText;
}
};
xhttp.open(\"GET\", \"./wachtruimterInterface.php?action=heartbeat&id=" . $ID . "\", true);
console.log('keeping in touch ༼つ ◕_◕ ༽つ');
xhttp.send();
}
setInterval(heartbeat, 1000);
</script>"; ?>
</html>
The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
$resultaat .= "<tr><td>{$user['username']} <br></td></tr>";
}
echo "<table>$resultaat</table>";
Just now, doesn't seem to work, any tips on how to progress?
I've fixed the issue;
$resultaat = "";
foreach($onlineUsers as $user){
$naam= $user['username']
$resultaat .= "<tr><td>$naam</td></tr>";
}
echo "<table border=1>$resultaat</table>";

Categories