PHP - Uploading File Via Curl Problem
Hi All, I have been having issues for several days uploading a simple pdf file via Curl to one of our service providers servers. I'm doing an is_uploaded_file check and getting a successful response, but the document is not actually being uploaded to the server. Can anyone help?? Please see code below:
Code: [Select] $filename = $_FILES['activity_doc']['name']; // Name of the file (including file extension). $upload_path = https://upload_url //Curl session initialized $session = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)"); curl_setopt($session, CURLOPT_URL, $upload_path); curl_setopt($session, CURLOPT_USERPWD, 'username:password'); curl_setopt($session, CURLOPT_POST, 1); $post = array( "file_box"=>"@" . $filename, ); curl_setopt($session, CURLOPT_POSTFIELDS, $post); $response = curl_exec($session); if (is_uploaded_file($_FILES['activity_doc']['tmp_name'])) { echo "File ". $_FILES['activity_doc']['name'] ." uploaded successfully.\n"; } else { echo "Error occurred, file uploaded unsuccessful"; } $req = new SimpleXMLElement($response); print_r($req); curl_close($session); Similar TutorialsHi.
I'm working on some program. It adds new posts to facebook profiles, fanpages and groups. Everything works well, but when I want to create image uploading it just doesn't work (whitepage as result + file probably isn't even send, because of very short sending time).
Multipart form sniffed with Firefox looks like this.
Spoiler
Content-Type: multipart/form-data; boundary=---------------------------13742240526862 Content-Length: 788662 -----------------------------13742240526862 Content-Disposition: form-data; name="fb_dtsg" AQGlrKAR9le4 -----------------------------13742240526862 Content-Disposition: form-data; name="charset_test" â¬,´,â¬,´,æ°´,Ð,Ð -----------------------------13742240526862 Content-Disposition: form-data; name="file1"; filename="h.jpg" Content-Type: image/jpeg FILE_CONTENTS_HERE -----------------------------13742240526862 Content-Disposition: form-data; name="file2"; filename="" Content-Type: application/octet-stream -----------------------------13742240526862 Content-Disposition: form-data; name="file3"; filename="" Content-Type: application/octet-stream -----------------------------13742240526862 Content-Disposition: form-data; name="caption" -----------------------------13742240526862 Content-Disposition: form-data; name="return_uri" /groups/880573151971764?view=group&fc=photo_upload_success -----------------------------13742240526862 Content-Disposition: form-data; name="return_uri_error" https://m.facebook.com/photos/upload/?target_id=880573151971764&upload_source=composer&cwevent=intent_media&ctype=inline&referrer=group&session_id=5f737e58-0e23-4270-a8af-8bfa1100f3c5&refid=18 -----------------------------13742240526862 Content-Disposition: form-data; name="target" 880573151971764 -----------------------------13742240526862 Content-Disposition: form-data; name="ref" m_upload_pic -----------------------------13742240526862 Content-Disposition: form-data; name="album_fbid" -----------------------------13742240526862 Content-Disposition: form-data; name="csid" 5f737e58-0e23-4270-a8af-8bfa1100f3c5 -----------------------------13742240526862 Content-Disposition: form-data; name="ctype" advanced -----------------------------13742240526862 Content-Disposition: form-data; name="referrer" group -----------------------------13742240526862 Content-Disposition: form-data; name="is_old_composer" 1 -----------------------------13742240526862-- I am having trouble getting my upload file to work... Form HTML: Code: [Select] <form action="" method="POST"> <input type="file" name="file" /> <input type='"submit" name="upload" value="Upload" /> </form> PHP: Code: [Select] if($_POST["upload_avatar"]){ $upload_path = "images/users/"; $file = $_FILES["file"]["name"]; $extension_types = array("gif","jpg","jpeg","png"); if($file){ $filename = stripslashes($_FILES["file"]["name"]); $extension = getExtension($filename); $extension = strtolower($extension); $size = filesize($_FILES["file"]["tmp_name"]); if(in_array($extension, $extension_types)){ if($size <= $max_file_size){ $file_search = glob($upload_path . strtolower($username) . '*'); array_map("unlink", $file_search); $file_name = $upload_path . strtolower($username) . "." . $extension; $copied = copy($_FILES["file"]["tmp_name"], $file_name); if (!$copied){ $r_error = "Upload has failed"; } } else{$r_error = "File too big";} } else{$r_error = "Unknown file extension";} } else{$r_error = "No file chosen";} } Every time, it gives me the "No File Chosen" error. It doesn't seem to be actually uploading the file... I hope this isn't just some stupid thing I am looking over, can someone help me? Hi.. I have code for importing .xml file to database. the problem is I cannot upload my file but no error display. And also I got a problem in importing data from .xml file to database but not all row will be save. here is my code: Code: [Select] <?php $data = array(); $con = mysql_connect("localhost", "root",""); if (!$con) { die(mysql_error()); } $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $sql = "select * from sales_order"; $result = mysql_query($sql); if (!$result) { die(mysql_error()); } function add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth) { global $data; $con = mysql_connect("localhost", "root",""); if (!$con){ die(mysql_error());} $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $ProductType= $ProductType; $WorkOrder = $WorkOrder; $POIssueDate = $POIssueDate; $SalesMonth = $SalesMonth; $sql = "INSERT INTO sales_order (ProductType,WorkOrder,POIssueDate,SalesMonth) VALUES ('$ProductType','$WorkOrder','$POIssueDate','$SalesMonth')" or die(mysql_error()); mysql_query($sql, $con); $data []= array('ProductType'=>$ProductType,'WorkOrder'=>$WorkOrder,'POIssueDate'=>$POIssueDate,'SalesMOnth'=>$SalesMonth); } if ( $_FILES['file']['tmp_name'] ['error']) //f (empty($_FILES['file']['tmp_name']['error'])) { //$dom = DOMDocument::load('SalesOrder.xml'); $dom = DOMDocument::load($_FILES['file']['tmp_name']); $dom = DOMDocument::__construct(); $rows = $dom->getElementsByTagName('Row'); global $last_row; $last_row = false; $first_row = true; foreach ($rows as $row) { if ( !$first_row ) { $ProductType = ""; $WorkOrder = ""; $POIssueDate = ""; $SalesMonth = ""; $index = 1; $cells = $row->getElementsByTagName( 'Cell' ); foreach( $cells as $cell ) { $ind = $cell->getAttribute( 'Index' ); if ( $ind != null ) $index = $ind; if ( $index == 1 ) $ProductType = $cell->nodeValue; if ( $index == 2 ) $WorkOrder = $cell->nodeValue; if ( $index == 3 ) $POIssueDate = $cell->nodeValue; if ( $index == 4 ) $SalesMonth = $cell->nodeValue; $index += 1; } if ($ProductType=='' AND $WorkOrder=='' AND $POIssueDate=='' AND $SalesMonth=='') { $last_row = true; } else { add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth); } } if ($last_row==true) { $first_row = true; } else { $first_row = false; } } } ?> <html> <body> <table> <tr> <th>Sales Order</th> </tr> <?php foreach( $data as $row ) { ?> <tr> <td><?php echo( $row['ProductType'] ); ?></td> <td><?php echo( $row['WorkOrder'] ); ?></td> <td><?php echo( $row['POIssueDate']) ;?> </td> <td><?php echo( $row['SalesMonth'] ); ?></td> </tr> <?php } ?> </table> </body> </html> and I will attach my sample data and the data with color yellow background is only row I want to save to my database. Thank you so much.. Hi, I am trying upload files to a remote server using CURL however It is not sending all the values in the array. $auth_local='testing123'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $auth_remote_url[$auth_no] ); curl_setopt($ch, CURLOPT_POST, TRUE); $post_array = array( "auth"=>$auth_local, "auth_e"=>$auth_e, "my_file"=>"@".$myfile, "md5"=>$md5, "check"=>"0", "upload"=>"Upload"); curl_setopt($ch, CURLOPT_USERAGENT, "Test Upload"); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch ); curl_close($ch ); When I check the value of $_POST['auth'] it is blank. When I remove "my_file"=>"@".$myfile, It does read the correct value Why is this not returning a value? Thanks, mme I have a PHP web system that store in a windows server. In the system, there is a function for user to upload files to another server (Shared server in Unix). When i try to upload a file, it gives warning: Warning: move_uploaded_file(\\unixserver/sharedfolder/upload/test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in C:\wamp\www\upload\index.php on line 40 For your information, my username has been assigned in xxx's group that has access to read and write on that folder. Besides, i'm able to open,create and delete files on that folder's server manually (samba). The safe mode setting is off. Does anybody has any idea why this thing happen? Hey all So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory. I tried undoing the mysql changes but it still won't upload the image to the directory. Am testing on my own computer using xampp so no file permission issues, plus it was working before. Any help much appreciated. Thanks <?php $product_code = mysqli_real_escape_string($conn, $_POST['product_code']); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $category = mysqli_real_escape_string($conn, $_POST['category']); $filter = mysqli_real_escape_string($conn, $_POST['filter']); $description = mysqli_real_escape_string($conn, $_POST['description']); $specification = mysqli_real_escape_string($conn, $_POST['specification']); $price = mysqli_real_escape_string($conn, $_POST['price']); $target_dir = "../images/products/"; if (!isset ($_FILES["img1"]["name"])) { $target_file1 = NULL; } else { if (!empty($_FILES["img1"]["name"])) { $target_file1 = $target_dir . basename($_FILES["img1"]["name"]); } else { $target_file1 = NULL; } } if (!isset ($_FILES["img2"]["name"])) { $target_file2 = NULL; } else { if (!empty($_FILES["img2"]["name"])) { $target_file2 = $target_dir . basename($_FILES["img2"]["name"]); } else { $target_file2 = NULL; } } if (!isset ($_FILES["img3"]["name"])) { $target_file3 = NULL; } else { if (!empty($_FILES["img3"]["name"])) { $target_file3 = $target_dir . basename($_FILES["img3"]["name"]); } else { $target_file3 = NULL; } } if (!isset ($_FILES["img4"]["name"])) { $target_file4 = NULL; } else { if (!empty($_FILES["img4"]["name"])) { $target_file4 = $target_dir . basename($_FILES["img4"]["name"]); } else { $target_file4 = NULL; } } $uploadOk = 1; $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION)); $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION)); $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION)); $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check1 = getimagesize($_FILES["img1"]["tmp_name"]); $check2 = getimagesize($_FILES["img2"]["tmp_name"]); $check3 = getimagesize($_FILES["img3"]["tmp_name"]); $check4 = getimagesize($_FILES["img4"]["tmp_name"]); if($check1 !== false) { echo "File is an image - " . $check1["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file1)) { echo "Sorry, image one already exists."; $uploadOk = 0; } if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg" && $imageFileType1 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1."; $uploadOk = 0; } if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image one."; } } echo '<br />'; if($check2 !== false) { echo "File is an image - " . $check2["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file2)) { echo "Sorry, image two already exists."; $uploadOk = 0; } if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg" && $imageFileType2 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2."; $uploadOk = 0; } if (isset ($target_file2)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image two."; } } } echo '<br />'; if($check3 !== false) { echo "File is an image - " . $check3["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file3)) { echo "Sorry, image three already exists."; $uploadOk = 0; } if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg" && $imageFileType3 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3."; $uploadOk = 0; } if (isset ($target_file3)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) { echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image three."; } } } echo '<br />'; if($check4 !== false) { echo "File is an image - " . $check4["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file4)) { echo "Sorry, image four already exists."; $uploadOk = 0; } if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg" && $imageFileType4 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4."; $uploadOk = 0; } if (isset ($target_file4)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) { echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image four."; } } } } echo '<br />'; $image1 = basename($target_file1); $image2 = basename($target_file2); $image3 = basename($target_file3); $image4 = basename($target_file4); // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')"; if (mysqli_query($conn, $sql)) { echo "Product Added successfully, Now on to the Sizes"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } ?>
I am working on making an album however I am not sure where I am going wrong with my codes. I have an upload and thumbs folder in the albums folder but I keep getting this message.... Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 44 Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 45 Warning: Cannot modify header information - headers already sent by (output started at /home/ebermy5/public_html/albums/create_album.php:9) in /home/ebermy5/public_html/albums/create_album.php on line 29 Codes: for line 44 and 45 function create_album($album_name, $album_description){ $album_name = mysql_real_escape_string(htmlentities($album_name)); $album_description = mysql_real_escape_string(htmlentities($album_description)); mysql_query("INSERT INTO `albums` VALUES ('', '".$_SESSION['SESS_ID']."', UNIX_TIMESTAMP(), `$album_name`,`$album_description`)"); mkdir('uploads/'.mysql_insert_id(), 0744); mkdir('uploads/thumbs/'.mysql_insert_id(), 0744); } Code: for line 29 if(isset($_POST['album_name'], $_POST['album_description'])){ $album_name = $_POST['album_name']; $album_description = $_POST['album_description']; $errors = ""; if(empty($album_name) || empty($album_description)){ $errors = 'Album name and description required'; }else{ if(strlen($album_name) > 55 || strlen($album_description) > 255){ $errors = 'One or more fields contains too many characters'; } } if(!empty($errors)){ foreach($errors as $error){ echo $errors, '<br />'; } } else { create_album ($album_name, $album_description); header('Location: albums.php'); exit(); } } ok i added this script in the bottom of my other uploader script.
what i wanted to do was, to upload an imagefile to an folder called uploads
and in the same time add the name of the file to an database called uploads,
together with the next id of another database
i dont get any error msg, the page is just blank.
<?php include 'sqlconnect.php'; $result = mysql_query(" SHOW TABLE STATUS LIKE 'aktiviteter' "); $data = mysql_fetch_assoc($result); $next_increment = $data['Auto_increment']; $sql = sprintf( "INSERT INTO aktiviteter (`title`, `firma`, `beskrivelse`, `information`, `pris`, `varighed`, `antal`, `adresse`, `by`, `postnummer`, `telefon`, `email`, `hjemmeside`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", mysqli_real_escape_string($con, $_POST['title']), mysqli_real_escape_string($con, $_POST['firma']), mysqli_real_escape_string($con, $_POST['beskrivelse']), mysqli_real_escape_string($con, $_POST['information']), mysqli_real_escape_string($con, $_POST['pris']), mysqli_real_escape_string($con, $_POST['varighed']), mysqli_real_escape_string($con, $_POST['antal']), mysqli_real_escape_string($con, $_POST['adresse']), mysqli_real_escape_string($con, $_POST['by']), mysqli_real_escape_string($con, $_POST['postnummer']), mysqli_real_escape_string($con, $_POST['telefon']), mysqli_real_escape_string($con, $_POST['email']), mysqli_real_escape_string($con, $_POST['hjemmeside']) ); if (!mysqli_query($con, $sql)) { die('Error: ' . mysqli_error($con)); } echo "Aktiviteten er uploaded"; if(isset($_POST['upload'])) { $allowed_filetypes = array('.jpg','.jpeg','.png','.gif'); $max_filesize = 10485760; $upload_path = 'uploads/'; $targetId = $next_increment $filename = $_FILES['billede']['name']; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!in_array($ext,$allowed_filetypes)) die('The file you attempted to upload is not allowed.'); if(filesize($_FILES['billede']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); if(move_uploaded_file($_FILES['billede']['tmp_name'],$upload_path . $filename)) { $query = "INSERT INTO uploads (name, target) VALUES ($filename, $targetId)"; mysql_query($query); echo 'Your file upload was successful!'; } else { echo 'There was an error during the file upload. Please try again.'; } } mysqli_close($con); ok im stuck again and need help. I have gotten rid of the attachment system(too many issues) on ASF and decided to replace it with my own. The problem is that the original new post form is sent to php via jQuery. Obv i cannot do this with files so the attachment section needs to be a seperate form. Now i have no issues with sending files to the folder and sending their name to the database but i need to send multiple. so far when the user selects a file it will add the name of it to a hidden input element and each one that is added to that element is seperated with | . then in the php i would use explode on this element to get an array of the file names. but this only helps when sending to the database and not when moving files. I also dont want a page refresh when uploading files. No other file upload systems out there will work because they upload the file as soon as you press submit, but then how do i add the post id to the attachments row in the database? Hi, I have a system that uses PHP to create a Word Doc as information is extracted from a table using this code: Code: [Select] header("Content-type: applicaton/save"); header("Content-Disposition: attachment; filename="FILE NAME".doc"); header("Pragma: no-cache"); header("Expires: 0"); This part of the system I'm trying to implement is working fine. However, what I would ideally like for it to do (and at this point I understand that it sounds a bit pointless) is to save that downloaded file onto a specified folder location on the server directory i.e. to the uploads folder. This will enable all users of the system to then download / view these files as required. I'm not sure whether this is possible or not but and help would be greatly appreciated. Thanks in advance, Ben Hi, really need some extra brains to help me with this one! I have a form with only 1 text box (input type=text) in this textbox I enter a local path on my computer to a specific folder. in this folder I have few files, each has a set name that I know in advance. what I want to do is to be able to upload all those files in my local folder to the server, without making the user click browes and pick them 1 by 1. I searched and searched but I see it's not as simple as I thought cuz I can't just set the value of the input file.. since my page has a form eitherway I thought of maybe doing something sneaky and hiding the input files and some how passing them the path of each file (the folder path will be taken from the not hidden textbox) and the file name is known to me so I can add those 2 somehow.. I can't find a way to do that, so I wonder if any of you have an idea? maybe it's possible to set the file path after the form is submited? basicly I think it's possible to give the name of the file, but I also need the temp name of the file ($_FILES['docfile1']['tmp_name']), and this I don't know how to set.. this is my code for uploading a file with <input type=file> Code: [Select] if ($_FILES['docfile1']['name']!='') { $target = 'import/'; $target = $target . basename($_FILES['docfile1']['name']); if ($target =="import/myfile.xlsx"){ if (file_exists($target)) unlink($target); if (move_uploaded_file($_FILES['docfile1']['tmp_name'], $target)) { echo 'success'; }else{ echo 'fail'; } }else{ echo 'fail'; } }desperately need help! i am using the fancy upload script for post attachments on my forum. the problem is that when a user starts a new post and adds an attachment the attachment is uploaded before the post is complete. so how would i associate the attachment with the post that they are going to post when i have no post id to go off? i had tried not uploading the files straight away and instead populate an input box with the filenames but i cant figure it out with this script. Anyone got any other options or ideas? Sorry for posting this here, but for some reason the "create new topic" in linux subforum doesnt exist. anyways i made a small php script that enables me to retrieve data between two dates. now am stuck on how i should copy it or u0pload it into linux. system tells me i need to upload to /usr/bin/libexec , i am there now but i dont have the slightest idea on how to do that. help is much appreciated. Thanks Hi All Please can someone help me. I have a CSV file with over 3000 lines. Each one contains the following information Country Insurance Name Mandatory or Optional Description and Coverage Group SIPP Cost Per Day Cost Per Week Cost Per Month Deductable I have written the following script to read line by line, compare the country and insurance with the previous and if it is the same, tag certain parts of each line onto the end of the previous. However, I am getting no output from this, and I keep getting an error saying I am using too much memory or my computer hangs. I am fairly new to php so any pointers would be good. Firstly, does my script look like it should do what I want it to do? If so, any clues how to get around the momory issue. If not, what have I done wrong? Cheers guys <?php //open file paths $handle=fopen("insurances.csv","r"); $handle_out=fopen("insuranceoutput.csv","a"); //writes the first line of the csv file into an array to act as a comparrison if($handle){ $line=fgets($handle); $line_array=explode(",",$line); $full_array=$line_array; fclose($handle); } } if($handle) { while (!feof($handle)) { // read one line into array $line=fgets($handle); $line_array=explode(",",$line); fclose($handle); //test to see if country matches previous while ($line_array[0] == $full_array[0]) { //test to see if insurance matches previous while ($line_array[1] == $full_array[1]) { //write array values 4 - 9 to main array $full_array[]=array("$line_array[4]","$line_array[5]","$line_array[6]","$line_array[7]","$line_array[8]","$line_array[9]"); } } //write to new file when new insurance is found foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } // write to new file if new country is found. foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } } ?> I don't know why this image upload code isn't uploading the image file to the uploads/ folder.
Any help will be appreciated.
$allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = strtolower( end($temp) ); if ( $_FILES["file"]["size"] < 2000000 && in_array($extension, $allowedExts) ) { if ($_FILES["file"]["error"]!= 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { $length = 20; $randomString = substr(str_shuffle(md5(time())),0,$length); $newfilename = $randomString . "." . $extension; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename ); $file_location = '<a href="http://www.--.com/upload/' . $newfilename . '">http://www.--.com/upload/' . $newfilename . '</a>'; } } else { echo "Invalid upload file"; } <form enctype="multipart/form-data" action="uploader.php"> <input type="file" name="file" id="file"> <input type="submit" name="submitted" value="Submit"> </form> Hello I am new to programming, coding, php... and need some help. I have some code that uploads a file and does some basic checks but I also want it to rename the file possibly adding the time stamp. Heres what I have so far. cheers. $tbl_name="guestbook"; // Table name $email = $_REQUEST["email"]; $name = $_REQUEST["name"]; $comment = $_REQUEST["comment"]; $_FILES["file"]["name"]; $_FILES["file"]["type"]; $_FILES["file"]["size"]; $_FILES["file"]["tmp_name"]; $_FILES["file"]["error"]; $datetime = date("dmy"); $uploaddir = "upload/"; $filename = $_FILES["file"]["name"]; $pathinfo = pathinfo($_FILES['userfile1']['name']); mysql_connect("$host", "$username", "$password")or die("cannot connect server "); mysql_select_db("$db_name")or die("cannot select DB"); $sql="INSERT INTO $tbl_name(name, email, comment, datetime)VALUES('$name', '$email', '$comment', '$datetime')"; $result=mysql_query($sql); if($result){ echo "Successful added update to the Melody Bear Bulletin Board"; echo "<BR>"; echo "<a href='ViewBulletinBoard.php'>View Bulletin Board</a>"; } else { echo "ERROR"; } if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]. "<br>"; } } } else { echo "Invalid file"; } mysql_close(); ?> please just deleting this post I think i figured it out I'm trying to use the ZipArchive class and it works on my localhost but when I upload the script and try to use it on my website it can't find the ZipArchive class. How do I install this on my remote host? Also on my localhost it seems like I can only directories of a certain size. When the directory is to big nothing happens. I'm having a problem with using cURL or php ftp to write or create files remotely. Is there a way I can use cURL or php ftp and set the file permissions while it's being uploaded? I'm on a windows server so I can't change the file permissions through ftp_chmod. How else can I get around this so I can write/create files remotely. Thanks! Hello all, I'm designing an upload file section for a home medical company. So far it has been going great, I am uploading files and they're being successfully inserted into my MYSQL Table. However, my issue is when I download the files they claim to be corrupted and unusable. If I save the PDF files to my desktop they won't open at all, they claim to be corrupted. If I download a JPG and then open it in photshop it warns me the file may be corrupted, knowing it is not I clicked "yes". The jpg actually opens and looks like the image, however about 50 pixels on the bottom get cut off and look like a messy TV screen, if that makes sense. Wondering if anyone has had this similar issue, the uploading part is not the issue - just downloading the files. My Upload Form Code: Code: [Select] <p><a href="upload.php">Upload a File</a> <a href="../admin/admin.php">Back to Control Panel</a></p> <form action="add_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> My Add File Code (This is working fine but may cause issues with downloading?) Code: [Select] <?php // Check if a file has been uploaded if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors if($_FILES['uploaded_file']['error'] == 0) { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Gather all required data $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']); $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); $size = intval($_FILES['uploaded_file']['size']); // Create the SQL query $query = " INSERT INTO `file` ( `name`, `mime`, `size`, `data`, `created` ) VALUES ( '{$name}', '{$mime}', {$size}, '{$data}', NOW() )"; // Execute the query $result = $dbLink->query($query); // Check if it was successfull if($result) { echo 'Success! Your file was successfully added!'; } else { echo 'Error! Failed to insert the file' . "<pre>{$dbLink->error}</pre>"; } } else { echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); } // Close the mysql connection $dbLink->close(); } else { echo 'Error! A file was not sent!'; } // Echo a link back to the main page echo '<p>Click <a href="upload.php">here</a> to go back</p>'; ?> My List File Code (This is working fine also, but does contain the link that I click when I want to download a file) Code: [Select] <?php $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Query for a list of all existing files $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`'; $result = $dbLink->query($sql); // Check if it was successfull if($result) { // Make sure there are some files in there if($result->num_rows == 0) { echo '<p>There are no files in the database</p>'; } else { // Print the top of a table echo '<table width="100%"> <tr> <td><b>Name</b></td> <td><b>Mime</b></td> <td><b>Size (bytes)</b></td> <td><b>Created</b></td> <td><b> </b></td> </tr>'; // Print each file while($row = $result->fetch_assoc()) { echo " <tr> <td>{$row['name']}</td> <td>{$row['mime']}</td> <td>{$row['size']}</td> <td>{$row['created']}</td> [u][b]<td><a href='get_file.php?id={$row['id']}'>Download</a></td>[/b][/u] </tr>"; } // Close table echo '</table>'; } // Free the result $result->free(); } else { echo 'Error! SQL query failed:'; echo "<pre>{$dbLink->error}</pre>"; } // Close the mysql connection $dbLink->close(); ?> And here is my Get File page. This is where my problem lies. (I think) Code: [Select] <?php // Make sure an ID was passed if(isset($_GET['id'])) { // Get the ID $id = intval($_GET['id']); // Make sure the ID is in fact a valid ID if($id <= 0) { die('The ID is invalid!'); } else { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` WHERE `id` = {$id}"; $result = $dbLink->query($query); if($result) { // Make sure the result is valid if($result->num_rows == 1) { // Get the row $row = mysqli_fetch_assoc($result); // Print headers header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']); // Print data echo $row['data']; } else { echo 'Error! No image exists with that ID.'; } // Free the mysqli resources @mysqli_free_result($result); } else { echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; } @mysqli_close($dbLink); } } else { echo 'Error! No ID was passed.'; } ?> Thanks for any help that anyone can provide, this issue is really causing some stress and hurting my sleep at night! Can't figure out why this won't work, it's literally the last step in completing this website. Please let me know if you need any other information regarding this issue. Thanks, - Mike |