Destroying array element + unlink file - php

after uploading files they get converted into a new array. im making a display function to display uploaded files + to destroy them on click
function display($type){
// echo $type;br();
// prettyR($_SESSION[$type]);
// echo"<hr>";
prettyR($_POST);
if(isset($_POST["del"])){
$p = $_POST["del"];
prettyR($_SESSION["misc"][$p]);
unlink($_SESSION["misc"][$p]["filename"]);
// $_SESSION["misc"][$p]["filename"] looks like this: upload/63eb3d2b83068_misc.jpg
unset($_SESSION["misc"][$p]);
}
echo"<form method='post'><input type='hidden' name='ka'></form>";
// this form is here so that the other forms work, because the display is in another form
if($type == "misc"){
// echo"<hr>";
// echo"hi";
foreach($_SESSION[$type] as $file){
echo"<hr>";
// echo"hi";
echo $file["name"];
$key = $file["type"];
echo"<form method='post'> <input type='hidden' value='$key' name='del'>";
echo"<input type='submit'>";
echo"</form>";
}
}
}
but instead this message appears
Warning: Undefined array key "63eb3d2b83c20" in
im expecting this function to delete the files from the folder and to unset the informations from the misc array

ifound the answer: ive been using a live server on vscode. that means right after the files get deleted the page reloads again, that means that the web server tries to unset something that doesnt exist. im sorry for my bad explenation, english istn my native language

Related

PHP Post data not received

i'm currently working on a small script for my Homepage but i ran into a problem.
I Try to upload an Image, but it seems like the POST data from the form is not being received. What did i do wrong?
I already changed the post_max_size and everything in the php.ini.
These are the Errors i get:
"Notice: Undefined index: image in ...." & "Notice: Undefined index:
submit in ...."
<form method="POST" action="/eye/sites/handling/post.php" enctype="multipart/form-data">
<div class="fileUpload">
<span><i class="fa fa-folder-o" aria-hidden="true"></i> Bild wählen</span>
<input type="file" class="upload" name="image"/>
</div>
<input type="submit" value="Upload It!" name="submit"/>
</form>
<?php session_start();
error_reporting(E_ALL);
if (isset($_SESSION["login_stat"])) {
date_default_timezone_set('Europe/Berlin');
$config = "$_SERVER[DOCUMENT_ROOT]/eye/more/config.xml";
$xml = simplexml_load_file($config);
$picWidth = $xml->pic->width;
$picHeight = $xml->pic->height;
$fulldate = date('dmYHis');
if(isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
$typeCheck = $_FILES['image']['type'];
if ($typeCheck != "image/jpeg") {
$error = "Not a .jpg";
header('location: /eye/sites/post.php?stat=bad&error='.$error);
exit;
}
$file = $_SERVER['DOCUMENT_ROOT']."/uploads/".$fulldate.".jpg";
$type = "image/jpeg";
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$file_thmb = $_SERVER['DOCUMENT_ROOT']."/uploads/!1A_thmb/".$fulldate.".jpg";
include "resize-class.php";
$resizeObj = new resize($file);
$resizeObj->resizeImage($picWidth, $picHeight, 'crop');
$resizeObj->saveImage($file_thmb, 100);
// header('location: /eye/sites/post.php?stat=good');
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No File');
}
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No Data');
echo $_SERVER['CONTENT_TYPE'];
echo "<br>";
echo $_FILES['image']['tmp_name'];
echo "<br>";
echo $_POST['submit'];
echo "<br>";
}
} else {
header('location: /eye/index.php?stat=in');
}
?>
Edit:
The problem is definitely about my Localhost.
This whole thing is working fine on my Webspace, but on my localhost it's not working.
BUT: I'm not getting errors anymore, when is click on Submit it goes to the php file that should save the image, but nothing is happening. I just see a white Page.
But like i said, it runs perfectly on my webspace..
If this is running on your local machine, do a quick check to make sure your "php.ini" file is configured to allow file uploads.
php.ini
file_uploads = On
The codes look fine. Check if your form action is posting to the correct path and if I may suggest using a simpler approach to test your file upload function before making it more complex. Use the following to start testing.
if (isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
echo "Upload is working!";
}
}
Keep us updated on your findings.
Perhaps this general information will help someone, as it helped me: a submitted form will only include fields that have defined 'name' attributes. 'id' is not enough.
The idea is that 'id' identifies an element in the DOM for use by JavaScript (either as a global variable or for use in document.getElementById(ID)), but 'name' identifies those elements whose names and values will be sent to the destination ('action') page.
So it makes sense that there are two different identifying attributes, used in two different ways.

