PHP - Fopen And Fread Trouble
Hi
i am trying to read a page that i open but i keep getting errors and dont know why any ideas. The code im using is: foreach($url_extq_data as $a) { $var .=$a; } // now replace all the tags in the substring and out put the data $from = array("{our_track}", "{name}", "{surname}", "{email}", "{title}", "{gender}", "{dobday}", "{dobmonth}", "{dobyear}", "{address}", "{address2}", "{town}", "{county}", "{postcode}", "{tel}", "{mobile}", "{timestampu}", "{timestampr}", "{username}", "{password}", "{company}", "{siteurl}", "{fax}", "{tracking}"); $to = array("$our_id", "$name", "$surname", "$email", "$title", "$gender", "$dobday", "$dobmonth", "$dobyear", "$address", "$address2", "$town", "$county", "$postcode", "$tel", "$mobile", "$timestampu", "$timestampr", "$username", "$password", "$company", "$siteurl", "$fax", "$trackit"); $final_url = str_replace($from, $to, $var); // open url and wait for response $handle = fopen('$final_url', "r"); echo $final_url; ##$contents2 = stream_get_contents($handle); $contents2 = ''; $contents2 .= fread($handle, 100); $contents2 = trim($contents2); This is what i get back: <br /> <b>Warning</b>: fopen($final_url) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: No such file or directory in <b>/home/s/e/searlco/web/public_html/ms_creg.php</b> on line <b>232</b><br /> http://www.cleanleads.co.uk/lead.aspx?campid=30&suppid=284&HSID=1121&HOID=52&FirstName=Dafydd&LastName=Thomas&AddressLine1=31 Cottage Street&Postcode=SS131HR&Gender=M&DateOfBirth=13/10/1980&emailaddress=dait@tedfsdfsdit.com&title=Mr&SupplierSourceCode=11866<br /> <b>Warning</b>: fread(): supplied argument is not a valid stream resource in <b>/home/s/e/searlco/web/public_html/ms_creg.php</b> on line <b>236</b><br /> ER Any help anyone???? im lost 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); Hi! I run a site the requires users to access largeish files, for download as well for streaming to the browser. It's fairly active, so assuming the worst, how bad is getting php to read the files that would be stored outside of the webroot and then getting it to echo it to a page dynamically for the browser to then read? Currently, I just have the files stored accessible to the web, but a htaccess protects them via requiring a cookie but also requires the referrer to be my site. Now I'm not totally stupid and realise those are both easily spoofed, so I'm looking for a better solution. How do the file hosting sites do it? Using a token system has to involve PHP or some other server side scripting, but then getting the server to read the file with fread() or some similar equivalent would be resource heavy, no? Is that the best way to do it? 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 I want to load and display the content of a text file (actually it is a cache file). I tested both method using a long for loop as Code: [Select] for ($i=0; $i < 10000; $i++) { $handle = fopen("test.txt", "r"); $text = fread($handle, filesize("test.txt")); fclose($handle); echo $text; }and Code: [Select] for ($i=0; $i < 10000; $i++) { $text = file_get_contents("test.txt"); echo $text; } but the results were similar, though with a large distribution of the comparative data. The speed of a method was 0.5 to 2.0 faster than the other one (in various runs). Which method do you recommend? Could you please quote the pros and cons of each method? Hello. I need help adding a text file content by one and then saving. My current code is $myFile = "serving"; $fh = fopen($myFile, 'w+') or die("can't open file"); $conv = fread($fh, 4); $stringData = $conv++; fwrite($fh, $stringData); fclose($fh); I was told this would work, but of course, it doesn't. It always returns 1. I also tried casting it as an int by using $stringData = (int) $conv++; Hi all I am pulling my hair out trying to get the following script to work Code: [Select] <?php error_reporting(E_ALL); ini_set('display_errors', '1'); if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist"); // log in at server1.example.com on port 22 if(!($con = ssh2_connect("*.*.*.*", 22))){ echo "fail: unable to establish connection\n"; } else { // try to authenticate with username root, password secretpassword if(!ssh2_auth_password($con, "root", "********")) { echo "fail: unable to authenticate\n"; } else { // allright, we're in! echo "okay: logged in...\n"; // execute a command if (!($stream = ssh2_exec($con, "ls -al" ))) { echo "fail: unable to execute command\n"; } else { echo "should be ok"; // collect returning data from command stream_set_blocking($stream, true); $data = "path to file checked by logging into WINSCP and looking at properties. Is a .txt file"; echo $data; while ($buf = fread($stream,4096)) { $data .= $buf; } fclose($stream); } } } Basically shouldnt this display the contents of the file to me? On screen I just get Quote okay: logged in... should be ok What is my error? Thanks Dear friends, I wrote a code to extract a text from a pages of a site like this: ************ $handle = @fopen($url, 'r'); $contents = ''; if ($handle) { while (!feof($handle)) { $contents .= fread($handle, 8192); } ************ This code is working properly with many pages just pages those are began with the following tags: ************ ... <body> <form name="aspnetForm" method="post" action="ViewContents.aspx?Contract=cms_Contents_I_News&amp%3br=721192" id="aspnetForm"> <input type="hidden" name="__VIEWSTATE" id=" __VIEWSTATE" value="" /> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwL+raDpAgL3qPzdCwLyp86ZD5mqDm6ZnRL/pRerpqyobvzmy5LB" /> ************ The result of function read() in variable $content is not full. It's just theme of the page without main content. I mean there isn't the story related to id of page (e.g. 721192) in the $content. Why? Is the above <form> affected the result? What can i do? Please help me. I found a script online that I am trying to get working. It was giving a 500 error from the get go and I've pinpointed it to the $data = fread() line. Does anyone know why? <?php $file = "../../media/v_360.m4v"; $filesize = filesize($file); $offset = 0; $length = $filesize; if (isset($_SERVER['HTTP_RANGE'])) { // if the HTTP_RANGE header is set we're dealing with partial content $partialContent = true; // find the requested range // this might be too simplistic, apparently the client can request // multiple ranges, which can become pretty complex, so ignore it for now preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); $length = intval($matches[2]) - $offset; } else { $partialContent = false; } $file = fopen($file, 'r'); // seek to the requested offset, this is 0 if it's not a partial content request fseek($file, $offset); $data = fread($file, $length); /* fclose($file); if ($partialContent) { // output the right headers for partial content header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize); } // output the regular HTTP headers header('Content-Type: ' . $ctype); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Accept-Ranges: bytes'); // don't forget to send the data too print($data); */ ?> Its trying to read a 60mb file. Do you think it is timing out and that is causing the error? 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> 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. 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 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; } } 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. 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. |