Undefined offset 1: when passing a file using ajax file upload - javascript

When I pass data into my file upload controller, it is giving an error of undefined offset: 1.
function TestFileUpload() {
$i=0;
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
$count = count($_FILES[$i]['name']). ' ';
while ($i <= 4 )
{
echo $count;
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
echo $_FILES[$i]['name'].' '.$_FILES[$i]['type'].' '.$_FILES[$i]['size'] ;
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else{
$data = array('upload_data' => $this->upload->data());
$this->new_development_model->insertonAttachments($data['upload_data']);
$i++;
}
}
}
}

It's probably related cause you need to check in your loop if $_FILES[$i] is defined.
You do this but only one time, when $i = 0.
I even think that if you check in the loop, you wont need to do
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else { /*...*/ }
before the loop

Related

how to get socket_read value to plain text sent from javascript in PHP websocket

i am trying to make my small websocket php class in which i wanted to make functions like onopen onmessage etc like node js [i know there are other libraries out there but i wanted to learn it myself].so far i am able to successfully recieve message from js websocket to php with this code below
<?php
$host = "localhost";
$port = 8001;
$sockets=array();
function sendAll($connections,$msg){
foreach ($connections as $each) {
send($each,$msg);
}
}
function send($client,$msg){
$msg = chr(129) . chr(strlen($msg)) . $msg;
socket_write($client,$msg,strlen($msg));
}
function handshake($client){
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
'H*',
sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));
}
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_nonblock($server);
socket_bind($server, $host, $port);
socket_listen($server);
while(true){
$client = socket_accept($server);
if($client != false){
usleep(100);
handshake($client);
array_push($sockets,$client);
print_r($sockets);
}
else{
if(count($sockets) > 0){
foreach ($sockets as $each) {
$msg = socket_read($each,5000);
if($msg != false){
filter($msg);
// send($each,"testing");
}
}
}
}
}
function filter($msg){
$msg = unpack("c*",$msg);
foreach ($msg as $value) {
echo chr($value);
}
// print_r($msg);
}
?>
after some research i found that websocket sends message in binary. i cant convert that message into plain text. i dont know which language or format that data is sent into.tell me please which format is it and how to read it as plain text sample picture below
finally i find the way to decode from this website
its actually masked which needed to be unmasked . here i found a function from a website all i have to do is to read that scarmled text is unmask with below custom function
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}

Vue.js Array of Images from Backend Returned as Array of Objects to Frontend

My aim is to display an array of images that I saved in the file folder and its directory in the database. Recently, I managed to get the images based from the static directory that I declared at the backend once but now, my problem is displaying multiple images. Here is my code below.
I got this error: GET 127.0.0.1:8887/undefined 404 (Not Found)
Frontend
<template>
<div>
<q-img
v-for="(data, index) in base64data"
:src="'http://127.0.0.1:8887/' + data.daimage"
:key="index"
style="width:100px;height:50px"
/>
</div>
</template>
<script>
export default {
methods: {
getTests() {
axios
.get("http://localhost/MyComposer/", {
params: {
id: 6,
token: this.token
}
})
.then(res => {
console.log(res.data);
for (var i = 0; i < res.data.length; i++) {
this.base64data.push({
//image: res.data[i].TestImage,
daimage: res.data[i].DaImage
});
this.dataList.push({
subjectId: res.data[i].SubjectId,
question: res.data[i].Question,
answer: res.data[i].Answer,
timer: res.data[i].Timer / 60
});
}
});
}
}
}
</script>
Backend
public function getTest()
{
$datab = new ConnectDb;
$db = $datab->Connect();
// if (isset($_GET['id']) && $_GET['id'] == 3) {
// $db->where('AccessId', $_GET['token']);
// $testdb = $db->get('testdetails');
// echo json_encode($testdb);
// }
if (isset($_GET['id']) && $_GET['id'] == 6) {
$dir = 'C:\xampp\htdocs\MyComposer\pictures';
function Get_ImagesToFolder($dir)
{
$ImagesArray = [];
$file_display = ['jpg', 'jpeg', 'png', 'gif'];
if (file_exists($dir) == false) {
return ["Directory \'', $dir, '\' not found!"];
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_type, $file_display) == true) {
$ImagesArray[] = $file;
}
}
return $ImagesArray;
}
}
$ImagesA = Get_ImagesToFolder($dir);
$ret = [];
foreach ($ImagesA as $img) {
$db->where('AccessId', $_GET['token']);
$db->where('TestImage', $dir . '\_' . $img);
$db->where('DaImage', $img);
$testdb = $db->get('testdetails');
$ret[] = json_encode($testdb);
}
echo json_encode($ret);
}
}
In your loop you echo which is immediately returning back the first image and closing out the response. Instead, push the image into an array and then return that:
Bad:
echo json_encode($testdb);
Better:
$ret = [];
foreach ($ImagesA as $img) {
$db->where('AccessId', $_GET['token']);
$db->where('TestImage', $dir . '\_' . $img);
$db->where('DaImage', $img);
$testdb = $db->get('testdetails');
$ret[] = $testdb;
}
echo json_encode($ret);

Is there an easy way to update CSV with an API data?

I have a code that can get the Amazon product price if you gave it's "ASIN" (It's Amazon product identification number)... below you can find the code (I don't think there is a need to read the code anyway).
<?php
class AmazonAPI {
var $amazon_aff_id;
var $amazon_access_key;
var $amazon_secret_key;
var $url_params;
var $itemID;
var $xml;
var $operation;
var $signature;
var $response_groups = "Small,Images,OfferSummary";
var $error_message;
var $error=0;
public function __construct($affid, $access, $secret)
{
$this->amazon_aff_id = $affid;
$this->amazon_access_key = $access;
$this->amazon_secret_key = $secret;
}
public function build_url()
{
$url = "http://webservices.amazon.com/onca/xml?";
$this->response_groups = str_replace(",", "%2C", $this->response_groups);
$url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
$url_params .= "&AssociateTag=" . $this->amazon_aff_id;
if(!empty($this->itemID)) {
$url_params .= "&ItemId=" . $this->itemID;
}
$url_params .= "&Operation=" . $this->operation;
$url_params .= "&ResponseGroup=" . $this->response_groups;
$url_params .= "&Service=AWSECommerceService";
$url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url_params .= "&Version=2013-08-01";
$this->url_params = $url_params;
$url .= $url_params;
$url .= "&Signature=" . $this->generate_signature();
return $url;
}
public function generate_signature()
{
$this->signature = base64_encode(hash_hmac("sha256",
"GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
$this->amazon_secret_key, True));
$this->signature = str_replace("+", "%2B", $this->signature);
$this->signature = str_replace("=", "%3D", $this->signature);
return $this->signature;
}
public function item_lookup($id)
{
$this->operation = "ItemLookup";
$this->itemID = $id;
$url = $this->build_url();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$this->xml = simplexml_load_string($output);
return $this;
}
public function check_for_errors()
{
if(isset($this->xml->Error)) {
$this->error_message = $this->xml->Error->Message;
$this->error = 1;
}
if(isset($this->xml->Items->Request->Errors)) {
$this->error_message = $this->xml->Items->Request->Errors->Error->Message;
$this->error = 1;
}
return $this->error;
}
public function get_item_price($product)
{
$price = 0;
if(isset($product->LowestNewPrice)) {
$price = $product->LowestNewPrice->Amount;
} elseif(isset($product->LowestUsedPrice)) {
$price = $product->LowestUsedPrice->Amount;
} elseif(isset($product->LowestCollectiblePrice)) {
$price = $product->LowestCollectiblePrice->Amount;
} elseif(isset($product->LowestRefurbishedPrice)) {
$price = $product->LowestRefurbishedPrice->Amount;
}
return $price;
}
public function get_item_data()
{
if($this->check_for_errors()) return null;
$product = $this->xml->Items->Item;
$item = new STDclass;
$item->detailedPageURL = $product->DetailPageURL;
$item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
$item->title = $product->ItemAttributes->Title;
$item->smallImage = $product->SmallImage->URL;
$item->mediumImage = $product->MediumImage->URL;
$item->largeImage = $product->LargeImage->URL;
$item->price = $this->get_item_price($product->OfferSummary);
return $item;
}
}
?>
Then i echo the price with this code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();
echo $item->price;
Now if i have a csv sheet like this
https://ibb.co/dHS4EK
can i update the prices on column D and E given the asin found on column B and C,
so for example the value of cell D2 will get it using the following code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup(Value on cell D2)->get_item_data();
echo $item->price;
then save the csv file after updating it's prices, is there a simple easy way to do that in maybe php especially that i'm very new to coding?
Edit 1: I need the csv file to import it using WooCommerce import tool which only accept csv files
Thanks in advance
What you have to do is:
Parse the CSV file into an array. You can use PHP functions for that like str-getcsv
Find the correct line inside the array with either array_filter or a simple foreach loop.
Update the respective value with the new price
Create a CSV file from the array with fputcsv

Javascript : Uncaught SyntaxError: Unexpected token <

I have these code, which stores the php variable to a global javascript variable. All the modules are in same file, but still I get an Uncaught SyntaxError: Unexpected token <, at the rowNum1's line:-
<script type="text/javascript">
var glo = 0;
var rowNum = <?php echo $_GET['SN'];?>;
var newnames = new Array();
var rowNum1 = "";
var tempVal = "";
var destTextarea = "";
newnames=<?php echo json_encode($userinfoarr); ?>; //This varaible initialisation works fine
function fetchNext(){
if (glo++ === 0)
{
if(rowNum < newnames.length)
{
document.getElementById("Txt0").value = rowNum;
document.getElementById("Txt1").value = newnames[rowNum];
tempVal = newnames[rowNum];
}
rowNum++;
}
else
{
rowNum1=<?php echo json_encode($sln); ?>; //This one throws an Uncaught Syntax error
if(rowNum1 < newnames.length)
{
document.getElementById("Txt0").value = rowNum1;
document.getElementById("Txt1").value = newnames[rowNum1];
tempVal = newnames[rowNum1];
}
rowNum1++;
console.log("test");
}
}
</script>
This is the php code for $sln:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
}
}
?>
This is the php code for $userinfoarr
<?php
require_once('config.php');
$result = mysqli_query($conn, "SELECT tweet from tweet");
$userinfoarr = array();
while ($row_user = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$userinfo = $row_user["tweet"];
$push=array_push($userinfoarr, $userinfo);
}
?>
COuld anybody help me out with this, as I am unable here to understand the scenario?
Here is a screenshot of the error inside browser
change your php code as below. assign $sln default value
<?php
$sln = ""; //<---- assign default value to $sln
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
}
}
?>
Do something like this
Modify $sln code as
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
echo "<script type='text/javascript'>var sln='$sln'</script>";
}
}
?>
and in script
{
rowNum1 = sln; //
if(rowNum1 < newnames.length)
{
document.getElementById("Txt0").value = rowNum1;
document.getElementById("Txt1").value = newnames[rowNum1];
tempVal = newnames[rowNum1];
}
rowNum1++;
console.log("test");
}
Use single quote for PHP code:
var rowNum = '<?php echo $_GET['SN'];?>';

