On a PHP page, I call an upload function that contains the standard PHP upload procedure. After I call the function, I do a redirect (tried with either window. location or header ()).
The strange thing is that everything works fine a couple of times, then it would not upload anymore (uploadOK won't be 0 either). It would just not move the file onto the server.
Then, I would take out the redirect and the upload would start working again. I put the redirect back in, the upload will still work a couple of times then stop again... Do you have any idea why?
Another strange thing is that, even when it doesn't work, the upload function still returns the correct path+filename, but it would not echo "File ... was uploaded".
I suspect that the problem might be in the move_uploaded_file() function... but it would not return 0, because "Error..." would not be echoed.
Without calling the redirect after the upload, it uploads fine every time.
PHP page:
$_SESSION["temp_file_name"]="../".UploadFisier($_FILES["fileToUpload"], $_SESSION["ID_CLASA"]."_".$id_item."_temp_".UserIdLogat($dbocr)."_", "../teme/", "");
header("Location: trimite_tema_script.php");
The Upload function:
function UploadFisier($file, $sufix, $target_dir, $maxsize)
{
if ($maxsize=="") { $maxsize=3000000; }
if ($target_dir=="") { $target_dir="../upload/"; }
$target_empty_file=$target_dir.$sufix;
$target_file = $target_empty_file.basename($file["name"]);
$uploadOk = 1;
if ($target_file != $target_empty_file)
{
if ($file["size"] > $maxsize)
{
echo "file too large";
$uploadOk = 0;
}
}
else
{
echo "no file selectec.";
$uploadOk = 0;
}
if ($uploadOk == 1)
{
//we overwrite
if (file_exists($target_file))
{
unlink($target_file);
}
if (move_uploaded_file($file["tmp_name"], $target_file))
{
echo "File ". basename( $file["name"]). " was uploaded.";
//we output the path and filename without the "../" at the beginning
$linksave=substr($target_file, 3);
}
else
{
echo "Error....";
}
}
echo "uploadOk ".$uploadOk;
return $linksave;
}
Check the file_uploads value in PHP.ini and confirm that is something like this
file_uploads = On
Wrap a try/catch in your code. maybe you will find out more about the error.
function UploadFisier($file, $sufix, $target_dir, $maxsize)
{
try {
// your code
} catch (\Exception $e) {
echo $e->getMessage();
die();
}
}
Related
In the web page I have 2 tabs and 1 submit button. I first tab inputs with type=text. In second inputs with type=file. I wanna to send both tabs with 1 submit. But problem isn't here. In the second tab I need to check files for error before sending them. So If it has an error then submit button isn't active. How can I do this?
Now I check them for error only after sending them. And when some of the files have an error then upload fails and its return to page with an error. And all other files which haven't error disappear from the input .
First tab http://prntscr.com/mnzc79 . Second tab http://prntscr.com/mnzca3 .
Here all inputs are the document of the student in university. So I can use just multi upload. Because all of them are a different files. I can't understand the mechanism of uploading many file inputs with error check.
Here my code
Check if text inputs uploaded. If files were set then I push them to the array to use in query.
if(!empty($_POST["first_name"])){
$keys=$keys."first_name,";
$first_name=$_POST["first_name"];
$values=$values."'".$_POST['first_name']."',";
}
if(!empty($_POST["last_name"])){
$keys=$keys."last_name,";
$last_name=$_POST["last_name"];
$values=$values."'".$_POST['last_name']."',";
}
...
...
Check if files uploaded
if(isset($_FILES["zayavlenie_o_zachisleniy"]["name"]) && !empty($_FILES["zayavlenie_o_zachisleniy"]["name"])){
array_push($uploads,"zayavlenie_o_zachisleniy");
upload("zayavlenie_o_zachisleniy");
}
...
...
Here checks file for error and upload
function upload($filename){
if (!file_exists('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo)) {
mkdir('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo, 0777, true);
}
$target_dir = 'student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo.'/';
$target_file = $target_dir . basename($_FILES[$filename]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
.....
}
// Check if file already exists
if (file_exists($target_file)) {
.....
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
.....
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
.....
} else {
if (move_uploaded_file($_FILES[$filename]["tmp_name"], $target_file)) {
array_push($values,$target_file);
echo "The file ". basename( $_FILES[$filename]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
$sql="UPDATE students set $set where id='$student_id'";
for($i=0;$i<sizeof($uploads);$i++){
if($i==(sizeof($uploads)-1)){
$sql=$sql."'".$uploads[$i]."'";
}
else{
$sql=$sql."'".$uploads[$i]."',";
}
}
$db->insert($sql.")");
You can either do this with javascript or php. If you are checking if the file does already exist on your webserver, you can't do this ONLY using javascript. So you need to check this with php, cause php is running on your server. Javascript not.
So, when you encounter any error while uploading the files (like already existing files or wrong file formats) you can redirect the user to any page you want and cancel the request like this:
header("Location: http://YourErrorPage.com");
exit;
I've the following PHP script launching on click of a submit form button :
<?php
//header('Location: video_download.html');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$new_name = 'logo'.'.'.$imageFileType;
$target_file = $target_dir . $new_name;
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["logo"]["tmp_name"]);
if($check == false) {
echo "File is not an image.\n";
$uploadOk = 0;
}
}
// Check file size
if ($_FILES["logo"]["size"] > 5000000) {
echo "Sorry, your file is too large.\n";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "png") {
echo "Sorry, only PNG files are allowed.\n";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.\n";
if (file_exists("config.txt")) {
unlink("config.txt");
}
if (file_exists("upload/logo.png")) {
unlink("upload/logo.png");
}
// if everything is ok, try to upload file & create config.txt
} else {
if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
$template = $_POST['template'] . "\n";
$club = $_POST['club'] . "\n";
$stats = $_POST['stats'];
if (file_exists("config.txt")) {
unlink("config.txt");
}
file_put_contents("config.txt", $template . $club . $stats);
echo '<meta http-equiv="Refresh" content="0; url=video_download.html">';
shell_exec("./blender_lite/bin/blender -b -P blender.py");
exit();
} else {
echo "There was an error uploading your file.\n";
exit();
}
}
?>
I want it to redirect the browser to another html page after executing all script's content. I've tried two different approach : the header (commented in the above code) and echoing an html meta tag with a redirection.
Both doesn't work for unknown reasons and I can't find it (already passed many hours trying to find other methods and resolve the issue without success, so I guess it's kind of a specific issue with a part of my php script). Any help is welcome, thanks :)
You would use the header function.
header("Location: http://www.website.com/page.php");
exit();
Replace the part of your code where you echo the meta refresh with the header location command and place it at the end of your logic. This will only redirect when everything else is complete then.
Example:
if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
$template = $_POST['template'] . "\n";
$club = $_POST['club'] . "\n";
$stats = $_POST['stats'];
if (file_exists("config.txt")) {
unlink("config.txt");
}
file_put_contents("config.txt", $template . $club . $stats);
shell_exec("./blender_lite/bin/blender -b -P blender.py");
header('Location: video_download.html'); // <-- put redirect here
exit();
} else {
echo "There was an error uploading your file.\n";
exit();
}
Found out that the redirection worked fine as I did on my first post. The issue was that PHP waits for the shell_exec to be over. Thus, since I was launching a blender rendering with shell_exec, it was taking several minutes to end so I thought the redirection was not working.
Using exec('bash -c "exec nohup setsid ./blender_lite/bin/blender -b -P blender.py > /dev/null 2>&1 &"');
instead of shell_exec("./blender_lite/bin/blender -b -P blender.py");
so the PHP script doesn't wait for the command to end is the solution, the redirection is now immediate.
I have a very simple function:
unlink($oldPicture);
if (is_readable($oldPicture)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}
}
The file shows not readable after execution and disappears from the file directory. However, it's still available when accessed from the browser despite not being cached (opened the file on separate browsers for testing). Is there something I am missing here? Is the file being cached by the server? That is the only explanation I could come up with.
Try something like:
if (is_file($oldPicture)) {
chmod($oldPicture, 0777);
if (unlink($oldPicture)) {
echo 'File deleted';
} else {
echo 'Can\'t remove file';
}
} else {
echo 'File does not exist';
}
Make sure you have full path for $oldPicture
Example:
$oldPicture = dirname(__FILE__) . '/oldpicture.png';
EDIT: got it working, but could still use help. Please see below in edit section.
I've searched all over, but this is really confusing me.
I have a form that allows for multiple file uploads. Each file input is named "track[]" so that way it can get associated into an array. When the form is submitted, I set the file information into an array here:
private $tracks = [];
public function setTracks () {
$length = count($_FILES['track']['name']);
for ($i=0; $i < $length; $i++) {
$this->tracks[$i] = ["file_temp" => $_FILES['track']['tmp_name'][$i],
"file_name" => $_FILES['track']['name'][$i],
"file_size" => $_FILES['track']['size'][$i],
"file_type" => $_FILES['track']['type'][$i],
"target_path" => "tracks/" . $_FILES['track']['name'][$i],
"file_error" => $_FILES['track']['error'][$i]];
}
}
This creates the array just fine, but I'm finding it difficult trying to actually save the file by getting the information I need from this array.
This is my rather basic method for uploading images. How can I adapt this for uploading tracks?
public function uploadImg () {
if ($this->file_size > $this->img_max_size) {
echo "The file size is too large. Please compress it and try again.";
}
if (move_uploaded_file($this->file_temp, "../../" . $this->target_path)) {
echo "The image ". $this->file_name . " has been uploaded successfully!";
}
else {
echo $this->file_error . "There was an error uploading the image, please try again!";
}
}
By the way, I think a foreach loop would be better in both my setTracks and my new uploadTracks methods I'm trying to make, rather than the for loop I am currently implementing, but I wasn't able to figure out how to use one in this case.
EDIT: I'm not sure exactly what I did, but I got this to work. Still, if somebody could help me change my for loop to a foreach it would be greatly appreciated. Here's my method that handles the upload:
public function uploadTrack () {
$length = count($this->tracks);
for ($i=0; $i < $length; $i++) {
if ($this->file_size > $this->track_max_size) {
echo "The file size is too large. Please compress it and try again.";
}
else if (move_uploaded_file($this->tracks[$i]["file_temp"], "../../" . $this->tracks[$i]['target_path'])) {
echo "The image ". $this->file_name . " has been uploaded successfully!";
}
else {
echo $this->file_error . "There was an error uploading the image, please try again!";
}
}
}
This is the PHP code used for the upload:
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
} else { echo "Error"; }
When I test the script, it says "The file has been uploaded successfully." but when I check the FTP server, it hasn't really...
Also, if you need to know, here's the HTML codes:
Form tag:
<form name="profilestyle" action="account.php?action=profiletheme" method="post" enctype="multipart/form-data">
Input tag:
<input type="file" name="bgimage" />
Extra Information:
Yes, I remembered the CHMod the uploads directory
Odd, the code looks fine as far as I can see.
Can you use file_exists() to check whether the file exists, but maybe is not visible to your FTP user?
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file '$upload' has been uploaded successfully.";
if (file_exists($upload)) echo "And it exists! It is ".filesize($upload)." bytes big.";
else echo "But it doesn't exist.";
} else { echo "Error"; }
You also need to check $_FILES['bgimage']['error'] to make sure it is equal to UPLOAD_ERR_OK and is not an error code.
Please try the following test code
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
sprintf('<pre>Debug: moving file from %s to %s</pre>',
$_FILES['bgimage']['tmp_name'],
$upload
);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
sprintf('<pre>Debug: realpath=%s, filesize=%d</pre>',
realpath($upload),
filesize($upload)
);
}
else {
echo "Error";
}
and esp. keep an eye on the realpath=xyz output.