Using get_file_contents() to make an array - php

I am trying to upload a CSV file and get it's contents into an array, but I am getting this an error: (Multiples of this error on each line after 10)
Notice: Undefined offset: 1 in C:\xampp\htdocs\amazon\upload_file.php on line 10
Below is a sample of my code:
if ($handle = file_get_contents($_FILES["file"]["tmp_name"])) {
$data = array();
while ($csv = array(file_get_contents($_FILES["file"]["tmp_name"]))) {
$data = array(
'order-id' => $csv[0],
'order-item-id' => $csv[1], //This is line 10.
'purchase-date' => $csv[2],
'payments-date' => $csv[3],

file() opens puts each as an array element. fgetcsv() and its family of functions are very useful when dealing with csv files.
Your code array(file_get_contents($_FILES["file"]["tmp_name"])) will only ever have one element because file_get_contents returns a string.

This issue comes if your file has only one line.
I guess you need to do this.
$row = explode(",", $csv[0]);
$data = array(
'order-id' => $fileArray[0],
'order-item-id' => $row[1], //This is line 10.
'purchase-date' => $row[2],
'payments-date' => $row[3]
);
Also, you can use functions like fgetcsv() to parse your CSV file.

Related

Echo file contents inside params array

I'm trying to finish creating a php keygen for my product.
Is it possible for me to echo a text value inside on array (specifically the HWID which is taken from an uploaded text file)?
<?php
$file = file_get_contents('text.txt');
$params = array(
hwid => "echo $file;", // Exactly as returned by VMProtectGetCurrentHWID
user_data => base64_decode("CGCvRvMWcPHGdMjQ"), // string of bytes
);
?>
Is there a better way of doing it?
You don't need to echo just do this:
<?php
$file = file_get_contents('text.txt');
$params = array(
hwid => $file, // Exactly as returned by VMProtectGetCurrentHWID
user_data => base64_decode("CGCvRvMWcPHGdMjQ"), // string of bytes
);

I want to add a csv file content into the database and it's not working

I want the admin of the website to select a CSV file with a file input. The CSV file with have users in it which is then inserted into the database with randomly generated passwords. For each user inserted into the database, the user will receive a mail which contains their login (which is their email) and their password.
I tried to get the CSV content in an array with a library but I haven't managed to make it work.
Here is the function in the controller that reads the CSV file
public function lire_csv()
{
$this->load->library('Csvimport');
$file_data = $this->Csvimport->get_array($_FILES["csv_file"]["liste_etu"]);
foreach($file_data as $row)
{
$data[] = array(
'nom' => $row["Nom"],
'prenom' => $row["Prenom"],
'statut'=> "Etudiant",
'civilite' => $row["Civilite"],
'mail' => $row["Email"],
'adresse' => $row["Adresse"],
'complement' => $row["Complement"],
'code_postal' => $row["Code_postal"],
'ville' => $row["Ville"],
'pays' =>$row["Pays"],
'tel' => $row["Telephone"],
'date_naiss' => $row["Date_de_naissance"],
'num_secu' => $row["Numero_secu"],
'mutuelle' => $row["Mutuelle"],
'objectif_pro' => $row["Objectif_pro"],
'motdepasse' => uniqid()
);
$this->envoyer_mail($data['mail'],$data['motdepasse'],$data['nom'],$data['prenom']);
}
$this->mStages->create_utilisateur($data);
}
This is the library I used CSV Import
This function gives me warning about the timeset
And finally here is the view code portion where the admin has to select the CSV file. There is a weird behavior because only the rectangle surrounding the button that is supposed to open the file explorer works, but the button itself does nothing.
<form action=<?php echo base_url('index.php/main_stage/lire_csv'); ?> method="post">
<center><input type="file" name="fichier" id="csv_file" required accept=".csv"/></center> <p>Fichier .csv uniquement</p>
<input type="submit" value="Envoyer la liste">
When I try to send the CSV I get these errors:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Main_stage::$Csvimport
Filename: controllers/main_stage.php
Line Number: 507
Backtrace:
File: D:\boulot\php\UwAmp\www\Projet_PHP\CodeIgniter-3.1.9\application\controllers\main_stage.php
Line: 507
Function: _error_handler
File: D:\boulot\php\UwAmp\www\Projet_PHP\CodeIgniter-3.1.9\index.php
Line: 315
Function: require_once
( ! ) Fatal error: Call to a member function get_array() on null in D:\boulot\php\UwAmp\www\Projet_PHP\CodeIgniter-3.1.9\application\controllers\main_stage.php on line 507
Call Stack
# Time Memory Function Location
1 0.0149 150416 {main}( ) ...\index.php:0
2 0.0281 197248 require_once( 'D:\boulot\php\UwAmp\www\Projet_PHP\CodeIgniter-3.1.9\system\core\CodeIgniter.php' ) ...\index.php:315
3 0.3565 2069632 call_user_func_array:{D:\boulot\php\UwAmp\www\Projet_PHP\CodeIgniter-3.1.9\system\core\CodeIgniter.php:532} ( ) ...\CodeIgniter.php:532
4 0.3565 2069832 Main_stage->lire_csv( ) ...\CodeIgniter.php:532
A PHP Error was encountered
Severity: Error
Message: Call to a member function get_array() on null
Filename: controllers/main_stage.php
Line Number: 507
Backtrace:
I want to see how can I improve my code or easier ways to do this.
For me i don't use third-party libraries for dealing with relatively simple files like csv cause you can already read it in one line of code and convert it you an array like this:
$csv = array_map('str_getcsv', file('book.csv'));
Then we will create an array of associative arrays with the first row column headers as the keys like this:
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
You can then remove column header and keep it if you want like this:
$header = array_shift($csv);
Then you can add your random password to each user like this:
foreach ($csv as $key => $value)
{
$csv[$key]['password'] = 'random_password';
}
This will generate an array like this:
[0]=>
array(3) {
["username"]=>
string(6) "sherif"
["email"]=>
string(15) "sherif#code.com"
["password"]=>
string(15) "random_password"
}
...
Then continue doing your magic, send email to every single user in this array, save it to your db using insert_batch or whatever you wanna do.
Finally about your other html/css question, try asking another separate question.
Final version:
$csv = array_map('str_getcsv', file('book.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
$header = array_shift($csv);
foreach ($csv as $key => $value)
{
$csv[$key]['password'] = 'random_password';
}
EDIT: if you want to read the uploaded file you got two option, first is to read it directly form tmp like this:
$csv = array_map('str_getcsv', file($_FILES['uploadedfile']['tmp_name']));
Or you can save the file first and read the path as mentioned before.
About if it would work with any csv file, yeah it should work with any valid csv file without a problem.

read text file and insert into mysql php

I have huge text file and I am trying to read and insert this line by line.
this is txt file data.
'REG','KOIL','Kohinoor Industries Ltd.','READY',4.82,2.82,3.82
'REG','EPQL','Engro Powergen Qadirpur Ltd.','READY',36.9495,33.4305,35.19
Function for insert data
$file_path =FCPATH.'uploads/text/'.$file_name;
$psx_date=$this->input->post('file_date');
$open=fopen($file_path,"r");
$i=1;
while(!feof($open)){
$line=fgets($open);
if($i>2){
$values = explode(",",$line);
$psx_symbol=str_replace('\'',null,$values[1]);
$no_of_rows=read_psx_where($psx_symbol,$psx_date);
if($no_of_rows<=0){
$psx_data=array(
'PSX_SYMBOL' => $psx_symbol,
'PSX_DATE' => $psx_date,
'PSX_HIGH' => $values[4],
'PSX_LOW' => $values[5],
'PSX_CLOSE' => $values[6],
'PSX_DATETIME' => date('Y-m-d H:i:s'),
'PSX_SATUS' => 1
);
insert_psx_data($psx_data);
}
}
$i++;
}
fclose($open);
I am first skip first two lines of test file and then I am checking if same symbol is already exist so then skip this line.
This method is working but too much slowdown and exceeding max exectution time.

Php file_put_contents with multiple files

I am using file_put_contents to create and add info to a json file. This works successfully, however I need to create two files with different names (title.json and dates.json) - is this possible?
The reason I need to do this is because I am using twitter typeahead and it seems to only work with separate json files.
It works with a single file i.e;
file_put_contents(URL . '/title.json', json_encode($data));
However not with this;
file_put_contents(URL . '/title.json', '/dates.json',
json_encode($data));
I receive the following error message;
Warning: file_put_contents() expects parameter 3 to be long, string
given in C:\xampp\htdocs... on line 23
$sql = ("SELECT DISTINCT pub_id, title, place_name, party_name, publication_date FROM vw_ft_search");
$data = array();
while($row = $result->fetch_assoc())
{
$data[] = array('title' => utf8_encode($row['title']),
'pub_id' => utf8_encode($row['pub_id']),
'place_name' => utf8_encode($row['place_name']),
'party_name' => utf8_decode($row['party_name']),
'publication_date' => $row['publication_date']);
}
file_put_contents(URL . '/title.json','/dates.json', json_encode($data)); //line 23
I am probably missig something very easy, any advice is appreciated.
file_put_contents only accepts one file. Use a loop to insert in all files ->
$files = array('/title.json', '/dates.json');
then iterate through $files:
foreach($files as $file)
{
file_put_contents(URL.$file, json_encode($data));
}

how do I pass many php variables to python

I am using the following code to initiate a python script and pass a php variable to it.
$tmp = exec("python path/to/pythonfile.py $myVariable $mySecondVariable", $output);
This works very well, my issue is that I will need to pass 100+ variables to the python script. I don't want this exec line to become extremely long and unmanageable. I have also explored passing a php array instead of a variable with the following code:
$checked = array(
"key1" => "1"
"key2" => "1"
"key3" => "1"
);
$checkedJson = json_encode($checked);
$tmp = exec("python path/to/pythonfile.py $myVariable $checkedJson", $output);
With this I have been unable to decode the JSON on the python side. I have been able to do a basic print of the array variable(undecoded) in python, but it gives every individual character as a new array value. ie [0] = k, [1] = e, [2] = y, [3] = 1, etc...
Any help is greatly appreciated.
Just to be clear,I am looking for a simpler method than encoding and decoding an array. Is there a way I can format the exec line to allow for multiple variables.
Store your PHP variables within a temporary text file then use python to read that file.
Simple and effective.
Assuming Scripts are in the same directory
PHP Portion
long version (self contained script - skip to the short version below if you only want the code snippet)
<?php
#Establish an array with all parameters you'd like to pass.
#Either fill it manually or with a loop, ie:
#Loop below creates 100 dummy variables with this pattern.
#You'd need to come up with a way yourself to fill a single array to pass
#$variable1 = '1';
#$variable2 = '2';
#$variable3 = '3';
#....
#$variableN = 'N';
#...
for ($i=1; $i<=100; $i++) {
${'variable'.$i} = $i;
}
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
#let's say N=100
for ($i=1; $i<=100; $i++) {
#for custom keys
$keyname = 'Key'.$i;
# using a variable variable here to grab $variable1 ... $variable2 ... $variableN ... $variable100
$phpVariablesToPass[$keyname] = ${'variable'.$i} + 1000;
}
#phpVariablesToPass looks like this:
# [Key1] => 1001 [Key2] => 1002 [Key3] => 1003 [KeyN] = > (1000+N)
#now write to the file for each value.
#You could modify the fwrite string to whatever you'd like
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
#close the file
fclose($fh);
?>
or in short, assuming $phpVariablesToPass is an array filled with your values:
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
fclose($fh);
Python Snippet to Grab the Data
lines = [line.strip() for line in open('temp.dat')]
the variable lines now contains all of your php data as a python list.

Categories