Why this error comes as per i upload multiple images? - image

When i upload multiple images from my code, everything is uploaded to mysql database, but displays error with saying success :
I just don't want this error.[Error is :Notice: Undefined variable: user_id in C:\wamp\www\swaminarayant\multiple_file_up.php on line 13]
Can anyone help me out of this?
My code is:
<?php include 'connect.php';?>
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}?
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>

Look at your Code around Line 13:
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES
('$user_id','$file_name','$file_size','$file_type'); ";
Within the VALUES part you try to include a variable $user_id which was never defined above.
Youre setting the other values properly:
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_type=$_FILES['files']['type'][$key];
But you are missing a definition for $user_id. If you insert for example:
$user_id = "foo";
Or
$user_id = 1;
In case it must be a number you should be all good.

Related

controller method is not working and page is refreshing instead of redirecting to given path in laravel

I am not getting any error, it's just refreshing on that page. The controller method is not called where I have given the path for redirection.
My code is:
blade-file
<form action="{{route('validate-promocode')}}" method="post">
#csrf
<input class="promo-input" id="code" type="text" onkeyup="this.value = this.value.toUpperCase();" name="code" placeholder="EG. APPLY HERE"><br>
<input type="hidden" name="_token" value="{!!csrf_token()!!}">
<button id="save" type="submit" class="apply-promo">Apply Promo Code</button>
</form>
Route file
Route::post('/validade-code', 'PromoController#validateCode')->name('validate-promocode');
Controller file
public function validateCode(Request $request){
if (Gate::allows('isUser')) {
$ip = $request->input('code');
dd($promo);
$promo = Promo::where('code','=', trim($ip))->first();
if(!empty($promo)){
$dataamountMonthly = 40000 - (($promo->discount_percentage * 40000) / 100);
$dataamountYearly = 300000 - (($promo->discount_percentage * 300000) / 100);
if($dataamountMonthly == 0 || $dataamountYearly == 0){
return view('paymet.subscription-success');
}
$data = array(
'dataamountMonthly' => $dataamountMonthly ,
'dataamountYearly' => $dataamountYearly,
'code' => $ip
);
return view('payment.startPromoCode',$data);
}else{
$data = array(
'error' => 'Something went wrong, please try again'
);
return redirect()->back()->with($data);
}
}
}
I don't know what I am missing , any help will be appriciated.
Solved
Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group or has all of the session middleware applied
I think according to your code
$promo = Promo::where('code','=', trim($ip))->first();
the value of $promo can be null/ empty
and instead of executing your expected code it is redirecting back the page, and it seems the refresh for you. rest your code is correct.

Laravel View::render() gives error

