PHP - Fopen() Help
I'm having trouble connecting through fopen using variables as the login details, but with file_get_content it works fine?!
These are my variables:- $ftpaddy="ftp.mydomain.com"; $username="me"; $password="password"; $editingdir="/public_html/edit/"; $editfile="editme.txt"; $myftppath = "ftp://" . $username . ":" . $password . "@" . $ftpaddy . $editingdir . $editfile; //puts all variables into string When I try to connect and read the file using the following method it works fine:- $file = file_get_contents("$myftppath", "r"); but when i try and use the same string with fopen as below it doesn't work?! the line i have commented out however works and when i echo the $myftppath variable below it looks the same.. i don't really get it! //$myftppath = "ftp://me:password@ftp.mydomain.com/public_html/edit/editme.txt"; $myftppath = "ftp://" . $username . ":" . $password . "@" . $ftpaddy . $editingdir . $editfile; //puts all variables into string $stream_options = array('ftp' => array('overwrite' => true)); $stream_context = stream_context_create($stream_options); if ($fh = fopen($myftppath, 'w', 0, $stream_context)){//fopen only likes the commented out $myftppath not the one using the variables?! fputs($fh, $newcontents); fclose($fh); } else { die('Could not open file.'); } does anyone know if I am doing the syntax wrong and how to correct it? I read I may need to put another slash after domain.com but this didn't help either. any help would be much appreciated! thanks in advance Kev. Similar Tutorialshi, I want to write pdf file but it is getting garbage value i check following url http://bugs.php.net/bug.php?id=21904&edit=1 Code: [Select] $fp = fopen($fdirandname,'wb'); fwrite($fp,$pdfcode); fclose($fp); So I am tryting to create a script to upload a CSV file into a MySql DB. It has like 10K records into SQL
My Code is copy below ...
I get the following errors.
Line 16 is the $handle
line 18 is the While Statement
Error:
Warning: fopen(): Filename cannot be empty in C:\local\htdocs\ADPStorage\DemandCSV.php on line 16 Warning: fopen()expects parameter 1 to be resource, boolean given in C:\local\htdocs\ADPStorage\DemandCSV.php on line 18 I use my script for another table and it worked like a charm. Less data and less colums do. Bad Code: (good Code sample below. this one) <?php $today = date("m.d.y.h.m.s"); echo $today; $BPTD_fy = '2014'; $BPTD_updatedate = $today; $conn = mysql_connect("Localhost","root","password") or die (mysql_error()); mysql_select_db("ds_storage",$conn); if(isset($_POST['submit'])) { $file = $_FILES['file']['tmp_name']; $handle = fopen($file, "r"); while(($fileop = fgetcsv($handle, 100000, ",")) !==FALSE) { $BPTD_fy = $fileop[0]; $BPTD_Status = $fileop[1]; $BPTD_Classification = $fileop[2]; $BPTD_ProcureCat = $fileop[3]; $BPTD_Product = $fileop[4]; $BPTD_Project = $fileop[5]; $BPTD_DSCategory = $fileop[6]; $BPTD_Calculated = $fileop[7]; $BPTD_CapacityType = $fileop[8]; $BPTD_Amount = $fileop[9]; $BPTD_Jul = $fileop[10]; $BPTD_Aug = $fileop[11]; $BPTD_Sep = $fileop[12]; $BPTD_Oct = $fileop[13]; $BPTD_Nov = $fileop[14]; $BPTD_Dec = $fileop[15]; $BPTD_Jan = $fileop[16]; $BPTD_Feb = $fileop[17]; $BPTD_Mar = $fileop[18]; $BPTD_Apr = $fileop[19]; $BPTD_May = $fileop[20]; $BPTD_Jun = $fileop[21]; $BPTD_Location = $fileop[22]; $BPTD_Env = $fileop[23]; $BPTD_Requester = $fileop[24]; $BPTD_ServiceArea = $fileop[25]; $BPTD_ServiceGroup = $fileop[26]; $BPTD_DepHead = $fileop[27]; $BPTD_Recgroup = $fileop[28]; $BPTD_RecOwner = $fileop[29]; $BPTD_Entrydate = $fileop[30]; $BPTD_updatedate = $fileop[31]; $sql = mysql_query("INSERT INTO inv_bpt_demand (Status, Classification, ProcureCat, Product, Project, DSCategory, Calculated, CapacityType, Amount, Jul, Aug, Sep, Oct, Nov, Dec, Jan, Feb, Mar, Apr, May, Jun, Location, Env, Requester, ServiceArea, ServiceGroup, DepHead, Recgroup, RecOwner, Entrydate, updatedate) VALUES ('$BPTD_Status', '$BPTD_Classification', '$BPTD_ProcureCat', '$BPTD_Product', '$BPTD_Project', '$BPTD_DSCategory', '$BPTD_Calculated', '$BPTD_CapacityType', '$BPTD_Amount', '$BPTD_Jul', '$BPTD_Aug', '$BPTD_Sep', '$BPTD_Oct', '$BPTD_Nov', '$BPTD_Dec', '$BPTD_Jan', '$BPTD_Feb', '$BPTD_Mar', '$BPTD_Apr','$BPTD_May', '$BPTD_Jun','$BPTD_Location', '$BPTD_Env','$BPTD_Requester', '$BPTD_ServiceArea', '$BPTD_ServiceGroup','$BPTD_DepHead', '$BPTD_Recgroup','$BPTD_RecOwner','$BPTD_Entrydate','$BPTD_updatedate')"); if($sql) { echo 'Data Uploaded Successfully'; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>BPT Demand CSV</title> <link rel="stylesheet" type="text/css" href="file:///C|/local/htdocs/style/style.css" /> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> </head> <body> <div id="mainWrapper"> <form method="post" action="https://localhost/Storage/DemandCSV.php" enctype="multipart/form-data"> <input type="file" name="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </div><!--end mainWrapper--> </body> </html>Similar Working code (good) <?php $conn = mysql_connect("Localhost","root","password") or die (mysql_error()); mysql_select_db("ds_storage",$conn); if(isset($_POST['submit'])) { $file = $_FILES['file']['tmp_name']; $handle = fopen($file, "r"); while(($fileop = fgetcsv($handle,1000,",")) !==FALSE) { $PC_Num = $fileop[0]; $PC_Name = $fileop[1]; $PC_BPTNUM = $fileop[2]; $PC_busclass = $fileop[3]; $PC_Note = $fileop[4]; $PC_Acro = $fileop[5]; $PC_type = $fileop[6]; ///echo $fileop[1]; $sql = mysql_query("INSERT INTO inv_names (PC_Num, PC_Name, PC_BPTNUM, PC_busclass, PC_Note, PC_Acro, PC_type) VALUES ('$PC_Num', '$PC_Name', '$PC_BPTNUM', '$PC_busclass', '$PC_Note', '$PC_Acro', '$PC_type')"); if($sql) { echo 'Data Uploaded Successfully'; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Upload CSV</title> <link rel="stylesheet" type="text/css" href="file:///C|/local/htdocs/style/style.css" /> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> </head> <body> <div id="mainWrapper"> <form method="post" action="https://localhost/Storage/Storage_CSV.php" enctype="multipart/form-data"> <input type="file" name="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </div><!--end mainWrapper--> </body> </html>Please help and thx in advance ~J Hey all i am attempting to connect to a ftp address and display the contents of a file into a textarea and i keep getting errors is there something wrong with the code or the ftp server? <?php $log_file= "ftp://username:password@68.232.164.100/czero/68.232.164.100:27015/czero/gsconsole.log"; $log_handle = fopen($log_file, "r"); $log_contents = fread($log_handle, filesize($log_file)); fclose($log_handle); ?> Console Log: <textarea name="log_view" cols="110" rows="20" readonly="readonly" wrap="virtual"><?php echo "$log_contents" ; ?></textarea> Hey all, my doubt is the following: Is there a way of opening files (images,pdf's,etc) in a popup window? What I intend to do, is have a button, that when pressed, would acess and open certain files in a popup window. I already know how to acess and download the files, but I would like to know how to open them inside the browser. sorry for the bad English. Hope you understood and can help. Thanks alot, Ruben Greetings all, I'm completely stumped...so I'd like to run this issue by you guys (and gals!). I have encountered an odd issue, and I have no idea why this is doing what it's doing. When I execute the following code, all by itself, in an "index.php" file (with no other files around...completely isolated!) I get a result of "testtest" $log_file = 'all.txt'; $handle = fopen($log_file, 'a'); fwrite($handle, 'test'); fclose($handle); Note: I delete the file each time I execute the script (in a browser). I am also the only one running this script. I've tried running on PHP 5.2.x and PHP 5.3.x I have also tried on my machine as well as a separate, remote machine. Is the script running twice? If so, what's causing it? Any help is appreciated as always! Ryan I have a script that uses fopen, except the site doesn't allow it. does any one know how i can rewrite this using curl? f(isset($_REQUEST['l']) && $_REQUEST['l'] <> ''){ $link = VAR.'/blah/blaf/blah/'.rawurlencode($_REQUEST['l']).'/blah/1'; $fp = fopen($link,'r'); foreach($http_response_header as $v){if(substr($v,0,7)=='Content'){header($v);}} fpassthru($fp); fclose($fp); }else{echo 'Parameters not set';} Im kindof a noob. Hey, I was just wondering if there's a way to speed up how quickly Linux opens files. I noticed that after having implemented File Caching, the data takes 1/3 times longer to retrieve after having refreshed the page(via fopen). Probably due to the file still being in memory. Are there any apache/linux settings which I can modify which will reduce this time even further. Maybe even keep the (temporary) cached files in memory? hdparm, etc. Hi, I am modding phpBB3 and I want to make the contents of a text documents appear in a border. This is what I have in my portal_style.html: Code: [Select] <!-- INCLUDE overall_header.html --> <?php $a1=fopen("/port/announce/announce1.txt", "r"); $a2=fopen("/port/announce/announce2.txt", "r"); $a3=fopen("/port/announce/announce3.txt", "r"); $a4=fopen("/port/announce/announce4.txt", "r"); $a5=fopen("/port/announce/announce5.txt", "r"); ?> <h2>Announcement!</h2> <div class="panel"> <div class="inner"><span class="corners-top"><span></span></span> <div class="content"> <?php echo $a1; ?> </div> <span class="corners-bottom"><span></span></span></div></div> <h2>Announcement!</h2> <div class="panel"> <div class="inner"><span class="corners-top"><span></span></span> <div class="content"> <?php echo $a2; ?> </div> <span class="corners-bottom"><span></span></span></div> </div> <!-- INCLUDE jumpbox.html --> <!-- INCLUDE overall_footer.html --> Anyone mind showing me how to make it work? Thanks. Ive just tried to use fopen for the first time, but ive been denied access. Im trying to create a new page. Code: [Select] $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value){ $i++; echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".html'>" . $nt[$i] . "</a>" . "<br/>";} $FileName = str_replace(' ','_',$nt[$i]) . ".html"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); fclose($FileHandle); Warning: fopen(Indian.html) [function.fopen]: failed to open stream: Permission denied in D:\Hosting\######\html\1pw\b.php on line 40 cant open file. The hosting company I use say in their help forum; "If a file is outside of the paths defined by open_basedir, PHP will refuse to open it" Is there a query I can run to find out which paths are defined by open_basedir and is it possible to edit open_basedir? I have this function to get other website title tag. But since the fopen is disabled in my shared server, this function cannot work. How can i still do it? thanks in adv function getTitle($Url){ $file=@fopen($Url,"r"); if($file) { fclose($file); $str=file_get_contents($Url); if($str) { if(strlen($str)>0){ preg_match("/\<title\>(.*)\<\/title\>/",$str,$title); return $title[1]; } }else{ return true; } }else{ return false; } } I have fopen() code that works fine.. Code: [Select] $filename = "trade.php"; $filehandle = fopen($filename, 'w') or die("can't open file"); fclose($filehandle); But I want it to create the file "trade.php" in a specific directory called "tradepages". I tried changing the one line to be... Code: [Select] $filename = ".../tradepages/trade.php"; But that just gives an error saying no such directory exists (even though it definitely does). There has to be a way to create files in whatever folder/directory you want, right? Anyone know how, or what I'm doing wrong? Hi, I was using latest php5 but as I couldn't find a ffmpeg-php extension for it, I actually swapped to latest php4, and now I'm having a problem when using fopen for urls, when it's used it just stops the script with no error / warning, i tried using the same php.ini used with my php5 too but it changes nothing. Btw allow_url_fopen is enabled. Thanks if someone can help. $DOCUMENT_ROOT=$_SERVER['DOCUMENT_ROOT']; $outputstring = $date."\t".$tireqty." tires \t".$oilqty."oil\t".$sparkqty." spark plugs\t\$".$totalamount."\t".$address."\n"; //open file for appending @$fp = fopen('$DOCUMENT_ROOT/../orders/orders.txt', 'ab'); if (!$fp) { echo '<p><strong>Your order can not be processed at this time. Please try again later</strong></p></body></html>'; exit; } //write to file fwrite($fp, $outputstring, strlen($outputstring)); flock($fp, LOCK_UN); fclose($fp); Can someone please explain to me why this Code is giving me the error? i've tried to take out $DOCUMENT_ROOT and specify where exactly i want the file to be /dir/dir/file.txt but it still gives me an error. Hi all I need to retrieve a remote file and store it on my server. There are several methods to do this, but all of them fail when the URL contains special characters such as spaces. Consider the following URL: 'http://www.somedomain.com/Images/Products/MyProduct (Large).jpg' Assuming the allow_url_fopen directive is set to "on" in the php.ini, one can normally call: $url = ... $handle = fopen($url); to access the file. However, the space in the filename causes a Bad HTTP Request (Response 400). Using urlencode to encode the url doesn't solve the problem either, as all forward slashes and the colon after the protocol get escaped, and fopen doesn't recognize it as a URL. Besides manually replacing all the characters in the URL that are not colons or forward slashes (and are considered 'special'), can anyone give me any other solutions to make this work? Thanks Hello all, I'm trying to open a file, take some text from it conditionally, and paste the newly edited text back into the same file. At first I used a seperate fopen($handle, 'r') handler to open the file to read it, get its contents CONDITIONALLY, close the read handler, and open a new write handler to overwrite the file. In short, I need to extract the text from the file after ignoring some amount of text , and then rewrite the file with the newly altered text. I was trying out r+ and w+ options when using fopen(), but w+ is working in a way thats leaving me confused. Here is my code. $file = 'test.txt'; $fileHandle = fopen($file,'w+'); fwrite($fileHandle, 'Newly inserted text'); $fileContents = fread($fileHandle, filesize($file)); echo $fileContents; fclose($fileHandle); The manual says that if the w+ option is specified then the file is opened for reading and writing. From what I understand this means that I should be able to read from the file after writing to it. But the code above displays nothing after writing to the file. The file is chmodded 777. Can someone please explain to me why this is so Thanks I am having an issue in which fopen randomly generates either timeout or "failed to open stream" errors when trying to get stock quotes from yahoo finance. Here's an example. <b>Warning</b>: fopen(http://finance.yahoo.com/d/quotes.csv?s=NFLX&f=sl1d1t1c1ohgv&e=.csv) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: HTTP request failed! This issue occurs sporadically; sometimes it's fine, other times it errors out causing the quote to fail. Any ideas on how I can resolve this? Thanks very much. Hi, I am calling the sms gateway to send sms, Quote $sms_msg = "hi this is mubarak"; $url = $urlAccount_home."?username=".$userAccount."&password=".$passAccount."&number=".$O_Mobile."&sender=".$userSenderSMS."&msg=".$sms_msg; if (!($fp =fopen($url,"r"))) echo "<br><center>خطا في الاتصال </center><br>"; $result =fread($fp,10); fclose($fp); when i am sending like this am sending only the message "Hi" I am not getting the whole message... What might be the problem in sending the sms gateway.. Please help me if you guys came to know, Thanks and Regards, Mubarak Hey guys, I'm opening a HTML file from my server, and i can successfully echo it both as code to show the page, and as code which the person can then edit in a <textarea>. However, there are certain sections of the code i do not what echo'd to the page. What is the best way to go about stipping them? For example i do not want the user to be able to edit the doctype, head element, <header> or <nav> sections of the code. Thanks in advance Danny. Until I switched to Plesk 9 I had no trouble writing a log file for an application that I wrote. It used PHP's FOPEN() command. It would write the file as the user. Now it does not write at all. If I run it manually it the file is owned by siteadmin but writes it as as root:root.. If I run it through a browser it is owned by apache:apache. What's changed? Code: [Select] <?php if (file_exists('test.txt')) { unlink('test.txt'); // if it already exists let's erase it as a workaround } $fp = fopen('test.txt', 'w') or die("Unable to open file."); fwrite($fp, strftime('%c')."\r\n"); fclose($fp); ?> A similar block of code would write a ticker file that later would display on our pages. It was written and saved as the main site user, such as "siteadmin" on Plesk. Now PHP reports that it is unable to open or save the file. Permissions. We've changed nothing. This script has run since 2002 using chmod 644. We worked around this by creating an external script and using a CRON to write the file and this works fine. This suggests that the user has permission to open and write the file! Imagine our confusion. Don't laugh, but this server still has PHP 4.3.9, which adds to the confusion. It's run this way for years. Quote PHP 4.3.9 (cgi) (built: Sep 27 2006 20:40:56) Copyright (c) 1997-2004 The PHP Group Zend Engine v1.3.0, Copyright (c) 1998-2004 Zend Technologies with the ionCube PHP Loader v3.1.16, Copyright (c) 2002-2006, by ionCube Ltd., and with Zend Extension Manager v1.0.10, Copyright (c) 2003-2006, by Zend Technologies with Zend Optimizer v3.0.1, Copyright (c) 1998-2006, by Zend Technologies Code: [Select] $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".html'>" . $nt[$i] . "</a>" . "<br/>"; $FileName = str_replace(' ','_',$nt[$i]) . ".html"; $FileHandle = fopen($FileName, 'w') or die("cant open file");} fclose($FileHandle); ?> When a page is opened using fopen i would like the file menu.php to be written to the file created. To do this would I need to do somthing like; Code: [Select] $FileHandle = fopen($FileName, 'w', include ("menu.php")) or die("cant open file");} Im not sure about the correct use of syntax here. Any ideas? |