I am used to writing AJAX using the following structure, where I would end up sending variables to PHP
function requestToggle(type, user, elem) {
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "request_system.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText == "request_sent") {
_(elem).innerHTML = 'OK Request Sent';
} else if (ajax.responseText == "unrequest_ok") {
_(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type=" + type + "&user=" + user);
}
The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.
Here is the PHP
<?php
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
echo $result;
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
exit();
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
exit();
}
$sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
//delete old pic if set
if($avatar != ""){
$picurl = "users/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
//move file from temp folder to users folder
$moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
if ($moveResult != true) {
$result = "File upload failed";
echo $result;
exit();
}
include_once("image_resize.php");
//replace original file with resized version
$target_file = "users/$log_username/$db_file_name";
$resized_file = "users/$log_username/$db_file_name";
$wmax = 400;
$hmax = 600;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
//header("location: user.php?u=$log_username");
$result = "upload_success";
echo $result;
exit();
}
?>
UPLOAD FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);
Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:
$files= $_REQUEST['files'];
Related
I am attempting to create a page that will register information. I also need to be able to upload an image to the form, but when I add the image it gives me an error when I attempt to upload saying the file is not an image. I have attempted to change the parameters of what it will take as far as .jpeg, .png, etc. Can anyone see what I am doing wrong with the uploading?
if ($valid) {
$filetype = pathinfo($_FILES['profileimg']['name'], PATHINFO_EXTENSION);
if ((($filetype == "gif") or ($filetype == "jpeg") or ($filetype == "png")) and $_FILES['profileimg']['size'] < 200000) {
if ($_FILES['profileimg']['error'] > 0) {
$valid = false;
$fileError = $_FILES['profileimg']['error'];
$imageError = "<p class='error'>Return code: $fileError<br>";
switch ($fileError) {
case 1:
$imageError .= 'The file exceeds the uploads_max_filesize setting in php.ini.</p>';
break;
case 2:
$imageError .= 'The file exceeds the max_file_size setting in the HTMl form.</p>';
break;
case 3:
$imageError .= 'The file was only partially uploaded.</p>';
break;
case 4:
$imageError .= 'No file was uploaded.</p.';
break;
case 5:
$imageError .= 'The temporary folder does not exist.</p>';
break;
default:
$imageError .= 'something unexpected happened.</p>';
break;
}
} else {
$imageError = $_FILES['profileimg']['name'];
$file = "uploads/$imageName";
$fileInfo = "<p>Upload: $imageName<br>";
$fileInfo = "Type: " . $_FILES['profileimg']['type'] . "<br>";
$fileInfo .= "Size: " . ($_FILES['profileimg']['size'] / 1024) . "Kb<br>";
$fileInfo .= "Temp file: " . $_FILES['profileimg']['tmp_name'] . "</p>";
if (file_exists("$files")) {
$imageError = "<span class='error'>$imageName already exists.</span>";
$valid = false;
} else {
move_uploaded_file($_FILES['profileimg']['tmp_name'], $file);
if (move_uploaded_file($_FILES['profileimg']['tmp_name'], $file) == true) {
$fileInfo .= "<p>Your file has been uploaded. Stored as: $files</p>";
$query = "INSERT INTO 'membership' VALUES (default, '$first', '$last', '$username', '$email', '$password', '$imageName');";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (!$result) {
die(mysqli_error($conn));
} else {
$row_count = mysqli_affected_rows($conn);
if ($row_count == 1) {
$memberID = mysqli_insert_id($conn);
$loggedIn = true;
$msg = "<p>Record inserted</p>";
} else {
$msg = "<p>Insert failed</p>";
}
}
} else {
$imageError .= '<p><span class="error">Your file could not be uploaded.';
}
}
}
} else {
$imageError .= '<span class="error">Invalid file. This is not an image.</span>';
$valid = false;
}
}
}
I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}
I want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>
I just extend a column on my db table. So I try to put data on that table. I have 10 more column on that table. There is a column name _source_ and if its value become 1 then my new column input data correctly. but if its value became 2 then my new column show null. I check and re-check my function from last two days. I can't understand what I am missing!
Here is my full function PHP code:
function regular_upload($inputname, $ftp_server){
global $site_url;
$ok=1;
$upload_name = $inputname;
// AICI VERIFICAM DACA A FOST ADAUGATA O FILA
if (!isset($_FILES[$upload_name])) {
//header('Location: index.php');
echo 'No upload found in \$_FILES for ' . $upload_name;
$ok=0;
//exit();
} else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) {
// echo $uploadErrors[$_FILES[$upload_name]['error']];
echo "<p class='error'>No files</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name'])) {
echo "<p class='error'>Upload failed is_uploaded_file test.</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['name'])) {
$ok=0;
echo "<p class='error'>File has no name.</p>";
//exit();
}
// DACA ADULT NU E NUMERIC DIEEEEE
if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
$adult = $_POST['adult'];
} else {
die("You didn't specify if your file(s) are Adult or Non-Adult");
}
if(is_numeric($_POST['thumb_size_contaner'])) {
$thumbnail_size = $_POST['thumb_size_contaner'];
} else {
die("Injection detected");
}
if($ok == 1) {
// verificare tipul de imagini - un fel de whitelist
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
// blacklist ce nu tre sa fie
$filename = strtolower($_FILES[$upload_name]['name']);
$blacklist = array('php', 'php3', 'php4', 'phtml','exe'); #example of black list
foreach ($blacklist as $item) {
if(preg_match("/$item\$/i", $filename)) {
echo "<p class='error'>We do not allow uploading PHP files</p>";
$ok=0;
//exit();
}
}
}
if($ok == 1) {
// de aici setam dimensiunea maxima a imaginii
list($width, $height, $type, $attr) = getimagesize($_FILES[$upload_name]['tmp_name']);
if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
{
echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
$q = "SELECT img, thumb FROM sources WHERE id = '1'";
$result = mysql_query($q);
if(mysql_num_rows($result) > 0) {
$rowSources = mysql_fetch_array($result);
} else {
die("Something went wrong : ". mysql_error());
}
$data_year = date('Y');
$data_month = date('m');
$data_day = date('d');
if($ftp_server == 0) {
$dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
if(!file_exists($dir) OR !is_dir($dir)){
mkdir($dir, 0777, true);
}
if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
mkdir($dirthumb, 0777, true);
}
} else {
$q = "SELECT * FROM ftp_logins
INNER JOIN sources ON ftp_logins.source_id = sources.id
WHERE ftp_logins.id = $ftp_server
";
$result = mysql_query($q);
if(!$result) {
echo mysql_error();
}
$rowFTP = mysql_fetch_assoc($result);
$dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$FTP = new FTP();
$FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
global $ftp_conn_id;
if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
}
if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
}
}
//$uniquenumber = uniqid('', true);
$uniquenumber = uniqid();
$view_id = uniqid();
$target = $dir;
$extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
//$filename = $_FILES['uploaded']['name'];
$nameimage = $uniquenumber . "." . $extension;
$target = $target . "/" . $uniquenumber . "." . $extension;
$uploaded_size = $_FILES[$upload_name]['size'];
//echo $uploaded_size;
//This is our size condition
if ($uploaded_size > MAX_UPLOAD_SIZE*1024) { // IN KB
echo "<p class='error'>Your file is too large.</p>";
$ok=0;
}
}
//This is our limit file type condition
if ($ok==0) {
echo "<p class='error'>Sorry your file was not uploaded </p>";
} else {
//If everything is ok we try to upload it
if($ftp_server == 0) {
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $target)) {
echo "<p class='success'> ". basename( $_FILES[$upload_name]['name']). " has been succesfuly uploaded </p>";
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$target_thumb = $dirthumb;
$resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
$image = new SimpleImage();
$image->load($target);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($resizeuploadpatch);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$site_url}/{$dir}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$site_url}/{$dir}/{$nameimage}</div>";
} else {
echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
}
} else { // if FTP SERVER
$ftp_temp_img = "cache/ftp/".$nameimage."";
$ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $ftp_temp_img)) {
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$image = new SimpleImage();
$image->load($ftp_temp_img);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($ftp_temp_thumb);
}
if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_img in $target\n";
} else {
//echo "There was a problem while uploading $ftp_temp_img in $target\n";
}
if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
} else {
//echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
}
$FTP->disconnect($ftp_conn_id);
unlink($ftp_temp_img);
unlink($ftp_temp_thumb);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";
} // ftp end
} // ELSE IF EVERYTING IS OK, IF ERROR = 0
} // END FUNCTION
I am really frustrated with this and I can't find what is causing the error.
Here is the database screenshot:
I'm trying to create a social network site and I've been watching tutorials where the users can upload their profile picture and change their avatar. However, whenever I try to upload a picture it gives me an error 'File upload failed' I'm not very sure how to fix it or what exactly to do. Where exactly do I need to dump all the pictures the users have uploaded?
photo_system.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
user.php
$profile_pic = "";
$profile_pic_btn = "";
$avatar_form = "";
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
$profile_pic_btn = 'Toggle Avatar Form';
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">';
$avatar_form .= '<h4>Change your avatar</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
}
Create directory first if not exist
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
if(!file_exists($picurl)){
mkdir($picurl, 0777,true);
}
}