How can i get variable out of a class? - php

I am trying to get variable out of a class but seems that I am not doing it correctly.
Here is code for upload_inc.php
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
echo $this->user_full_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = "File size error (0): $this->user_file_size KB<br>";
if ($this->user_file_size > $this->max_filesize)
$this->error = "File size error (1): $this->user_file_size KB<br>";
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name. " from " . $userfile . "to destination directory.";
echo 'test file' . $userfile;
}
}
}
In the second page after uploading the file, I am trying to get only the file name. Then, I can store the file name in my database. Here is my code.
upload.php
// Defining Class
$uploaded = new upload;
// Set Max Size
$uploaded->set_max_size(350000);
// Set Directory
$uploaded->set_directory("data");
// Do not change
// Set Temp Name for upload, $_FILES['file']['tmp_name']
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
// Set file size,
$uploaded->set_file_size($_FILES['file']['size']);
// Set File Type,
$uploaded->set_file_type($_FILES['file']['type']);
// Set File Name,
$uploaded->set_file_name($_FILES['file']['name']);
// Start Copy Process
$uploaded->start_copy();
// Control File is uploaded or not
// If there is error write the error message
if($uploaded->is_ok()){
echo "successfully loaded <br />";
}else{
echo $uploaded->error()."<br>";
}this should show only file name but it does not.

Why do you expect the class to contain the filename in the member variable? Where are you assigning it to the member variable? All I see is that you are creating a new class (besides, it should be "new upload();", you missed the parentheses) whose member variables are not initalized. So you get a null value when doing the echo, which is the expected result.
What do you try to achieve? If you want the class-instance to "keep" its values across different request-response cycles you would have to store the whole instance somewhere (seralizing it) and restoring it when needed (unserializing it). You could also simply store the filename in the session if that is all you need.

I'm not sure what you're trying to achieve but as far as the error you're currently getting... You'll need to create a constructor for your Upload class that accepts a value for $user_file_name and then set it. Alternatively you can use set_file_name() before trying to use the $user_file_name var. As it stands right now that value is never being set, which is why you're getting an error on your call to echo.
Also, as others have said, you should really go back and accept answers to your questions if you found them helpful.

Main thing which you need is good IDE, with smart code highlighting :)
I recommend PhpStorm (not ideal, but best at this moment, I hope somebody will create something better).
In your code $userfile are not defined. You can define this variable:
$userfile = $this->user_tmp_name;
in function start_copy().

Related

Can't upload larage size pdf file in laravel [duplicate]

