Hi stackoverflow family ,
my problem is that i want to upload multiple files (php/html/css etc..) and keep my old version of files like github does, like to upload new files and when i want go back to my olds files i find it and i can download it i searched in stackoverflow if there's someone that asked about this topic to help me and i didn't find anything
the main idea is that i can upload files (html/css/sql etc..) and when i want to upload new files i can anytime go back and find the old version of files like github exactly
<form method="POST" action="php/upload.php" enctype="multipart/form-data">
<div class="control-panel">
<label>Project folder name</label>
<input type="text" name="directoryName"><br>
<label>Project name</label>
<input type="text" name="projectName"><br>
<label>Project description</label>
<textarea name="description"></textarea><br>
<span>PUSH PROJECT</span>
<input type="file" name="uploadedFile" />
</div>
<input type="submit" class="uploadBtn button5" name="uploadBtn" value="Push" />
</form>
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "github";
$description = $_POST["description"];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_SESSION["username"];
$message = '';
echo "hello";
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Push')
{
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
{
// get details of the uploaded file
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// sanitize file-name
$newFileName = (date("Y-m-d")."_".time()."_". $fileName) . '.' . $fileExtension;
// check if file has one of the following extensions
$allowedfileExtensions = array('jpg', 'php', 'html', 'zip', 'txt', 'xls', 'doc');
if (in_array($fileExtension, $allowedfileExtensions))
{
// directory in which the uploaded file will be moved
$dirc = $_POST["directoryName"];
mkdir($dirc);
$uploadFileDir = './'.$dirc.'/';
$dest_path = $uploadFileDir . $newFileName;
$projectName=$_POST["projectName"];
$sql = "INSERT INTO project
VALUES ('$user', '$dest_path','$description','$projectName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if(move_uploaded_file($fileTmpPath, $dest_path))
{
$message ='File is successfully uploaded.';
}
else
{
$message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
}
}
else
{
$message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
}
}
else
{
$message = 'There is some error in the file upload. Please check the following error.<br>';
$message .= 'Error:' . $_FILES['uploadedFile']['error'];
}
}
$_SESSION['message'] = $message;
//begin *********************************************************************
header("Location: ../");
Related
I want to upload image to the server and save the file name in MySql. I am uploading from image from Android Application , i am sending all the required params from android app but still something is wrong in copy image in server. It is echoing "Upload Failed".
<?php
$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];
include('../Config.php');
$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
$filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
if($type == "Address"){
$sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
}else if($type == "ID"){
$sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
}else if($type == "GramPanchayat"){
$sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
}
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
}
?>
Let's start here. I would change the copy() function to the move_uploaded_file() function.
Secondly, You need to check to make sure the path for the download destination exist. If it does not then we need to create it.
We also need to make sure the folder/file has permissions to be able to write. If it does not then change the folder/files permission.
Then when done, change your folder/files permissions back to what they were originally.
Like so:
$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];
include('../Config.php');
$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
//Check to see if the folder exist.
if(!file_exists($uploaddir)) {
mkdir($uploaddir, 0777, true); //If it does not exist then create it and set permissions to be able to write.
}
//The folder does exist at this point. Check to see if it's writable.
if(!is_writable($uploaddir)){
chmod($uploaddir, 0777); //The folder is not writeable. Set the folder to be able to write.
}
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
$filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
if($type == "Address"){
$sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
}else if($type == "ID"){
$sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
}else if($type == "GramPanchayat"){
$sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
}
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//Reset the permissions back to what you need them to be.
//You probably want 0755
chmod($uploaddir, 0755);
chmod($uploadfile, 0644); //Sets your new file to read only.
//Add this code below to test.
if(file_exists($uploadfile)) {
echo 'Your file exist.';
}else{
echo 'You file does not exist.';
}
}
else
{
echo "Upload failed";
}
}
Some resources for you to read.
move_uploaded_file()
is_writeable()
chmod()
You will also want to read up on file permissions an how to properly set them. Not doing this correctly can leave you open to unwanted security issues.
Hope this helps.
Actually My problem is when I am registering user profile on localhost is working fine and image is storing in folder but after published is not storing image in folder.
my php code
$target_dir = "../upload/";
$target_file = $target_dir . basename($_FILES["photo"]["name"]);
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file);
}
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "SELECT email FROM register where email='$email'";
$qur = $connection->query($sql);
if(mysqli_num_rows($qur)==0)
{
$password = md5($_POST["password"]);
$birth = $_POST["birth"];
$sql = "INSERT INTO register(name, email,password,photo,birth)
VALUES ('$name','$email','$password','$target_file','$birth')";
$success = $connection->query($sql);
if (!$success) {
die("Couldn't enter data: ".$connection->error);
}else{
echo "Thank You For registration";
}
}else{echo "Email-id already exist";
}
most of the time server need dont allow to upload data.
you need to give permission to your upload folder and it will work
You can check your error: $_FILES['photo']['error']
You can get more detail from here :- http://php.net/manual/en/features.file-upload.errors.php
I have to create a CMS for a webstore for a webscript unit i'm taking. I have to upload a photo of the product but i keep getting and error when i try to upload. I search it a lot and tried a lot of things, i changed the folder to read & write, i did the 'chmod -R 777...', nothing. I'm starting to think the problem is with my code. I appreciate all help, thanks!
I always this error: Warning: File upload error - unable to create a temporary file in Unknown on line 0
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$dbname = 'ezcart';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Could not connect to the database: " . $conn->connect_error);
}
$name = $_FILES['photo']['name'];
$size = $_FILES['photo']['size'];
$type = $_FILES['photo']['type'];
$tmp_name = $_FILES['photo']['tmp_name'];
if (isset($name)) {
if(($type == 'image/jpeg' || $type == 'image/jpg' || $type = 'image/png') && ($size <= 3145728)) {
$path = 'prod_photos/';
if (move_uploaded_file($tmp_name, $path.$name)) {
$sql = "INSERT INTO product (prodCat, prodDes, prodNam, prodPho, prodPri, prodSto, prodSup) VALUES ('$_POST[prodCat]', '$_POST[prodDes]', '$_POST[prodNam]', '$name', '$_POST[prodPri]', '$_POST[prodSto]', '$_POST[prodSup]')";
if ($conn->query($sql) === TRUE) {
echo '<span>Product added sucessfully.</span>';
}
}
}
else {
echo '<span>Please choose a valid photo.</span>';
}
}
$conn->close();
?>
You should check your php.ini and look for the 'upload_tmp_dir' option.
After that, check the permission of your tmp dir, and try to chmod it again.
If you want to know what upload_tmp_dir your server is using, you can simply use this:
die(ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir());
I’m a novice in php and html, and I found some codes that allowed me to upload files to a remote server using a html form and a php code.
I tested the code locally using wamp and I found some bugs, like I cannot overwrite an existing file and the formatting of the name of the file is not taken into consideration.
The files that I would like to upload are named in French and have spaces between them, the server is a debian server.
The goal of this code is to retrieve a URL.
The HTML code:
<form enctype="multipart/form-data" action="remote_upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
The PHP code:
$ftp_server = "192.168.1.111";
$ftp_user_name = "";
$ftp_user_pass = "";
$remote_dir = "C:\wamp\www";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = #ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//default values
$file_url = "";
if($login_result) {
//set passive mode enabled
ftp_pasv($conn_id, true);
$file = $_FILES["uploadedfile"]["tmp_name"];
$remote_file = $_FILES["uploadedfile"]["name"];
$ret = ftp_nb_put($conn_id, $remote_file, $file, FTP_BINARY, FTP_AUTORESUME);
while(FTP_MOREDATA == $ret) {
$ret = ftp_nb_continue($conn_id);
}
if($ret == FTP_FINISHED) {
echo "File '" . $remote_file . "' uploaded successfully.";
} else {
echo "Failed uploading file '" . $remote_file . "'.";
}
} else {
echo "Cannot connect to FTP server at " . $ftp_server;
}
I have been struggling for some time with getting this single button upload to work, i have tried several methods to submit the upload and this one i have seems to work up to the point of the php but then something in the php seems to not like the submit, without the js this works as a regular select file and upload, but soon as i add the js (which appears to work) the php then doesnt work.
Im totally confused why this is happening!
Any advice appreciated thanks!
The upload form
<form name="form" method="POST" enctype="multipart/form-data" action="updateProfilePic_script.php">
<div class="update_header_pic">
<input type = 'button' value = 'Choose image'
onclick ="javascript:document.getElementById('Photo').click();">
<input id='Photo' type='file' style='visibility: hidden;' name='Photo' onchange='submit();'/>
</div>
</form>
The php
<?
session_start();
$user = $_SESSION['username'];
$hostname = "localhost";
$db_user = "xxxusername";
$db_password = "xxxpassword";
$database = "xxxdatabase";
$db_table = "user_profile_pic"; // image table
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
$uploadDir = 'usermedia/users/images/profileimages/'. $user .'/';//Image Upload Folder
if (!is_dir($uploadDir) && !mkdir($uploadDir)){
die("Error creating folder $uploadDir");
}
if(isset($_POST['submit'])) {
$date = date("Y-m-d H:i:s");
$unique = substr(number_format(time() * rand(),0,'',''),0,10);
$fileName = $unique .'-'.$_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image , username , datetime , filesize , filetype ) VALUES ('$filePath' , '$user' , '$date' , '$fileSize' , '$fileType' )";
mysql_query($query) or die('Error, query failed');
header('Location: edit_myProfile.php');
}
?>
In your HTML form there is no [input type=submit] then why in your PHP code you did:
if(isset($_POST['submit'])) {
//...
//..
}
You can simply change it to:
if(isset($_FILES['Photo'])) {
//the your uploading procedure
}