Passing php variables from php1 to php2, then having php2 return a new value assigning to variable from php1

This may sound really broken but essentially my intentions are for in php1, have a name for example validate to match a regex, if it fails to meet the conditions it will then redirect to php2 where there awaits a form where a user can retype it and submit it back to php1 where it will do the checks again. Then finally in the first php, if everything works ok it will echo it back.
Also how would i expand it so multiple things such as credit cards etc. can be validated too?
Thanks
php1
if (isset ($_POST["CardHolder"])) {
cardholder = $_POST["CardHolder"];
cardholder = sanitise_input($cardholder);
if (!preg_match("/^[a-zA-Z\s]{1,40}$/", $cardholder)) {
$errMsg .= "First name can only contain alpha characters, please re-enter";
$newcardholder = $_POST["newcardholder"];
$cardholder = $newcardholder;
}
else {
$cardholder = $_POST["CardHolder"];
}
if ($errMsg != "") {
header("Location: fix_order.php?errMsg=".$errMsg)
}
php2 (fix_order.php)
if (isset ($_GET["errMsg"])){
$cardholder = $_GET["errMsg"];
echo "<form action='process_order.php' method='post'>"
."<p><label>$cardholder:</label>"
."<input type='text' name='newcardholder'/></p>"
."<p><input type='submit' value='Submit'/>";
"</form>";
}
When calling header("Location:...") you need to give the full and absolute URL.
so header("Location: fix_order.php") will not work.

How to delete database row in this php script

I have a situation with my php code. What I am currently doing is using the iframe to link the javascript message with the phe script. In the javascript function stopImageUpload, I have stated that if success = 2, then display the cancel message for the file upload.
So what I have tried but failed to do in the php script is to try and state that if the $result = 2 (In other words if success = 2 message appears in javascript), then delete the database row. How can this be done?
Below is the form code:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='imageCancel' class='imageCancel' value='Cancel' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
Below is the startImageUpload() function where it starts an file upload and where the cancel button function is stored:
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).find(".imageCancel").on("click", function(event) {
return stopImageUpload(2);
});
return true;
}
Below is the stopImageUpload() function where it displays the cancel message using success and result:
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 2){
result = '<span class="imagecemsg"> The file upload was canceled!</span><br/><br/>';
} else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Finally below is the imageupload.php script which is linked to the QandATable.php (The script which contains the code above) using iframe and this is where the database row is suppose to be inserted and deleted from:
<?php
session_start();
...//connected to DB
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
if ($result == 2) {
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/".
mysql_real_escape_string($_FILES['fileImage']['name'])."'";
mysql_query($imagecancelsql);
}
mysql_close();
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
There are severe issues with your code that need to be addressed:
1)
This line:
return stopImageUpload(2);
Is calling the function:
function stopImageUpload(success, imagefilename){...}
But the stopImageUpload function needs two parameters, success and imagefilename
2)
This function returns true, but should return the contents of result.
function stopImageUpload(success, imagefilename){
...
return true;
}
3)
Here you set $result with the value 0, and compare it with the value 2 ?!?
$result = 0;
if ($result == 2) {
4)
This function accepts two parameters, but none of them is used inside ?!?
function startImageUpload(imageuploadform, imagefilename){...}
Also, it is returning
return stopImageUpload(2);
or
return true;
Are you controlling this situation!
Note: Where do you use this function ?!?
5)
This verification likely fails because file_exists checks whether a file or directory exists. So, if the file does not exist, surely the directory does, and it will continue to execute.
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
you should use is_file that tells you if the file is a regular file.
6)
You should not be using mysql_query anymore, please read PDO Tutorial for MySQL Developers
mysql_query($imagesql)
Please read this topics: to learn why are you failing to achieve your goal
PHP Variables
JavaScript Variables
JavaScript Functions
PHP File Upload e.g. 1 | PHP File Upload e.g. 2 | PHP File Upload e.g. 3
I hope this may help you getting on the right track and fixing some issues with your present code.
Best of Luck!

