PHP and mysql question - php

hello everyone i'm having some problem ... question is i want to get the information from a form and save it in database the data is (comment, uploading pictures and email) when i did it it gave a warning
the code
// move file from temp location on server to your uploads folder
move_uploaded_file($F1["tmp_name"], "Uploads/$F1[name]");
print "Stored in: Uploads/$F1[name]";
// save location of upload to text file uploads.txt for later use
$datafile = fopen("uploads.txt","a");
flock($datafile,1);
fwrite($datafile, "Uploads/$F1[name]\n");
flock($datafile,3);
fclose($datafile);
// divide size by 1024 to get it in KB
/* if ($F1["size"] / 1024 > 50) {
print "Your gif file is too large! Less that 50KB please!";
exit(0);
}*/
if (!(IsSet($_FILE["fname"]))) {
$query="insert into guestbook (comments, email, img,display) values
('$_POST[comments]','$_POST[email]','some address ', '0')";}
else
$query="insert into guestbook (comments, email, img, display) values
('$_POST[comments]','$_POST[email]','some addres', '$_POST[0]')";
the warning i got is
Warning: move_uploaded_file(Uploads/holder.jpg): failed to open stream: No such file or directory in (address) on line 48
Warning: move_uploaded_file(): Unable to move '/tmp/php4OAZMC' to 'Uploads/holder.jpg' in (some address) on line 48
Stored in: Uploads/holder.jpg
how can i fix it ?
thanks in advance

I think it needs an absolute path for the file to be saved to, not a relative to the script location, i.e.
/home/meme/www/example.com/Uploads/
Also, check your permissions for the Upload directory. Also another little tip that'll save your bacon in the future- keep directory and filenames in lower case; then you won't get bitten in the bottom sometime in the future when your code is looking for a file or directory that doesn't exist because your filesystem is case sensitive!

Does the Uploads/ folder already exist? If not, trying creating it first. That might be causing the error.
Also, its a good idea to check if move_uploaded_file() worked or not. It returns true if it worked, and false if not.
Also, as already mentioned, try using an absolute path as well.
Reference

You should also ensure that your Uploads folder has it's permissions set correctly - For testing purposes, chmod the Uploads folder to 777 using your favourite FTP client.
Make sure that when you're ready to put your upload into practice you ensure you secure the folder properly (ensure not just anyone can write to it) and make sure you put filters in place for the file types.

Check to insure the path to move to exists, and your webserver process has rights to write to it.
Your insert query is a gaping security hole just waiting for a SQL injection. You can use the following to reduce the likelihood of getting hacked:
$comments = mysql_real_escape_string($_POST['comments']);
$email = mysql_real_escape_string($_POST['email']);
$query="insert into guestbook (comments, email, img, display) values
('{$comments}','{$email}','some address ', '0')";

Related

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).

How to get the path of a selected file in input type="file" using php?

I want to get the path of a selected file and store it in the database for future use.
I have the following code but it does not work.
$path = $_FILES['txtImage']['tmp_name'];
$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')";
txtImage is the name of my input type="file" and $path is the code i am using but it does not work. IT just returns blank.
Anyone who can help me or lead me to a different, hopefully easier method? Thank you in advance. :)
PHP will store submitted files in a temporary directory, which you shouldn't be storing in the database as it'll be volatile.
Use PHP's move_uploaded_file function to move the file to where you'd like in your file system, and then store that path in your database.
Docs: http://php.net/manual/en/function.move-uploaded-file.php
$tmp_path = $_FILES['txtImage']['tmp_name'];
$dest_path = path_where_in_your_server_you_want_this_image_to_be_moved.$_FILES['textImage']['name']; (eg: 'images/'.$_FILES['name'])
if(move_uploaded_file($tmp_path,$dest_path)){ //this will move the file from tmp location in server to the destination you provide in the second parameter
$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$dest_path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')";
}else{
echo "Image could not be uploaded"
}
Also keep in mind that there can be permission issues (with the directory that you want the image to be uploaded to) while uploading the file.
Good Luck!
Have you set your form enctype correctly on the HTML side so that it is correctly able to work as it should.
Secondly, TMP is just a temporary location, you MUST move that file to a server readble directory using PHP function move_uploaded_file
Read about enctypes, in this answer or on w3 schools.
<form name="YourForm" method="post" enctype="multipart/form-data" action="">

PHP letting the code add the uploader's last name to the image file he is uploading from a form

Got the server, got the domain, got the code, getting the images successfully, making the products for the customers from the image files they upload. Yay!
Problem: all my image names are image_0001 etc.
Customers can't rename image files from iPhones and do not care to from PCs.
So I was thinking about putting a short form on the upload page asking for customer's last name and having the PHP code attach that name to the image file(s) being uploaded.
If it's not possible, I'm sorry for the inconvenience.
You can rename files after they have been saved to your server, check out the PHP manual for the rename function - http://www.php.net/manual/en/function.rename.php, or just while you are moving them from the tmp directory, you can specify a different name for the uploaded file. See http://www.php.net/manual/en/function.move-uploaded-file.php
Be careful to include something in your code for dealing with naming conflicts.
This one might help :
$imagename = basename($_FILES['file']['name']);
$ext = pathinfo($imagename , PATHINFO_EXTENSION); //we want to change the file name but not the extension
$newImagename= $imageName.$username.'.'.$ext; //assuming you hold the username in $username
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$newImagename}"))
{
....
}

PHP Script is not Properly Uploading Images

I'm working on a small, user-maintained online store, and am trying to allow my end user (the store administrator) to upload graphics for products. When I run this script, however, it doesn't actually store the image. I built this script from various tips here and a tutorial, and have gotten everything but the image upload portion to work.
// Set the image target directory here
$target = "itemImages/";
$target = $target . basename($_FILES["image"]["name"]);
// Variables get POSTed here - just tack new ones on at the end.
// Various POSTs omitted for brevity
$pic=($_FILES["image"]["name"]);
// Places the picture in the folder
if(move_uploaded_file($_FILES["image"]['tmp_name'], "itemImages/"))
{
echo "The file " . basename($_FILES['uploadedfile']["name"]) . " has been uploaded.<br />";
}else {
echo "There was an issue adding this item. Please try again.<br />";
}
// Writes variables to the database
mysql_query("INSERT INTO tbl_item (itemNAME,itemDESC,itemCOST,itemHCOL,itemHSIZ,itemIMG)
VALUES ('$itemName','$itemDesc','$itemCost','$hasColor','$hasSize','$pic')");
mysql_close($con);
?>
Any help, tips, advice, insight, etc. would be very much appreciated.
move_uploaded_files requires a filename as its target. It does not blindly move to a directory, so
move_uploaded_files($_FILES..., 'somedir/somefile.txt');
works, but
move_uploaded_file($_FILES..., 'somedir/');
will not.
Plus, note that your database operation is vulnerable to SQL injection attacks. You're blindly inserting the uploaded file's remote name (['name'] via $pic), and that name is fully under the remote user's control.
Make sure the itemImages folder has write permission by the user your web server (e.g. Apache) is running as (e.g. www-data)
make sure the .php file and the folder you are writing to have the same "owner". Or try setting permissions on the itemImages folder to 777 (This is not recommended, just a debug tactic)

Why i am not able to delete the files(PHP)?

I use a form where i have listed the data from database like title, date etc. from the database and using checkboxes i use the multiple delete operation
For example my code look like this
<form method="post" action="action.php">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>"/>
<input name="delete" type="submit" id="delete" value="Delete"/>
and in the action.php the code is like this
$checkbox = $_POST['checkbox'];
//count the number of selected checkboxes in an array
$count = count($checkbox);
//Create a for loop to delete
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM news WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
Now the table i want to delete actually have 5 table entities like title, timestamp,pic_title,pic_brief,pic_detail the last three entities i.e pic_title, pic_brief and pic_detail is actually storing the path of the image for example the value stored in one of the 3 entity would look like this upload/file/pic_title1.jpg
My problem is when i run my first for loop it successfully deletes the table without any problem but the file which exist in the file directory remains intact. i want to delete that file too, to remove that file i thought of adding another for loop which i did something like this
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT news.pic_title, news.pic_brief, news.pic_detail FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_detail']);
}
The above code is unable to delete the requested file, my Query string is perfectly working fine i tested it by removing the unlink function and printing the values, it prints all the selected value , but it is refusing to delete the file and when i try to run the loop it shows error in the last three line, while i am pretty sure that, $row['pic_title'], $row['pic_brief'], $row['pic_brief'], have the full path of the image.
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_brief']);
where i am going wrong?
P.S: There is nothing wrong with file permission because when i individually try to run the function unlink it deletes the file from the same directory.
EDIT : This is the error message i get
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 580
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 581
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 582
To be more precise i tested this function individually in php and it is working perfectly fine
$target = 'upload/file/file1.jpg';
unlink($target);
and for this reason i dont think the file permission is causing the error, i guess i am going wrong somewhere with the logic.
#Lekensteyn got me the solution, thank you Lekensteyn.
actually i had to first hold the value in a variable and then unlink the file. the working code looks like this.
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT * FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic_title = $row['pic_title'];
$pic_brief = $row['pic_brief'];
$pic_detail = $row['pic_detail'];
unlink($pic_title);
unlink($pic_brief);
unlink($pic_detail);
}
It could be file permissions. You need to be the owner of the file in order to delete it.
Some hosters run the website under the user 'apache' (or similar), but the files are owned by the ftpuser (accountxxxx for example).
Check the current working dir too, with echo getcwd() if the paths not absolute.
Your script is vulnerable to SQL injection too, a post request with checkbox[]='||1||' deletes everything.
Add
error_reporting(E_ALL);
at the top of your script.
Your problem is program flow related and can be found only by using debugging.
Start from displaying ALL errors occurred and repair them. This will most likely lead you to the reason you could not delete your files.
Probably your path to upload is the problem. In your test script:
$target = 'upload/file/file1.jpg';
unlink($target);
I bet you ran that from a directory right below 'upload/' right?
And this delete script, it's probably not in the same directory?
I recommend using the full path to the 'upload/file/' directory; this will vary depending on your configuration, but probably looks like /www/htdocs/upload/file or /var/www/public_html/upload/file.
To make the script more transportable, you can use the PHP constant FILE to figure out the directory. I usually set this app/site wide in a bootstrap or universal configuration file, along the lines of
define('PATH', dirname(__FILE__)); # sets PATH with the directory name of the bootstrap file where this code lives
I sometimes key on something in my path I can rely on, say my app name. Say my bootstrap is here:
/www/apps/golf-scorecard/bootstrap.php
I might split on 'golf-scorecard'.
list($path,) = explode('golf-scorecard',dirname(__FILE__)); # $path should be /www/apps/
define('PATH', $path.'golf-scorecard'); # since I split on it, I have to add it back in
This means if I move the app/site to another server, or clone it from a repository onto a machine where the document root is, say /home/username/apps/golf-scorecard/htdocs/, then it won't matter. It does couple the app name but I am okay with that.
first thing is you need to check the file permissions .you need to give 777 permission to the folder.and then follow below code
$target = 'upload/file/file1.jpg';
unlink($target);

Categories