file_get_contents 和 foreach 循环 - 仅插入最后一条记录
我正在编写脚本,该脚本从表单中的网址中提取电子邮件并将其添加到数据库中。 我有两个问题:
1.只有来自最后一个网址的电子邮件才会添加到数据库中。
2.如何向数据库添加电子邮件?;) 当我使用变量 $email 或 $email[0] 时,我在表中收到一个空字段或数组。我通过使用 foreach 循环避免了这种情况,但我希望您能找到一些更方便的解决方案。
$linki = explode("\n", $_POST['linki']);
$db = new mysqli('localhost', 'root', 'root', 'linki');
if (mysqli_connect_errno()) {
echo 'error: ';
exit;
}
foreach ( $linki as $link) {
$przetwarzany_url = file_get_contents($link);
preg_match( "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $przetwarzany_url, $email);//email
$query = "INSERT INTO urle set adres = '$email' "; //this query doens't add the email to db
$result = $db->query($query);
}
这是我的 print_r($link); 的输出在 foreach 循环中:
firsturl.com array(0) { } secondurl.com array(1) { [0]=> string(17) "[email protected]" }
I'm writing script, which extract emails from the urls in the form and add them to the database.
I've got two problems:
1.Only the email from last url is added to the database.
2.How can I add an email to the database?;) When I use variable $email or $email[0] I receive in the table an empty field or Array. I have avoid this by using foreach loop, but I hope you'll find out some more convenient solution.
$linki = explode("\n", $_POST['linki']);
$db = new mysqli('localhost', 'root', 'root', 'linki');
if (mysqli_connect_errno()) {
echo 'error: ';
exit;
}
foreach ( $linki as $link) {
$przetwarzany_url = file_get_contents($link);
preg_match( "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $przetwarzany_url, $email);//email
$query = "INSERT INTO urle set adres = '$email' "; //this query doens't add the email to db
$result = $db->query($query);
}
Here is my output from print_r($link); in the foreach loop:
firsturl.com array(0) { } secondurl.com array(1) { [0]=> string(17) "[email protected]" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有很多失败点:
$link
是否有效 - 因为它来自网络表单,所以没有什么可以阻止恶意用户输入“http://childporn”之类的内容.com' 等,然后您的脚本将尝试获取其中的内容。file_get_contents()
是否实际返回了任何内容,而是在代码中添加检查来处理所有这些问题,您可能会发现为什么只有一些插入成功。
You've got many points of failure:
$link
is valid - since it's coming from a web form, nothing stops a malicious user from entering things like 'http://childporn.com' and the like, which your script will then try to fetch the contents of.file_get_contents()
actually returned anythingadd checks to your code to handle all of these issues, and you'll probably find out why you're only get some inserts to succeed.