I am getting the undefined index error as I come for the first time in my upload form page or if I move to next page and click on back button then I have the same error message.
If I upload a file then it works fine and the error message gets away.
I have also tried this:
global $file;
if (!isset($file)) {
$file = '';
}
Here is my code:
<form id="uploadForm" name="upload" enctype="multipart/form-data"/>
<fieldset>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="file" />
<?php
echo '<pre>';
var_dump($_REQUEST['file']);
echo '</pre>';
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
?>
<div class="filesize">JPG minimaal 800x60 pixels max. 2Mb</div>
<span> Upload your own photo </span>
upload_inc.php
<?
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = 'File size error (0):' . $this->user_file_size . 'KB <br>';
if ($this->user_file_size > $this->max_filesize)
$this->error = 'File size error (1):' . $this->user_file_size . 'KB<br>';
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name . " from your folder to destination directory.";
}
}
}
?>
"Undefined index" means you're trying to read an array element that doesn't exist.
Your specific problem seems to be that you're trying to read upload data that doesn't exist yet: When you first visit your upload form, there is no $_FILES array (or rather, there's nothing in it), because the form hasn't been submitted. But since you don't check if the form was submitted, these lines net you an error:
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
They're all trying to read the value of $_FILES['file'] to pass them to the methods of $uploaded.
What you need is a check beforehand:
if (isset($_FILES['file'])) {
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
}
The error is probably in your upload class. The error message is pretty clear, if that is the actual message you get there is probably a line somewhere in that class that looks for an array key I that is named 'fileUpload'.
Just do a search in your code for 'fileUpload', and add something to check if the key is set, ie
if(isset($arraywhatever['fileUpload'])) condition to your code.

How to copy the set of files from one folder to another folder using php

I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");

When file_put_contents fails if the directory is full, a file with size 0 is created. How to avoid that?

When the tmp directory is full, file_put_contents returns FALSE but the file is created with size of 0. file_put_contents should either complete the creation of the file or have no effect at all. For example:
$data = 'somedata';
$temp_name = '/tmp/myfile';
if (file_put_contents($temp_name, $data) === FALSE) {
// the message print that the file could not be created.
print 'The file could not be created.';
}
But when I go to the tmp directory, I can find the file "myfile" created in the directory with size 0. This makes it difficult to maintain. The file should not be created and I would like to see a message or warning the the tmp directory is full. Am I missing anything? And is this normal behaviors?
You are probably missing that if you do the error messages, you need to take care of that scenario, too:
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if ($success === FALSE)
{
$exists = is_file($temp_name);
if ($exists === FALSE) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}
This will also allow you to deal with it, like cleaning up if the transaction to write to the temporary file failed, to reset the system back into the state like before.
The problem is that file_put_contents will not necessarily return a boolean value and therefore your condition may not be appropriate you could try:
if(!file_put_contents($temp_name, $data)){
print 'The file could not be created.';
if(file_exists ($temp_name))
unlink($temp_name);
}
hi bro i found the Solution,
i know its old but its maybe help other people like me,
i was search about this code long time.
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if (!$success){
$exists = is_file($temp_name);
if (!$exists) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}

Set File Size Limit Message

I wonder whether someone could help me please.
I have to admit I'm relatively new to writing PHP so please bear with me.
Through articles I've read on the internet and some first class tutition from one #Marcio on this site, I've put together a script that allows users to save Image Files to a mySQL database.
I've now gone a little further by restricting the size of the file that can be uploaded, but I I'd like to add a warning message that tells why the file cannot be uploaded i.e. because it's size is greater than the limit set.
I've made an attempt at this, as seen in the code below. But unfortunately I receive an error message stating that there is an unexpected '>' which I know relates to the line I've added, but not sure how to code this another way.
Revised Cut Down Code
<?php
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No title provided';// use (empty title) string
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = 'Success: Image Uploaded';
}
}
I just wondered whether someone could perhaps take a look at this and let me know what I'm doing wrong.
Many thanks and kind regards
You can use this
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
getfilesize() returns image dimensions in pixels, not file size. You need something along the lines of this:
if (filesize($_FILES['tmp_name']) >= 100000)

Undefined index: file

I am getting the undefined index error as I come for the first time in my upload form page or if I move to next page and click on back button then I have the same error message.
If I upload a file then it works fine and the error message gets away.
I have also tried this:
global $file;
if (!isset($file)) {
$file = '';
}
Here is my code:
<form id="uploadForm" name="upload" enctype="multipart/form-data"/>
<fieldset>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="file" />
<?php
echo '<pre>';
var_dump($_REQUEST['file']);
echo '</pre>';
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
?>
<div class="filesize">JPG minimaal 800x60 pixels max. 2Mb</div>
<span> Upload your own photo </span>
upload_inc.php
<?
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = 'File size error (0):' . $this->user_file_size . 'KB <br>';
if ($this->user_file_size > $this->max_filesize)
$this->error = 'File size error (1):' . $this->user_file_size . 'KB<br>';
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name . " from your folder to destination directory.";
}
}
}
?>
"Undefined index" means you're trying to read an array element that doesn't exist.
Your specific problem seems to be that you're trying to read upload data that doesn't exist yet: When you first visit your upload form, there is no $_FILES array (or rather, there's nothing in it), because the form hasn't been submitted. But since you don't check if the form was submitted, these lines net you an error:
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
They're all trying to read the value of $_FILES['file'] to pass them to the methods of $uploaded.
What you need is a check beforehand:
if (isset($_FILES['file'])) {
$uploaded = new upload;
//set Max Size
$uploaded->set_max_size(350000);
//Set Directory
$uploaded->set_directory("data");
//Set Temp Name for upload.
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
//Set file size
$uploaded->set_file_size($_FILES['file']['size']);
//set file type
$uploaded->set_file_type($_FILES['file']['type']);
//set file name
$uploaded->set_file_name($_FILES['file']['name']);
//start copy process
$uploaded->start_copy();
if($uploaded->is_ok())
echo " upload is doen.";
else
$uploaded->error()."<br>";
}
The error is probably in your upload class. The error message is pretty clear, if that is the actual message you get there is probably a line somewhere in that class that looks for an array key I that is named 'fileUpload'.
Just do a search in your code for 'fileUpload', and add something to check if the key is set, ie
if(isset($arraywhatever['fileUpload'])) condition to your code.

Categories