I'm trying to render a view with čćžšđ letters in it, but it's failing and giving me this error:
The Response content must be a string or object implementing __toString(), \"boolean\" given."
I extracted a partial, and when I load this partial using normal way (with #include) then everything is ok.
But I need "load more" function, so I'm using this partial to render html for me, and I only append it to DOM using jQuery.
This is the partial:
<?php $flag = true; ?>
#foreach($tags as $tag)
#if(empty($tag->tag)) <?php continue; ?> #endif
#if($flag == true)
<?php $temp = $tag->tag[0]; ?>
<br><label class="firstLetterLabel">{{ strtoupper($temp) }}</label><br><hr><br>
<?php $flag = false; ?>
#endif
#if($temp != $tag->tag[0])
<br><label class="firstLetterLabel">{{ strtoupper($tag->tag[0]) }}</label><br><hr><br>
#endif
<div class="singleTag">
{{ $tag->tag }}
</div>
<?php $temp = $tag->tag[0]; ?>
#endforeach
This is how I use it in "load more" function:
$tags = Tag::orderBy("tag")->take(Config::get("settings.num_tags_per_page"))->skip(($page-1)*Config::get("settings.num_tags_per_page"))->get();
$data = array();
$data['data'] = View::make("discover.partials.tags")->with("tags", $tags)->render();
if(count($tags)%Config::get("settings.num_tags_per_page") == 0 && count($tags) > 0)
$data['msg'] = 'ok';
else
$data['msg'] = 'stop';
return json_encode($data);
This partial read tags and sort them alphabetically, and it extracts first letter of every tag because I need that letter somewhere else.
And when this partial finds one of these letters čćžšđ then it gives me above error.
How to solve this?
Try this:
json_encode($output, JSON_UNESCAPED_UNICODE)
For future notice, I solved this problem by replacing $tag->tag[0] with mb_substr($tag->tag, 0, 1). This command extracts utf-8 characters from string while my previous approach wasn't properly encoding utf-8 chars.
More info here: Get first character of UTF-8 string

Simple Perl and CGI::Ajax form validation

I'm trying to do a real simple setup.
1.Do checks on each field using CGI::Ajax.
2.Validate that all fields have been filled in with simple perl CGI
The thing is, when testing individually, both work, but when combined as seen in the code below I have two issues:
1.In the username and password fields I see CGI=HASH(0x228ed48) etc
2. When I push the submit button and there is an error (a field is empty), it prints an internal server error, I believe this is due to $ajx->build_html( $cgi, \&form($error, $username, $password)); and calling the form function in this manner.
Any ideas?
Thanks in advance.
#!/usr/bin/perl -w
use CGI;
use CGI::Session qw/ -ip-match/;
use CGI::Ajax;
$cgi = new CGI;
#$session = new CGI::Session(undef, $cgi, {Directory=> '/tmp'});
my $ajx = new CGI::Ajax( 'checkuser' => \&checkuser );
#print $ajx->build_html( $cgi, \&form);
if($cgi->param("submit")) {
process(); } else { print $ajx->build_html( $cgi, \&form); }
sub checkuser
{
my $input = shift;
my $out = $input . " is not taken";
return $out;
}
sub form {
my $error = shift;
my $username = shift;
my $password = shift;
my $html = <<HTML;
<html>
<BODY>
<form id='log' action='session.cgi' method='post' accept-charset='UTF-8'>
<input type="hidden" name="submit" value="Submit">
<fieldset>
<legend>Login</legend>
<font color="red">$error</font>
<label for='username' >UserName*:</label>
<input type='text' name='user' id='user' value="$username"
maxlength="50" onchange="checkuser( ['user'], ['resultdiv'] );">
<br><br>
<div id="resultdiv"></div>
<label for='password' >Password*:</label>
<input type='password' name='pd' id='pd' value="$password" maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
</body></html>
HTML
return $html;
}
sub process
{
if(validate_form()) {
print $cgi->header;
print <<HTML;
<body>Validated<br></body>
HTML
}
}
sub validate_form
{
my $username = $cgi->param("user");
my $password = $cgi->param("pd");
my $error = "";
$error .= "Please enter your username<br/>" if ( !$username );
$error .= "Please specify your password<br/>" if ( !$password );
if ( $error )
{
$ajx->build_html( $cgi, \&form($error, $username, $password));
return 0;
}
else
{
return 1;
}
}
For development, use CGI::Carp qw/fatalsToBrowser/;. This will allow you to see the actual errors your code is producing, rather than "Internal Server Error".
Update: Also, your code is failing because you are misunderstanding how a callback function works. The callback function is not called by you; it is called by the code you pass it to--in this case the module. So you can't provide parameters, the module does. This won't work:
$ajx->build_html( $cgi, \&form($error, $username, $password));
build_html wants to call the function you pass in internally, with its own parameters.
Here you are not allowing to happen. Instead you are calling form() before you call build_html(), then passing in a scalar reference to the result. This fails later, because build_html tries to use that scalar reference as a subroutine reference.
Solution: you just need to use \&form. You will need another way to fill in the fields.
Also:
Form validation is a very common task. Mature Perl modules are available and are widely used for this (for example, HTML::FormFu and Data::Formvalidator). There are also some related modules that appear to add Javascript validation (HTML::FormFu::ExtJS, JavaScript::DataFormValidator). It is probably worth checking these out before you create your own.
Most modern Perl web development is done using a web framework of some sort. The available frameworks are very powerful and worth using for all but the simplest projects. If your goal is to learn, I recommend starting with a framework as early as possible, because development using a framework is quite different from traditional CGI development, and there is a learning curve. I am quite happy with Catalyst, and there are other options as well, such as Mojolicious and Dancer.

Unexpected change in Session value on form submission in Firefox

I am having an issue with PHP session in Firefox. There is a change in Session after each refresh/page reload. On other browsers, it is working fine.
In my WordPress template, I have initialized the session, comparing the post/session variables. A shortcode "inf_kit" defined in functions.php file will be called while executing "the_content()" function.
The shortcode defined in functions.php will call functions kit() and CSRF() which will set a session variable and add a hidden text field to the form, returned in my template. When I submit the form, I am getting a different value. In IE, Chrome is it OK. Does someone have any idea, where the issue might have?
Code in template file
<?php
session_start();
if(isset($_POST["s_405"])){
print_r($_SESSION);
if($_SESSION['token_valid'] == $_POST['token_valid']) echo 'Good'; else echo 'issue';
}
the_content();
?>
Code in functions.php
<?php
add_shortcode( 'inf_kit', 'kit');
function kit($atts){
$form .= '<form name="kit" method="post">
<input type="hidden" value="'.time().'" name="s_405"/>'
. CSRF('valid').
'</form>';
return $form;
}
function CSRF($key){
$tkn = sha1($key.uniqid(rand(), true));
$_SESSION['token_'.$key] = $tkn;
return '<input type="hidden" name="token_'.$key.'" value="'.$tkn.'">';
}
?>

filename and contenttype of upload image

how to get the name of the file and the content type of the image which we uploaded in mvc application please tell me its urgent
thanks
ritz
May be below code will be helpful..
//index..
<?php
require_once("include/DBConnect.php");
include_once('header.php');
?>
<div align="center">
<h1 style="color:red">Welcome </h1>
<br/>
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit" id="SubmitButton" value="Upload" />
</form>
</div>
<?php include_once('footer.php');?>
//upload
<?php
require_once("include/DBConnect.php");
require_once("include/FunctionGeneral.php");
include_once('header.php');
if(isset($_POST))
{
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
// check $_FILES['ImageFile'] array is not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something went wrong with Upload!'); // output error .
}
// Random number for both file, will be added after image name
$RandomNumber = rand(0, 9999999999);
// Elements (values) of $_FILES['ImageFile'] array
//let's access these values by using their index position
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.'thumbnail/'.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
echo '<div id="output">';
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$thumb_DestRandImageName.'" alt="Thumbnail"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestRandImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
echo '</div>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
$added = getCurDate();
$title = "test";//$dbObj->escape_special_char($_POST['title']);
session_start();
$_SESSION['user_id'] = "rakhi";
$user_id = $_SESSION['user_id'];
$fields = "`photo_title` ,`createuser` ,`image_name` ,`added`";
$values = "'$title','$user_id','$NewImageName','$added'";
}else{
die('Resize Error'); //output error
}
}
include_once('footer.php');
?>

Resources