php upload script not uploading - but it is adding to database? - php

A weird problem when i am trying to make a banner art upload system for user profiles.
I have searched for answers, but none have solved it.
It is not a permissions problem, my chmod is 755 on uploads folder and in the upload.php file.
code below:
if ($_POST && !empty($_FILES)) {
$formOk = true;
//Assign Variables
$path = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
$formOk = false;
echo "Error: Error in uploading file. Please try again.";
}
//check file extension
if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
$formOk = false;
echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
}
// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo "Error: File size must be less than 3 MB.";
}
if ($formOk) {
// read file contents
$content = file_get_contents($path);
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'hidden', 'hidden', 'hidden')) {
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$content = mysqli_real_escape_string($conn, $content);
$sql = "insert into banners (user_id, username, name, size, type, content) values ('{$user_id}','{$username}','{$name}', '{$size}', '{$type}', '{$content}')";
if (mysqli_query($conn, $sql)) {
$uploadOk = true;
$imageId = mysqli_insert_id($conn);
} else {
echo "Error: Could not save the data to mysql database. Please try again.";
}
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
}
And the form is:
<form method="post" enctype="multipart/form-data" action="<?=$_SERVER['PHP_SELF']?>" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<img src="<?php print_r($path); ?>"/>
<?php print_r($_FILES); ?>
<input type="text" name="user_id" value="<?php echo $user->data["user_id"]; ?>" readonly/>
<br />
<input type="text" name="username" value="<?php echo $user->data["username"]; ?>" readonly/>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload">
</div>
</form>
I have the form in the same file upload.php along with my include header and footer.
So basically it stores the data into the database, but just will not upload what so ever, i also checked the phpinfo and so on, and all is ok, it is turned on, and file limit in phpinfo is 64mb, so i don't get why it wont upload?
any help would be appreciated, thanks

Simple: You didn't move that file anywhere, as in move_uploaded_file().
http://php.net/manual/en/features.file-upload.post-method.php
Base yourself on the following example taken from the manual:
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
and check for errors too.
http://php.net/manual/en/function.error-reporting.php

I just wanted to post how i did it, thanks to Fred and some other comments others made :)
//Assign Variables
$username = $user->data['username'];
#mkdir("uploads/".$username,0755);
$target_dir = "../uploads/$username-";
$path = $target_dir . basename($_FILES['image']['tmp_name']);
$name = $target_dir . basename($_FILES['image']['name'].$user_id);
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if (move_uploaded_file($_FILES['image']['tmp_name'], $name)) {
echo "<h2>Thank you for uploading your banner art - File is valid, and was successfully uploaded.\n</h2>";
} else {
echo "Possible file upload attack!\n";
}
so I also made it so it now puts a username in front of the uploaded images name too.
The form is pretty much the same, I now also made it so that the upload and update open in a nice fancy box :)
https://gyazo.com/e12a03ce01d8f503b8fa2e79f5605809
Thanks again everyone :)

Related

upload video file using php