How to i post image id to php along with $_FILE

index.html with form tag
<input type='file' name='picture' id='".$row['sfname']."'onchange='javascript:ajaxFileUpload(this);'/>`
ajax code
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<div><img src="ajax-loader.gif" border="0" /></div>';`
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
upload.php
<?php
?>
I want $row['sfname'] in index.html to be accessed along with $_FILE variable here but how can I get the script to store the image in given folder so that I can store the path in the respective user record.
I have tested the upload.php by uploading the files successfully to the file system, now I want the file path to be stored in the sql table. For that I need the user first name the same I get it from the same
My question is; How do I access the input tag ID using the above ajax code to upload.php?
Why not simply put $row['sfname'] as a value of a hidden field as your JavaScript is submitting the whole form?
<input type='hidden' name='sfname' value='" . $row['sfname'] . "'>

I am getting an undefined variable

I am trying to retrieve a file name from one page where the php script uploads the file (imageupload.php), and I want to display it in another page within a javascript function (QandATable.php). But I don't know how to do this
I will show you all of the relevant code so you can follow it and so you are able to understand what is happening.
UPDATE: BELOW I WILL SHOW YOU THE STEPS ON HOW THE FILE IS UPLOADED. THE CODE BELOW SUCCESSFULLY UPLOADS THE FILE.
Below is the form (QandATable.php);
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
<label>Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><ul class='listImage' align='left'></ul>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
On the same page when the user submits the form, it will go onto the function below, it will check for validation and then when validation is clear, it will go onto the startImageUpload() function:
function imageClickHandler(imageuploadform){
if(imageValidation(imageuploadform)){
return startImageUpload(imageuploadform);
}
return false;
}
If there is no validation then it will go onto the JS function (QandATable.php) below where it hides the file input and it will submit the form to the imageupload.php where the file uploading occurs. When the file is uploaded it then calls back to the stopImageUpload() function (QandAtable.php) where it will display the message on whether the file is uploaded or not and this is where I want the name of the file from the server to be appended.
Below is startImageUpload() function:
var sourceImageForm;
function startImageUpload(imageuploadform){
$(imageuploadform).find('.fileImage').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
Below is the php script where it uploads the file (imageupload.php):
<?php
session_start();
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.stopImageUpload(<?php echo $result;?>);
</script>
Finally when upload is finished it goes back to the stopUploadImage() function (QandATable.php) to display the message on whether file is successfully uploaded or not. This is also where I want the uploaded file name from the server to be appended.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Your $_POST won't contain fileimagename. Instead, your form input was called fileImage. Use that instead:
// Check $_POST for fileImage, which was the form input name
if (isset($_POST['fileImage'])) {
$_SESSION['fileimagename'] = $_FILES['fileImage']['name'];
// Proceed with the file upload and save.
}
else {
// oops, can't proceed
}
On the JavaScript page, do some error checking when accessing the value:
<?php
session_start();
if (isset($_SESSION['fileimagename'])) {
$fileimagename = $_SESSION['fileimagename'];
// output JS code...
?>
<script type="text/javascript">Your JS code here...</script>
<?php
}
else {
// No filename - can't proceed with JavaScript code
// Display an eror or a message with instructions for user...
}
Note: Don't use the user-supplied filename to store the image! It opens you up to a directory traversal attack, and makes it possible for the user to write a file anywhere on your filesystem the web server has write-access to.
// This is unsafe!
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
Instead, it's common to store the value from $_FILES['fileImage']['name'] in your database, along with an identifier value for the actual file, and use the identifier to store it on disk.
$info = pathinfo($_FILES['fileImage']['name']);
// Get the original extension
$filext = $info['extension'];
// Make a unique filename and add the extension
$stored_filename = uniqid() . $filext;
// Use that to store the file on disk
move_uploaded_file($_FILES["fileImage"]["tmp_name"], $stored_filename);
// Now store BOTH $_FILES['fileImage']['name'] and $stored_filename in your database together
// The original user-supplied filename can be used for display, but isn't used on disk

Categories