Why is my code not passing to my div?

I'm trying to create a gameserver query for my website, and I want it to load the content, save it, and echo it later. However, it doesn't seem to be echoing. It selects the element by ID and is supposed to echo the content of the VAR.
Here's my HTML code:
<center><div id="cstrike-map"><i class="fa fa-refresh fa-spin"></i> <b>Please wait ...</b><br /></div>
JavaScript:
<script type="text/javascript">
var map = "";
var hostname = "";
var game = "";
var players = "";
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
map = ( data.map );
hostname = ( data.hostname );
game = ( data.game );
players = ( data.players );
}, "json");
function echoMap(){
document.getElementByID("cstrike-map");
document.write("<h5>Map: " + map + "</h5>");
}
</script>
PHP files:
query.php
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut = explode(":", $ip);
$HL2_address = $cut[0];
$HL2_port = $cut[1];
$HL2_command = "\377\377\377\377TSource Engine Query\0";
$HL2_socket = fsockopen("udp://".$HL2_address, $HL2_port, $errno, $errstr,3);
fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket,4);
$CheckStatus = socket_get_status($HL2_socket);
if($CheckStatus["unread_bytes"] == 0)
{
return 0;
}
$do = 1;
while($do)
{
$str = fread($HL2_socket,1);
$HL2_stats.= $str;
$status = socket_get_status($HL2_socket);
if($status["unread_bytes"] == 0)
{
$do = 0;
}
}
fclose($HL2_socket);
$x = 0;
while ($x <= strlen($HL2_stats))
{
$x++;
$result.= substr($HL2_stats, $x, 1);
}
$result = urlencode($result); // the output
return $result;
}
/* FORMAT SOURCE ENGINE QUERY (assumes the query's results were urlencode()'ed!) */
function format_source_query($string)
{
$string = str_replace('%07','',$string);
$string = str_replace("%00","|||",$string);
$sinfo = urldecode($string);
$sinfo = explode('|||',$sinfo);
$info['hostname'] = $sinfo[0];
$info['map'] = $sinfo[1];
$info['game'] = $sinfo[2];
if ($info['game'] == 'garrysmod') { $info['game'] = "Garry's Mod"; }
elseif ($info['game'] == 'cstrike') { $info['game'] = "Counter-Strike: Source"; }
elseif ($info['game'] == 'dod') { $info['game'] = "Day of Defeat: Source"; }
elseif ($info['game'] == 'tf') { $info['game'] = "Team Fortress 2"; }
$info['gamemode'] = $sinfo[3];
return $info;
}
cstrike.php
include('query.php');
$ip = 'play1.darkvoidsclan.com:27015';
$query = source_query($ip); // $ip MUST contain IP:PORT
$q = format_source_query($query);
$host = "<h5>Hostname: ".$q['hostname']."</h5>";
$map = "<h5>Map: ".$q['map']."</h5>";
$game = "<h5>Game: ".$q['game']."</h5>";
$players = "Unknown";
$stats = json_encode(array(
"map" => $map,
"game" => $game,
"hostname" => $host,
"players" => $players
));
You need to display the response in the $.post callback:
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
$("#map").html(data.map);
$("#hostname").html(data.hostname);
$("#game").html(data.game);
$("#players").html(data.players);
}, "json");
You haven't shown your HTML, so I'm just making up IDs for the places where you want each of these things to show.
There are some things that I can't understand from your code, and echoMap() is a bit messed up... but assuming that your php is ok it seems you are not calling the echomap function when the post request is completed.
Add echoMap() right after players = ( data.players );
If the div id you want to modify is 'cstrike-map' you could use jQuery:
Change the JS echoMap to this
function echoMap(){
$("#cstrike-map").html("<h5>Map: " + map + "</h5>");
}
So what I did was I had to echo the content that I needed into the PHP file, then grab the HTML content and use it.
That seemed to be the most powerful and easiest way to do what I wanted to do in the OP.
<script type="text/javascript">
$(document).ready(function(){
$.post("stats/query.cstrike.php", {},
function (data) {
$('#serverstats-wrapper-cstrike').html (data);
$('#serverstats-loading-cstrike').hide();
$('#serverstats-wrapper-cstrike').show ("slow");
});
});
</script>
PHP
<?php
include 'query.php';
$query = new query;
$address = "play1.darkvoidsclan.com";
$port = 27015;
if(fsockopen($address, $port, $num, $error, 5)) {
$server = $query->query_source($address . ":" . $port);
echo '<strong><h4 style="color:green">Server is online.</h4></strong>';
if ($server['vac'] = 1){
$server['vac'] = '<img src="../../images/famfamfam/icons/tick.png">';
} else {
$server['vac'] = '<img src="../../images/famfamfam/icons/cross.png">';
}
echo '<b>Map: </b>'.$server['map'].'<br />';
echo '<b>Players: </b>'.$server['players'].'/'.$server['playersmax'].' with '.$server['bots'].' bot(s)<br />';
echo '<b>VAC Secure: </b> '.$server['vac'].'<br />';
echo '<br />';
} else {
echo '<strong><h4 style="color:red">Server is offline.</h4></strong>';
die();
}
?>

Categories