I am trying to upload file using php and i get error of form not submit whenever everything is right according to me below is the code video upload form
<form action="tek.php" method="POST" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name"><br/>
<input type="text" name="mobile" placeholder="Mobile No."><br/>
<input type="file" name="videouser" ><br/>
<input type="file" name="audiouser" ><br/>
<input type="submit" name="submit" value="Submit">
</form>
and below is my tek.php page code
if(isset($_POST["submit"])){
$name = $_POST["name"];
$mobile = $_POST["mobile"];
$video_dir = "admin/video/";
$temp = explode(".", $_FILES["videouser"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["videouser"]["tmp_name"], "/admin/video/" .$newfilename)or die("not uploading a video");
$videofile = rand() . basename($_FILES["videouser"]["name"]);
if(move_uploaded_file($_FILES["videouser"]["name"], $video_dir.$newfilename))
{
echo "upload video successfull";
}else{
echo "video file not uploaded";
}
$audio_dir = "admin/audio/";
$audiofile = rand() . basename($_FILES["audiouser"]["name"]);
if(move_uploaded_file($_FILES["audiouser"]["name"], $audio_dir.$audiofile) or die("Not Uploaded audio"))
{
echo "upload audio successfull";
}else{
echo "audio file not uploaded";
}
}else{
echo "form not submitted.";
}
above code of tek.php page work fine for image but not for video or audio file i also increase limit post_max_size = 500M and upload_max_size = 500M where i make mistake don't know please help thanks in advance.
Change following codes:
if(move_uploaded_file($_FILES["videouser"]["tmp_name"], $video_dir.$newfilename))
{
echo "upload video successfull";
}else{
echo "video file not uploaded";
}
$audio_dir = "admin/audio/";
$audiofile = rand() . basename($_FILES["audiouser"]["name"]);
if(move_uploaded_file($_FILES["audiouser"]["tmp_name"], $audio_dir.$audiofile) or die("Not Uploaded audio"))
{
echo "upload audio successfull";
}else{
echo "audio file not uploaded";
}
you should use tmp_name instead of name in the move process
Hi Friends i got the answer
1. first configure your php.ini
2. if you use wamp then you get php.ini in wamp/bin/php/php7.0.10(php version)/php.ini
3. set in php.ini
post_max_size = 10240M
upload_max_filesize = 500M
4. Restart Your wamp server(must)
now the code to upload video below in upload.php
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type =$_FILES['file']['type'];
if (!file_exists('uploaded_here')) { // file will be uploaded in this folder
mkdir('uploaded_here', 0777, true);
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploaded_here/".$file_name);
echo "Uploaded in folder uploaded_here file name is : ".$file_name;
}else{
echo "Not Uploaded";
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="file_extension|audio/*|video/*|image/*|media_type">
<br>
<input type="submit" value="Upload">
</form>
its working for me

How to upload img file in php

I'm trying to upload a file in a server with PHP, but i have some problems. I have found this guide: http://www.sumedh.info/articles/store-upload-image-postgres-php-2.html.
My html is:
<form action="img_user.php" method="POST" enctype="multipart/form-data" >
<button id="buttonImgProf" class="btn" type="button" onclick="caricaImgProf()">Inserisci un immagine</button>
<div id="imgProfLoader" class="postContent" style="display:none;">
Name : <input type="text" name="name" size="25" length="25" value="">
<input type="file" name="userfile"></input>
<button class="btn" type="submit">Carica immagine</button>
</div>
</form>
(parts are not displays because i use javascript). The php code is:
$uploaddir = 'localhost'; //i have try lots of dir, maybe the error is here?
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$name = $_POST['name'];
echo $_FILES['userfile']['tmp_name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{ echo "File is valid, and was successfully uploaded.\n";
}
else { echo "File not uploaded"; }
the output is File not uploaded
your upload path($uploaddir = 'localhost'; ) should be physical path not should be url so change localhost to any path like ($uploaddir = "uploads/")
full demo code :
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
then your form page
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
The "upload.php" file contains the code for uploading a file:(it is action page for file upload form)
<?php
$target_dir = "uploads/";
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// you can write anything in this folder
} else {
die('Upload directory is not writable, or does not exist.');
}
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
PHP script explained:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there.
$uploaddir = 'localhost'; - localhost is for database connection purposes, not for a folder upload directive; use a folder that is writeable.
As per the manual http://php.net/manual/en/features.file-upload.post-method.php
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
I put your HTML and PHP code in a single file and wrapped your PHP code with a "not empty" $_FILES and it seems to work fine. Here's the full file.
I have also removed the display:none; style you had put on your div to make it useable, since you did not provide the contents of your caricaImgProf() function. Oh and the $uploaddir cannot be a domain such as localhost, it must be a valid directory, so I removed your localhost reference, so that the file uploads right next to where the script is (same directory) which you shouldn't do in a production server of course, but it's off topic :P
This single file should be named img_user.php :
<?php
if(!empty($_FILES)){
$uploadfile = basename($_FILES['userfile']['name']);
$name = $_POST['name'];
echo $_FILES['userfile']['tmp_name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{ echo " / File is valid, and was successfully uploaded.\n";
}
else { echo "File not uploaded"; }
exit();
}
?><html>
<body>
<form action="img_user.php" method="POST" enctype="multipart/form-data">
<button id="buttonImgProf" class="btn" type="button" onclick="caricaImgProf()">Inserisci un immagine</button>
<div id="imgProfLoader" class="postContent">
Name : <input type="text" name="name" size="25" length="25" value="">
<input type="file" name="userfile" />
<button class="btn" type="submit">Carica immagine</button>
</div>
</form>
</body>
</html>
It outputs this when I submit a picture file and the file correctly gets saved right next to the PHP script in the same folder with the original filename before the upload:
E:\wamp64\tmp\php38E6.tmp / File is valid, and was successfully
uploaded.

How to change the name of a picture selected by client and save it in Server with a different name

I have the following code to upload to my server an image than the user sends through an input type=file.
My questions is: How can I change the name of the file?
Example: let's say than the user upload the following file: "mypicture.jpg" and I want to save it with the name of a variable I have stored, like $username where $username = John so even the user selected "mypicture.jpg" the file will be save in my directory (/var/www/html/images/) as John.jpg
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uploaddir = '/var/www/html/images/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
pg_close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Thank you so much
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $username . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/html/images/" . $newfilename);

How can I get the picture I uploaded to my sever link to my website

I have created a basic car sales website. I have used the following PHP code to upload my image
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
So the file is being uploaded to the server and that is great (took me ages to get it to work), I am using phpliteadmin as my database manager and I have a field called car_image_url, this is where i paste the url to the image on the server, however I have added a page on the site where users can upload an image themselves, so my question is how can I get this to work.
I am using the following to convert the url to display an image.
echo "<td id='img'><img src=\"". $row["car_image_url"] . "\" /></td>";
However uploading the file is a different story, what code do I use on my website to get the uploaded file to link to the image url.
Here is my PHP code that makes a new car on the main site:
<?php
try {
# Connect to SQLite database
$dbh = new PDO("sqlite:../Car_Sales_Network");
$make = $_POST['Make'];
$model = $_POST['Model'];
$badge = $_POST['Badge'];
$price = $_POST['Price'];
$trans = $_POST['Transmission'];
$ppl = $_POST['P_Plate_Legal'];
$sth = $dbh->prepare('INSERT INTO Cars_On_Network
("car_make","car_model","car_badge","price","trans","P_Plate_Legal")
VALUES
(?, ?, ?, ?, ?, ?)');
$sth->execute(array($make, $model, $badge, $price, $trans, $ppl));
$id = $dbh->lastInsertId();
//header("Location: ../Carsales_Network.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>New Vehicle</title>
<link type="text/css" rel="stylesheet" href="New_Car_Form.css"/>
</head>
<body>
<div id="main">
<form action="Insert_Car.php" method="post" enctype="multipart/form-data">
Make:<br>
<input type="text" name="Make">
<br>
Model:<br>
<input type="text" name="Model">
<br><br>
Badge:<br>
<input type="text" name="Badge">
<br>
Price:<br>
<input type="text" name="Price">
<br>
Transmission: <br>
<input type="radio" name="Transmission" value="Manual" checked>Manual
<br>
<input type="radio" name="Transmission" value="Auto">Automatic
<br><br>
P Plate Legal: <br>
<select name="P_Plate_Legal">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Choose a Picture: <br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<br>
<br>
<input class="submit" type="submit" value="Submit">
<br>
Let's go back!
<br>
</div>
</body>
</html>
</form>
</body>
</html>
I am sure it is a similar process however I just can't think of how to do it.
Cheers.
it seems to me like youre having trouble with the upload script.
Here is a way that comes in handy (It creates an unique name for all images)
Crate your sql within the WRITE TO DATABASE comment i made:
if(isset($_FILES['fileToUpload'])){
$File = $_FILES['fileToUpload'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'jpeg', 'gif');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error?
if($FileError==0){
//Create new filename:
$NewName = uniqid('', true) . '.' . $FileExt;
//Destination
$UploadDestination = $_SERVER['DOCUMENT_ROOT'] . '/Cars_Photos/' . $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Filename = $NewName
//WRITE TO DATABASE:
//encode url:
$Image = urlencode($UploadDestination);
//Redirect:
header("Location: /complete.php?image=$Image&cat=Cars");
}
//File didnt upload:
else{
echo "File didnt upload...";
}
}
//An error occured
else{
echo "An error occured while uploading...";
}
}
//Filetype not allowed
else{
echo "Sorry, the file you tried to upload is not allowed.";
}
}
Complete.php:
<?php
//Your file is here:
echo urldecode($_GET['image']);

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories